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): run the full conversations settings checks on the project endpoint (#117123)

Paul D'Ambra3664a2995f86
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 2b2397626ca5..d77aa8f75e1d 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -34,7 +34,7 @@ from posthog.api.team.conversations_settings import (
ConversationsSettingsField,
merge_conversations_settings_locked,
report_conversations_settings_changes,
- strip_managed_conversations_settings,
+ validate_conversations_settings,
)
from posthog.api.team.integration_config import (
TeamLogsConfigSerializer,
@@ -691,22 +691,14 @@ class ProjectBackwardCompatSerializer(
def validate_conversations_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
- strip_managed_conversations_settings(value)
- # 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]
- validate_authorized_url_wildcards(value["widget_domains"])
- from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
- from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
-
# conversations_settings lives on the passthrough Team, not on Project, so a partial
# update that omits docs_source still normalizes against the saved source.
existing = self.instance.passthrough_team.conversations_settings if self.instance is not None else None
- validate_playbook_conversations_settings(value, existing=existing if isinstance(existing, dict) else None)
- validate_ai_context_conversations_settings(
- value, team_id=self.instance.passthrough_team.id if self.instance is not None else None
+ return validate_conversations_settings(
+ value,
+ existing=existing if isinstance(existing, dict) else None,
+ team_id=self.instance.passthrough_team.id if self.instance is not None else None,
)
- return value
class Meta:
model = Project
diff --git a/posthog/api/team/conversations_settings.py b/posthog/api/team/conversations_settings.py
index 5d1b70389798..7be00087f255 100644
--- a/posthog/api/team/conversations_settings.py
+++ b/posthog/api/team/conversations_settings.py
@@ -9,6 +9,7 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
+from posthog.api.utils import validate_authorized_url_wildcards
from posthog.event_usage import report_user_action
from posthog.models import Team, User
@@ -169,3 +170,131 @@ def handle_conversations_token_on_update(
validated_data["conversations_settings"] = conv_settings
return validated_data
+
+
+VALID_CONVERSATIONS_CHANNELS = {"widget", "email", "slack", "teams", "github"}
+VALID_AI_REPLY_MODES = {"private_note", "bot_reply"}
+VALID_AI_REPLY_TICKET_TYPES = {"how_to", "diagnostic", "account_billing"}
+# Only how_to replies may be published to the ticket author. diagnostic/account_billing
+# draw on project data (events, persons, recordings, logs) and must stay private notes —
+# there's no per-author authorization that the customer is entitled to that data.
+BOT_REPLY_TICKET_TYPES = {"how_to"}
+
+
+def validate_conversations_settings(
+ value: dict[str, Any], existing: dict[str, Any] | None, team_id: int | None
+) -> dict[str, Any]:
+ """Run every check a conversations_settings write must pass, shared by the team and project serializers.
+
+ `existing` is the team's currently stored conversations_settings (or None), used to skip
+ unchanged values and for merge-aware playbook validation. `team_id` is the team whose AI context gets validated.
+ """
+ strip_managed_conversations_settings(value)
+ # The web app sends back every stored setting on each save. A value stored before a check
+ # existed must not block an unrelated save or get cut down, so only changed values get checked.
+ stored = existing or {}
+ unchanged = {key: item for key, item in value.items() if key in stored and stored[key] == item}
+ for key in unchanged:
+ del value[key]
+ # 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]
+ validate_authorized_url_wildcards(value["widget_domains"])
+ # Normalize multi-channel list: must be a list of non-empty strings, deduped, capped at 50
+ if "slack_channel_ids" in value:
+ raw = value.get("slack_channel_ids")
+ if isinstance(raw, list):
+ cleaned: list[str] = []
+ seen: set[str] = set()
+ for item in raw:
+ if isinstance(item, str) and item and item not in seen:
+ seen.add(item)
+ cleaned.append(item)
+ value["slack_channel_ids"] = cleaned[:50]
+ elif raw is not None:
+ # Drop a malformed value instead of rejecting the save, but keep an explicit
+ # null so a clearing PATCH still overwrites the stored list (see
+ # merge_conversations_settings, which only replaces keys present here).
+ value.pop("slack_channel_ids", None)
+ icon_url = value.get("slack_bot_icon_url")
+ if icon_url is not None:
+ if not isinstance(icon_url, str):
+ raise serializers.ValidationError({"slack_bot_icon_url": "Must be a string."})
+ icon_url = icon_url.strip()
+ value["slack_bot_icon_url"] = icon_url or None
+ if icon_url and not icon_url.startswith("https://"):
+ raise serializers.ValidationError({"slack_bot_icon_url": "Must be an HTTPS URL."})
+ display_name = value.get("slack_bot_display_name")
+ if display_name is not None:
+ if not isinstance(display_name, str):
+ raise serializers.ValidationError({"slack_bot_display_name": "Must be a string."})
+ display_name = display_name.strip()
+ value["slack_bot_display_name"] = display_name or None
+ if display_name and (len(display_name) > 200 or any(ord(c) < 32 for c in display_name)):
+ raise serializers.ValidationError(
+ {"slack_bot_display_name": "Must be 200 characters or fewer with no control characters."}
+ )
+ for toggle_key in ("slack_notify_on_join", "slack_notify_on_leave", "slack_nudge_enabled"):
+ if toggle_key in value:
+ value[toggle_key] = bool(value[toggle_key])
+ if "slack_alert_channel_id" in value:
+ alert_channel = value.get("slack_alert_channel_id")
+ if alert_channel is None:
+ value["slack_alert_channel_id"] = None
+ elif isinstance(alert_channel, str):
+ value["slack_alert_channel_id"] = alert_channel.strip() or None
+ else:
+ raise serializers.ValidationError({"slack_alert_channel_id": "Must be a string."})
+ # AI resolution channels: list of valid channel strings or null
+ if "ai_resolution_channels" in value:
+ channels = value.get("ai_resolution_channels")
+ if channels is None:
+ pass
+ elif isinstance(channels, list):
+ invalid = [c for c in channels if not isinstance(c, str) or c not in VALID_CONVERSATIONS_CHANNELS]
+ if invalid:
+ raise serializers.ValidationError(
+ {
+ "ai_resolution_channels": f"Invalid channel(s): {', '.join(str(c) for c in invalid)}. "
+ f"Valid options: {', '.join(sorted(VALID_CONVERSATIONS_CHANNELS))}."
+ }
+ )
+ value["ai_resolution_channels"] = channels
+ else:
+ raise serializers.ValidationError({"ai_resolution_channels": "Must be a list of channel names or null."})
+ # AI reply modes: { channel: { ticket_type: mode } } or null
+ if "ai_reply_modes" in value:
+ modes = value.get("ai_reply_modes")
+ if modes is None:
+ pass
+ elif isinstance(modes, dict):
+ cleaned_modes: dict[str, dict[str, str]] = {}
+ for ch, type_map in modes.items():
+ if ch not in VALID_CONVERSATIONS_CHANNELS or not isinstance(type_map, dict):
+ continue
+ cleaned_map: dict[str, str] = {}
+ for tt, mode in type_map.items():
+ if (
+ tt not in VALID_AI_REPLY_TICKET_TYPES
+ or not isinstance(mode, str)
+ or mode not in VALID_AI_REPLY_MODES
+ ):
+ continue
+ # Demote bot_reply to private_note for ticket types that may never be
+ # published (diagnostic/account_billing). Coerce rather than reject so a
+ # stale value doesn't block unrelated settings saves.
+ if mode == "bot_reply" and tt not in BOT_REPLY_TICKET_TYPES:
+ mode = "private_note"
+ cleaned_map[tt] = mode
+ if cleaned_map:
+ cleaned_modes[ch] = cleaned_map
+ value["ai_reply_modes"] = cleaned_modes
+ else:
+ raise serializers.ValidationError({"ai_reply_modes": "Must be an object or null."})
+ from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
+ from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
+
+ validate_playbook_conversations_settings(value, existing=existing)
+ validate_ai_context_conversations_settings(value, team_id=team_id)
+ value.update(unchanged)
+ return value
diff --git a/posthog/api/team/team_serializer.py b/posthog/api/team/team_serializer.py
index f1d81f05d302..b79196cc2b83 100644
--- a/posthog/api/team/team_serializer.py
+++ b/posthog/api/team/team_serializer.py
@@ -640,113 +640,12 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
def validate_conversations_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
- conversations_settings.strip_managed_conversations_settings(value)
- # 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]
- validate_authorized_url_wildcards(value["widget_domains"])
- # Normalize multi-channel list: must be a list of non-empty strings, deduped, capped at 50
- if "slack_channel_ids" in value:
- raw = value.get("slack_channel_ids")
- if isinstance(raw, list):
- cleaned: list[str] = []
- seen: set[str] = set()
- for item in raw:
- if isinstance(item, str) and item and item not in seen:
- seen.add(item)
- cleaned.append(item)
- value["slack_channel_ids"] = cleaned[:50]
- else:
- value.pop("slack_channel_ids", None)
- icon_url = value.get("slack_bot_icon_url")
- if icon_url is not None:
- if not isinstance(icon_url, str):
- raise serializers.ValidationError({"slack_bot_icon_url": "Must be a string."})
- icon_url = icon_url.strip()
- value["slack_bot_icon_url"] = icon_url or None
- if icon_url and not icon_url.startswith("https://"):
- raise serializers.ValidationError({"slack_bot_icon_url": "Must be an HTTPS URL."})
- display_name = value.get("slack_bot_display_name")
- if display_name is not None:
- if not isinstance(display_name, str):
- raise serializers.ValidationError({"slack_bot_display_name": "Must be a string."})
- display_name = display_name.strip()
- value["slack_bot_display_name"] = display_name or None
- if display_name and (len(display_name) > 200 or any(ord(c) < 32 for c in display_name)):
- raise serializers.ValidationError(
- {"slack_bot_display_name": "Must be 200 characters or fewer with no control characters."}
- )
- for toggle_key in ("slack_notify_on_join", "slack_notify_on_leave", "slack_nudge_enabled"):
- if toggle_key in value:
- value[toggle_key] = bool(value[toggle_key])
- if "slack_alert_channel_id" in value:
- alert_channel = value.get("slack_alert_channel_id")
- if alert_channel is None:
- value["slack_alert_channel_id"] = None
- elif isinstance(alert_channel, str):
- value["slack_alert_channel_id"] = alert_channel.strip() or None
- else:
- raise serializers.ValidationError({"slack_alert_channel_id": "Must be a string."})
- # AI resolution channels: list of valid channel strings or null
- VALID_CHANNELS = {"widget", "email", "slack", "teams", "github"}
- if "ai_resolution_channels" in value:
- channels = value.get("ai_resolution_channels")
- if channels is None:
- pass
- elif isinstance(channels, list):
- invalid = [c for c in channels if not isinstance(c, str) or c not in VALID_CHANNELS]
- if invalid:
- raise serializers.ValidationError(
- {
- "ai_resolution_channels": f"Invalid channel(s): {', '.join(str(c) for c in invalid)}. "
- f"Valid options: {', '.join(sorted(VALID_CHANNELS))}."
- }
- )
- value["ai_resolution_channels"] = channels
- else:
- raise serializers.ValidationError(
- {"ai_resolution_channels": "Must be a list of channel names or null."}
- )
- # AI reply modes: { channel: { ticket_type: mode } } or null
- VALID_REPLY_MODES = {"private_note", "bot_reply"}
- VALID_TICKET_TYPES = {"how_to", "diagnostic", "account_billing"}
- # Only how_to replies may be published to the ticket author. diagnostic/account_billing
- # draw on project data (events, persons, recordings, logs) and must stay private notes —
- # there's no per-author authorization that the customer is entitled to that data.
- BOT_REPLY_TICKET_TYPES = {"how_to"}
- if "ai_reply_modes" in value:
- modes = value.get("ai_reply_modes")
- if modes is None:
- pass
- elif isinstance(modes, dict):
- cleaned_modes: dict[str, dict[str, str]] = {}
- for ch, type_map in modes.items():
- if ch not in VALID_CHANNELS or not isinstance(type_map, dict):
- continue
- cleaned_map: dict[str, str] = {}
- for tt, mode in type_map.items():
- if tt not in VALID_TICKET_TYPES or mode not in VALID_REPLY_MODES:
- continue
- # Demote bot_reply to private_note for ticket types that may never be
- # published (diagnostic/account_billing). Coerce rather than reject so a
- # stale value doesn't block unrelated settings saves.
- if mode == "bot_reply" and tt not in BOT_REPLY_TICKET_TYPES:
- mode = "private_note"
- cleaned_map[tt] = mode
- if cleaned_map:
- cleaned_modes[ch] = cleaned_map
- value["ai_reply_modes"] = cleaned_modes
- else:
- raise serializers.ValidationError({"ai_reply_modes": "Must be an object or null."})
- from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
- from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
-
existing = getattr(self.instance, "conversations_settings", None) if self.instance is not None else None
- validate_playbook_conversations_settings(value, existing=existing if isinstance(existing, dict) else None)
- validate_ai_context_conversations_settings(
- value, team_id=self.instance.id if self.instance is not None else None
+ return conversations_settings.validate_conversations_settings(
+ value,
+ existing=existing if isinstance(existing, dict) else None,
+ team_id=self.instance.id if self.instance is not None else None,
)
- return value
def validate_receive_org_level_activity_logs(self, value: bool | None) -> bool | None:
if value is None:
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 4ee92edf3c14..5454fe354700 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -53,6 +53,14 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
self.assertNotIn(field_name, serializer.fields)
self.assertFalse(any(field.read_only for field in serializer.fields.values()))
+ def test_conversations_settings_ai_reply_modes_requires_an_object(self):
+ # Checks that the real PATCH request runs the shared validator. test_team.py covers its other cases.
+ response = self.client.patch(
+ f"/api/projects/{self.project.id}/",
+ {"conversations_settings": {"ai_reply_modes": ["not", "a", "dict"]}},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def test_projects_outside_personal_api_key_scoped_organizations_not_listed(self):
other_org, _, team_in_other_org = Organization.objects.bootstrap(self.user)
personal_api_key = generate_random_token_personal()
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 8de8a4b2f0bc..2d19b9b2cd8a 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -15,7 +15,7 @@ from django.test.client import RequestFactory
from django.utils import timezone
from parameterized import parameterized
-from rest_framework import status, test
+from rest_framework import serializers, status, test
from posthog.api.project import ProjectBackwardCompatSerializer, log_activity
from posthog.api.team.conversations_settings import handle_conversations_token_on_update, merge_conversations_settings
@@ -4248,6 +4248,20 @@ class TestTeamAdminFieldAuthorization(APIBaseTest):
_TOO_MANY_WILDCARDS = ["https://*.*.*.*.*.*.example.com"]
+def _sixty_channel_ids() -> list[str]:
+ return [f"C{i}" for i in range(60)]
+
+
+def _validate_conversations_settings(
+ serializer_class: type[TeamSerializer] | type[ProjectBackwardCompatSerializer],
+ stored: dict[str, object] | None,
+ submitted: dict[str, object],
+) -> dict[str, object] | None:
+ team = Team(conversations_settings=stored)
+ instance = team if serializer_class is TeamSerializer else MagicMock(passthrough_team=team)
+ return serializer_class(instance=instance).validate_conversations_settings(submitted)
+
+
class TestTeamSerializerValidationNoDB(SimpleTestCase):
@parameterized.expand([(None,), ({},), ({"widget_color": "#123456"},)])
def test_conversations_settings_clear_without_managed_values(self, existing: dict[str, str] | None) -> None:
@@ -4345,6 +4359,134 @@ class TestTeamSerializerValidationNoDB(SimpleTestCase):
self.assertFalse(serializer.is_valid())
self.assertIn("conversations_settings", serializer.errors)
+ @parameterized.expand(
+ [
+ (serializer, name, ai_reply_modes, expected_cleaned)
+ for serializer in (TeamSerializer, ProjectBackwardCompatSerializer)
+ for name, ai_reply_modes, expected_cleaned in (
+ ("non_string_mode_is_dropped", {"slack": {"how_to": ["bot_reply"]}}, {}),
+ (
+ "bot_reply_for_diagnostic_becomes_private_note",
+ {"slack": {"diagnostic": "bot_reply"}},
+ {"slack": {"diagnostic": "private_note"}},
+ ),
+ )
+ ]
+ )
+ def test_conversations_settings_ai_reply_modes_cleans_up_values(
+ self,
+ serializer_class: type[TeamSerializer] | type[ProjectBackwardCompatSerializer],
+ _name: str,
+ ai_reply_modes: dict,
+ expected_cleaned: dict,
+ ) -> None:
+ # Calls the field validator directly, like test_normalize_logs_json_attribute_key below:
+ # building a full serializer.is_valid() call needs view/request context neither
+ # serializer has outside a real request, which this no-DB test does not set up.
+ cleaned = serializer_class().validate_conversations_settings({"ai_reply_modes": ai_reply_modes})
+ assert cleaned is not None
+ self.assertEqual(cleaned["ai_reply_modes"], expected_cleaned)
+
+ @parameterized.expand(
+ [
+ (serializer, name, stored, submitted)
+ for serializer in (TeamSerializer, ProjectBackwardCompatSerializer)
+ for name, stored, submitted in (
+ ("ai_reply_modes_must_be_an_object", None, {"ai_reply_modes": ["not", "a", "dict"]}),
+ (
+ "changed_ai_reply_modes_must_be_an_object",
+ {"ai_reply_modes": ["old"]},
+ {"ai_reply_modes": ["new"]},
+ ),
+ (
+ "changed_display_name_over_200_characters",
+ {"slack_bot_display_name": "a" * 201},
+ {"slack_bot_display_name": "b" * 201},
+ ),
+ )
+ ]
+ )
+ def test_conversations_settings_rejects_invalid_values(
+ self,
+ serializer_class: type[TeamSerializer] | type[ProjectBackwardCompatSerializer],
+ _name: str,
+ stored: dict[str, object] | None,
+ submitted: dict[str, object],
+ ) -> None:
+ with self.assertRaises(serializers.ValidationError):
+ _validate_conversations_settings(serializer_class, stored, submitted)
+
+ @parameterized.expand(
+ [
+ (serializer, name, stored, submitted, expected_cleaned)
+ for serializer in (TeamSerializer, ProjectBackwardCompatSerializer)
+ for name, stored, submitted, expected_cleaned in (
+ (
+ "dedupes_and_caps_at_50",
+ None,
+ {"slack_channel_ids": ["a", "a", "b"] + [f"c{i}" for i in range(50)]},
+ {"slack_channel_ids": ["a", "b"] + [f"c{i}" for i in range(48)]},
+ ),
+ ("null_clears_the_stored_list", None, {"slack_channel_ids": None}, {"slack_channel_ids": None}),
+ (
+ "unchanged_list_over_50_is_kept",
+ {"slack_channel_ids": _sixty_channel_ids()},
+ {"slack_channel_ids": _sixty_channel_ids()},
+ {"slack_channel_ids": _sixty_channel_ids()},
+ ),
+ (
+ "changed_list_over_50_is_capped",
+ {"slack_channel_ids": _sixty_channel_ids()},
+ {"slack_channel_ids": ["new", *_sixty_channel_ids()]},
+ {"slack_channel_ids": ["new", *_sixty_channel_ids()[:49]]},
+ ),
+ (
+ "unchanged_display_name_over_200_characters_is_kept",
+ {"slack_bot_display_name": "a" * 201},
+ {"slack_bot_display_name": "a" * 201},
+ {"slack_bot_display_name": "a" * 201},
+ ),
+ (
+ "unchanged_non_object_ai_reply_modes_is_kept",
+ {"ai_reply_modes": ["old"]},
+ {"ai_reply_modes": ["old"]},
+ {"ai_reply_modes": ["old"]},
+ ),
+ (
+ "unchanged_bot_reply_mode_is_kept",
+ {"ai_reply_modes": {"slack": {"diagnostic": "bot_reply"}}},
+ {"ai_reply_modes": {"slack": {"diagnostic": "bot_reply"}}},
+ {"ai_reply_modes": {"slack": {"diagnostic": "bot_reply"}}},
+ ),
+ (
+ "unchanged_widget_domains_is_kept",
+ {"widget_domains": _TOO_MANY_WILDCARDS},
+ {"widget_domains": _TOO_MANY_WILDCARDS},
+ {"widget_domains": _TOO_MANY_WILDCARDS},
+ ),
+ (
+ "changed_value_is_cleaned_with_unchanged_value_present",
+ {"ai_reply_modes": ["old"], "slack_alert_channel_id": "old"},
+ {"ai_reply_modes": ["old"], "slack_alert_channel_id": " new "},
+ {"ai_reply_modes": ["old"], "slack_alert_channel_id": "new"},
+ ),
+ )
+ ]
+ )
+ def test_conversations_settings_cleans_up_values(
+ self,
+ serializer_class: type[TeamSerializer] | type[ProjectBackwardCompatSerializer],
+ _name: str,
+ stored: dict[str, object] | None,
+ submitted: dict[str, object],
+ expected_cleaned: dict[str, object],
+ ) -> None:
+ # A PATCH that sends null must clear the stored list, not silently keep the old one:
+ # merge_conversations_settings only overwrites keys present in the validated value, so
+ # dropping the key here (instead of keeping it as None) would make the clear a no-op.
+ cleaned = _validate_conversations_settings(serializer_class, stored, submitted)
+ self.assertEqual(cleaned, expected_cleaned)
+
@parameterized.expand([(None,), (True,), (123,), ([],), ({},), ("a" * 201,)])
def test_invalid_logs_json_attribute_key(self, key):
self._assert_field_error(