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(api): reject non-object conversation settings (#108162)

Paul D'Ambrad76a59d758ff
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 96a78cf591c2..77c931fc8c69 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -684,6 +684,12 @@ export type ProjectBackwardCompatApiProductIntentsItem = {
updated_at?: string
}
+/**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+export type ProjectBackwardCompatApiConversationsSettings = { [key: string]: unknown } | null
+
export type ProjectBackwardCompatApiManagedViewsets = { [key: string]: boolean }
/**
@@ -2703,7 +2709,11 @@ export interface ProjectBackwardCompatApi {
* @nullable
*/
conversations_enabled?: boolean | null
- conversations_settings?: unknown
+ /**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+ conversations_settings?: ProjectBackwardCompatApiConversationsSettings
logs_settings?: unknown
/** @nullable */
proactive_tasks_enabled?: boolean | null
@@ -2779,6 +2789,12 @@ export type PatchedProjectBackwardCompatApiProductIntentsItem = {
updated_at?: string
}
+/**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+export type PatchedProjectBackwardCompatApiConversationsSettings = { [key: string]: unknown } | null
+
export type PatchedProjectBackwardCompatApiManagedViewsets = { [key: string]: boolean }
/**
@@ -3572,7 +3588,11 @@ export interface PatchedProjectBackwardCompatApi {
* @nullable
*/
conversations_enabled?: boolean | null
- conversations_settings?: unknown
+ /**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+ conversations_settings?: PatchedProjectBackwardCompatApiConversationsSettings
logs_settings?: unknown
/** @nullable */
proactive_tasks_enabled?: boolean | null
diff --git a/posthog/api/product_enablement.py b/posthog/api/product_enablement.py
index 06b48998cdd5..1be49edd53d9 100644
--- a/posthog/api/product_enablement.py
+++ b/posthog/api/product_enablement.py
@@ -22,7 +22,7 @@ from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.team import TEAM_CONFIG_ADMIN_FIELDS_SET
+from posthog.api.team import TEAM_CONFIG_ADMIN_FIELDS_SET, conversations_settings_as_dict
from posthog.helpers.impersonation import is_impersonated
from posthog.models import OrganizationMembership, User
from posthog.models.activity_logging.activity_log import Detail, dict_changes_between, log_activity
@@ -63,7 +63,7 @@ def _enable_conversations(team: Team, touched: set[str]) -> str:
touched.add("conversations_enabled")
# Mirror handle_conversations_token_on_update (posthog/api/team.py): mint a widget
# token but leave the widget off — tickets need a connected channel (the report CTA).
- settings = dict(team.conversations_settings or {})
+ settings = dict(conversations_settings_as_dict(team.conversations_settings))
if not settings.get("widget_public_token"):
settings["widget_public_token"] = secrets.token_urlsafe(32)
team.conversations_settings = settings
diff --git a/posthog/api/project.py b/posthog/api/project.py
index a890fbf106e2..6d285deb6cd5 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -33,6 +33,7 @@ from posthog.api.team import (
TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS,
TEAM_CONFIG_FIELDS,
TEAM_CONFIG_MEMBER_FIELDS_SET,
+ ConversationsSettingsField,
EvaluationContextSuggestionRequestSerializer,
EvaluationContextSuggestionResponseSerializer,
EventIngestionRestrictionSerializer,
@@ -46,6 +47,7 @@ from posthog.api.team import (
TeamWorkflowsConfigSerializer,
_default_data_color_theme_id,
_format_serializer_errors,
+ conversations_settings_as_dict,
get_or_mint_live_events_token,
handle_conversations_token_on_update,
handle_experiments_config,
@@ -637,6 +639,11 @@ class ProjectBackwardCompatSerializer(
customer_analytics_config = TeamCustomerAnalyticsConfigSerializer(required=False) # Compat with TeamSerializer
workflows_config = TeamWorkflowsConfigSerializer(required=False) # Compat with TeamSerializer
feature_flag_policy_config = TeamFeatureFlagPolicyConfigSerializer(required=False) # Compat with TeamSerializer
+ conversations_settings = ConversationsSettingsField(
+ required=False,
+ allow_null=True,
+ help_text="Settings for Conversations. Must be a JSON object or null.",
+ )
# No `default` on purpose: a default value would be auto-injected into every create payload, which trips the
# admin-only-fields-on-creation gate in validate_team_attrs and blocks members allowed to create projects.
base_currency = serializers.ChoiceField(choices=CURRENCY_CODE_CHOICES, required=False) # Compat with TeamSerializer
@@ -656,6 +663,8 @@ class ProjectBackwardCompatSerializer(
def validate_conversations_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("Conversation settings must be an object or null.")
# Filter out None values from widget_domains if present
if "widget_domains" in value and value["widget_domains"] is not None:
value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
@@ -1300,7 +1309,7 @@ class ProjectBackwardCompatSerializer(
# Merge conversations_settings with existing values, unless explicitly clearing with null
if "conversations_settings" in validated_data and validated_data["conversations_settings"] is not None:
- existing_settings = team.conversations_settings or {}
+ existing_settings = conversations_settings_as_dict(team.conversations_settings)
new_settings = validated_data["conversations_settings"]
validated_data["conversations_settings"] = {**existing_settings, **new_settings}
diff --git a/posthog/api/team.py b/posthog/api/team.py
index e6ec7462b42f..46463ef9d274 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1363,6 +1363,11 @@ def _custom_logs_retention_enabled(serializer: serializers.BaseSerializer, team:
)
+@extend_schema_field(OpenApiTypes.OBJECT)
+class ConversationsSettingsField(serializers.JSONField):
+ pass
+
+
class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):
instance: Team | None
_group_types_cache: list[dict[str, Any]] | None = None
@@ -1386,6 +1391,11 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
workflows_config = TeamWorkflowsConfigSerializer(required=False)
feature_flag_policy_config = TeamFeatureFlagPolicyConfigSerializer(required=False)
base_currency = serializers.ChoiceField(choices=CURRENCY_CODE_CHOICES, default=DEFAULT_CURRENCY)
+ conversations_settings = ConversationsSettingsField(
+ required=False,
+ allow_null=True,
+ help_text="Settings for Conversations. Must be a JSON object or null.",
+ )
heatmaps_screenshot_secret = serializers.SerializerMethodField(
help_text=(
@@ -1913,6 +1923,8 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
def validate_conversations_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("Conversation settings must be an object or null.")
# Filter out None values from widget_domains if present
if "widget_domains" in value and value["widget_domains"] is not None:
value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
@@ -2327,7 +2339,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
# Merge conversations_settings with existing values, unless explicitly clearing with null
if "conversations_settings" in validated_data and validated_data["conversations_settings"] is not None:
- existing_settings = instance.conversations_settings or {}
+ existing_settings = conversations_settings_as_dict(instance.conversations_settings)
new_settings = validated_data["conversations_settings"]
validated_data["conversations_settings"] = {**existing_settings, **new_settings}
@@ -3163,13 +3175,22 @@ class ProjectEnvironmentsViewSet(TeamViewSet):
)
+def conversations_settings_as_dict(value: object) -> dict[str, Any]:
+ """Coerce a conversations_settings value to a dict for merging or diffing.
+
+ A row written before validation required an object/null can hold a stray array or scalar;
+ treat it as empty rather than raising.
+ """
+ return value if isinstance(value, dict) else {}
+
+
def report_conversations_settings_changes(user: User, before_settings: dict | None, team: Team) -> None:
"""Fire one "support setting changed" event per changed conversations_settings key.
Shared by the team and project serializers — both endpoints can PATCH the settings.
"""
- old_settings = before_settings or {}
- new_settings = team.conversations_settings or {}
+ old_settings = conversations_settings_as_dict(before_settings)
+ new_settings = conversations_settings_as_dict(team.conversations_settings)
changed_keys = sorted(
k for k in old_settings.keys() | new_settings.keys() if old_settings.get(k) != new_settings.get(k)
)
@@ -3186,7 +3207,7 @@ def report_conversations_settings_changes(user: User, before_settings: dict | No
def handle_conversations_token_on_update(
validated_data: dict[str, Any],
current_conversations_enabled: bool | None,
- current_conversations_settings: dict | None,
+ current_conversations_settings: object,
) -> dict[str, Any]:
"""Auto-generate/clear conversations widget token based on conversations_enabled changes."""
if "conversations_enabled" not in validated_data:
@@ -3195,15 +3216,17 @@ def handle_conversations_token_on_update(
is_enabling = validated_data["conversations_enabled"] and not current_conversations_enabled
is_disabling = not validated_data["conversations_enabled"] and current_conversations_enabled
+ stored_settings = conversations_settings_as_dict(current_conversations_settings)
+
if is_enabling:
# Check if token already exists in current DB state (not user input, which is stripped)
- has_token = current_conversations_settings and current_conversations_settings.get("widget_public_token")
+ has_token = stored_settings.get("widget_public_token")
if not has_token:
- conv_settings = dict(validated_data.get("conversations_settings") or current_conversations_settings or {})
+ conv_settings = dict(validated_data.get("conversations_settings") or stored_settings)
conv_settings["widget_public_token"] = secrets.token_urlsafe(32)
validated_data["conversations_settings"] = conv_settings
elif is_disabling:
- conv_settings = dict(validated_data.get("conversations_settings") or current_conversations_settings or {})
+ conv_settings = dict(validated_data.get("conversations_settings") or stored_settings)
conv_settings["widget_public_token"] = None
validated_data["conversations_settings"] = conv_settings
diff --git a/posthog/api/test/test_product_enablement.py b/posthog/api/test/test_product_enablement.py
index a805141e229e..aff9b557c2fb 100644
--- a/posthog/api/test/test_product_enablement.py
+++ b/posthog/api/test/test_product_enablement.py
@@ -1,5 +1,6 @@
from posthog.test.base import APIBaseTest
+from parameterized import parameterized
from rest_framework import status
from posthog.models import OrganizationMembership
@@ -50,7 +51,11 @@ class TestProductEnablementAPI(APIBaseTest):
self.team.refresh_from_db()
self.assertTrue(self.team.autocapture_exceptions_opt_in)
- def test_enables_conversations_mints_token_but_leaves_widget_off(self):
+ @parameterized.expand([(None,), ("legacy string",), (1,)])
+ def test_enables_conversations_mints_token_but_leaves_widget_off(self, stored_settings):
+ self.team.conversations_settings = stored_settings
+ self.team.save()
+
response = self._enable(["conversations"])
self.assertEqual(response.json(), {"results": {"conversations": "enabled"}})
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index b664d89f6b89..054c4cb608f3 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1909,6 +1909,19 @@ def team_api_test_factory():
assert settings["widget_greeting_text"] == "Hello!"
assert settings["widget_color"] == "#ff0000"
+ @parameterized.expand([(["legacy", "list"],), ("legacy string",), (1,)])
+ def test_conversations_settings_merges_with_legacy_non_object_existing(self, legacy_value):
+ # Rows written before validation required an object/null can hold a stray
+ # array or scalar. A later object update must not 500 trying to merge it.
+ self.team.conversations_settings = legacy_value
+ self.team.save()
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"conversations_settings": {"widget_color": "#ff0000"}},
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["conversations_settings"]["widget_color"] == "#ff0000"
+
def test_conversations_settings_change_reports_event_per_setting(self):
with patch("posthog.api.team.report_user_action") as mock_report:
response = self.client.patch(
@@ -2071,9 +2084,10 @@ def team_api_test_factory():
)
assert bad.status_code == status.HTTP_400_BAD_REQUEST
- def test_enabling_conversations_auto_generates_token(self):
+ @parameterized.expand([(None,), ("legacy string",), (["legacy", "list"],)])
+ def test_enabling_conversations_auto_generates_token(self, stored_settings):
self.team.conversations_enabled = False
- self.team.conversations_settings = None
+ self.team.conversations_settings = stored_settings
self.team.save()
response = self.client.patch("/api/environments/@current/", {"conversations_enabled": True})
@@ -2092,16 +2106,23 @@ def team_api_test_factory():
assert response.status_code == status.HTTP_200_OK
assert response.json()["conversations_settings"]["widget_public_token"] == "existing_token_123"
- def test_disabling_conversations_clears_token(self):
+ @parameterized.expand(
+ [
+ (
+ {"widget_public_token": "some_token", "widget_color": "#123456"},
+ {"widget_public_token": None, "widget_color": "#123456"},
+ ),
+ (1, {"widget_public_token": None}),
+ ]
+ )
+ def test_disabling_conversations_clears_token(self, stored_settings, expected_settings):
self.team.conversations_enabled = True
- self.team.conversations_settings = {"widget_public_token": "some_token", "widget_color": "#123456"}
+ self.team.conversations_settings = stored_settings
self.team.save()
response = self.client.patch("/api/environments/@current/", {"conversations_enabled": False})
assert response.status_code == status.HTTP_200_OK
- settings = response.json()["conversations_settings"]
- assert settings["widget_public_token"] is None
- assert settings["widget_color"] == "#123456"
+ assert response.json()["conversations_settings"] == expected_settings
def test_generate_conversations_public_token(self):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
@@ -4056,6 +4077,20 @@ _TOO_MANY_WILDCARDS = ["https://*.*.*.*.*.*.example.com"]
class TestTeamSerializerValidationNoDB(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (serializer, value)
+ for serializer in (TeamSerializer, ProjectBackwardCompatSerializer)
+ for value in (list[object](), "text", 1, True)
+ ]
+ )
+ def test_conversations_settings_requires_an_object(
+ self, serializer_class: type[TeamSerializer] | type[ProjectBackwardCompatSerializer], value: object
+ ) -> None:
+ serializer = serializer_class(data={"conversations_settings": value}, partial=True)
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("conversations_settings", serializer.errors)
+
@parameterized.expand([(None,), (True,), (123,), ([],), ({},), ("a" * 201,)])
def test_invalid_logs_json_attribute_key(self, key):
self._assert_field_error(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c6d9cd79d106..4a662ca32e02 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79023,6 +79023,12 @@ export namespace Schemas {
updated_at?: string;
};
+ /**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+ export type PatchedProjectBackwardCompatConversationsSettings = { [key: string]: unknown } | null;
+
export type PatchedProjectBackwardCompatManagedViewsets = {[key: string]: boolean};
/**
@@ -79937,7 +79943,11 @@ export namespace Schemas {
* @nullable
*/
conversations_enabled?: boolean | null;
- conversations_settings?: unknown;
+ /**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+ conversations_settings?: PatchedProjectBackwardCompatConversationsSettings;
logs_settings?: unknown;
/** @nullable */
proactive_tasks_enabled?: boolean | null;
@@ -84090,6 +84100,12 @@ export namespace Schemas {
updated_at?: string;
};
+ /**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+ export type ProjectBackwardCompatConversationsSettings = { [key: string]: unknown } | null;
+
export type ProjectBackwardCompatManagedViewsets = {[key: string]: boolean};
/**
@@ -84883,7 +84899,11 @@ export namespace Schemas {
* @nullable
*/
conversations_enabled?: boolean | null;
- conversations_settings?: unknown;
+ /**
+ * Settings for Conversations. Must be a JSON object or null.
+ * @nullable
+ */
+ conversations_settings?: ProjectBackwardCompatConversationsSettings;
logs_settings?: unknown;
/** @nullable */
proactive_tasks_enabled?: boolean | null;
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index de73416e4db5..5da3f85e3f38 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -246,7 +246,10 @@ export const OrganizationsProjectsCreateBody = () => zod
.boolean()
.nullish()
.describe('Enables the customer conversations \/ live chat product for this project.'),
- conversations_settings: zod.unknown().optional(),
+ conversations_settings: zod
+ .record(zod.string(), zod.unknown())
+ .nullish()
+ .describe('Settings for Conversations. Must be a JSON object or null.'),
logs_settings: zod.unknown().optional(),
proactive_tasks_enabled: zod.boolean().nullish(),
revenue_analytics_config: zod
@@ -2950,7 +2953,10 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod
.boolean()
.nullish()
.describe('Enables the customer conversations \/ live chat product for this project.'),
- conversations_settings: zod.unknown().optional(),
+ conversations_settings: zod
+ .record(zod.string(), zod.unknown())
+ .nullish()
+ .describe('Settings for Conversations. Must be a JSON object or null.'),
logs_settings: zod.unknown().optional(),
proactive_tasks_enabled: zod.boolean().nullish(),
revenue_analytics_config: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
index f213f28db23a..a0c3d2992ac1 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
@@ -279,7 +279,21 @@
],
"description": "Enables the customer conversations / live chat product for this project."
},
- "conversations_settings": {},
+ "conversations_settings": {
+ "anyOf": [
+ {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Settings for Conversations. Must be a JSON object or null."
+ },
"cookieless_server_hash_mode": {
"anyOf": [
{