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): return 405 for unsupported ticket create POST (#72997)

Steven Shults149d1d7d74bb
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index 9929febab137..a55de0b4fe1b 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -26,6 +26,8 @@ from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.models import ActivityLog, Comment, Organization, Tag, User
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.persons import create_person
from products.conversations.backend.api.tickets import TicketReplyRequestSerializer
@@ -60,6 +62,30 @@ class TestTicketAPI(APIBaseTest):
self.assertEqual(response.json()["count"], 1)
self.assertEqual(response.json()["results"][0]["id"], str(self.ticket.id))
+ @parameterized.expand(["session", "personal_api_key"])
+ def test_create_ticket_not_allowed(self, mock_on_commit, auth):
+ # The bare collection POST was never a real intake path — DRF's default create
+ # can't set team/ticket_number and used to 500 (issue #71101). It must 405 instead.
+ # The reporter used a ticket:write personal API key, so cover that path too: with
+ # "create" kept in scope_object_write_actions the token clears the scope gate and
+ # reaches the 405 rather than a misleading "not supported" 403.
+ if auth == "personal_api_key":
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="ticket-write",
+ user=self.user,
+ secure_value=hash_key_value(raw_key),
+ scopes=["ticket:write"],
+ )
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_key}")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/conversations/tickets/",
+ data={"status": "new"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
+
def _ticket_with_tags(self, *tag_names):
ticket = Ticket.objects.create_with_number(
team=self.team,
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index bf98ca44189d..c7faea5c03e8 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -23,6 +23,7 @@ from rest_framework import (
viewsets,
)
from rest_framework.decorators import action
+from rest_framework.exceptions import MethodNotAllowed
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@@ -359,6 +360,8 @@ TICKET_ID_PARAM = OpenApiParameter(
class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "ticket"
scope_object_read_actions = ["list", "retrieve", "unread_count", "messages"]
+ # "create" stays listed so a ticket:write token reaches the create() override below and
+ # gets a clear 405 (pointing to the SDK), rather than a misleading "not supported" 403.
scope_object_write_actions = ["create", "update", "partial_update", "patch", "compose", "reply", "ai_feedback"]
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
@@ -595,6 +598,19 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod
context["team"] = self.team
return context
+ @extend_schema(exclude=True)
+ def create(self, *args, **kwargs):
+ # Tickets are created through their channel (widget, email, Slack, etc.) or the
+ # `compose` action, all of which assign team + ticket_number. The bare collection
+ # POST can't set those and is not a supported intake path — reject it explicitly
+ # instead of 500ing on the NOT NULL violation.
+ raise MethodNotAllowed(
+ method="POST",
+ detail="Creating tickets via this endpoint is not supported. "
+ "Use posthog.conversations.sendMessage() from the JavaScript SDK. "
+ "See https://posthog.com/docs/support/javascript-api for details.",
+ )
+
def _attach_persons_to_tickets(self, tickets: Sequence[Ticket]) -> None:
"""Batch-fetch persons by distinct_id and attach to tickets."""
distinct_ids = sorted([t.distinct_id for t in tickets if t.distinct_id])
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index 6ef415effe2e..54239c01bc16 100644
--- a/products/conversations/frontend/generated/api.ts
+++ b/products/conversations/frontend/generated/api.ts
@@ -321,23 +321,6 @@ export const conversationsTicketsList = async (
})
}
-export const getConversationsTicketsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/conversations/tickets/`
-}
-
-export const conversationsTicketsCreate = async (
- projectId: string,
- ticketApi?: NonReadonly<TicketApi>,
- options?: RequestInit
-): Promise<TicketApi> => {
- return apiMutator<TicketApi>(getConversationsTicketsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(ticketApi),
- })
-}
-
export const getConversationsTicketsRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/conversations/tickets/${id}/`
}
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index 05b7e42c0cf6..85adfbbce936 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -154,41 +154,6 @@ export const ConversationsQueuePartialUpdateBody = /* @__PURE__ */ zod.looseObje
export const ConversationsQueueClearCreateBody = /* @__PURE__ */ zod.looseObject({})
-export const ConversationsTicketsCreateBody = /* @__PURE__ */ zod
- .object({
- status: zod
- .enum(['new', 'open', 'pending', 'on_hold', 'resolved'])
- .describe(
- '\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'
- )
- .optional()
- .describe(
- 'Ticket status: new, open, pending, on_hold, or resolved\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'
- ),
- priority: zod
- .union([
- zod
- .enum(['low', 'medium', 'high', 'critical'])
- .describe('\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Ticket priority: low, medium, high, or critical. Null if unset.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'
- ),
- anonymous_traits: zod.unknown().optional().describe('Customer-provided traits such as name and email'),
- ai_resolved: zod.boolean().optional(),
- escalation_reason: zod.string().nullish(),
- sla_due_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('SLA deadline set via workflows. Null means no SLA.'),
- snoozed_until: zod.iso.datetime({ offset: true }).nullish(),
- tags: zod.array(zod.unknown()).optional(),
- })
- .describe('Serializer mixin that handles tags for objects.')
-
/**
* Handle ticket updates including assignee changes.
*/
diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yaml
index 9fbebfacd203..c50007e526eb 100644
--- a/products/conversations/mcp/tools.yaml
+++ b/products/conversations/mcp/tools.yaml
@@ -21,9 +21,6 @@ tools:
conversations-tickets-compose-create:
operation: conversations_tickets_compose_create
enabled: false
- conversations-tickets-create:
- operation: conversations_tickets_create
- enabled: false
conversations-tickets-destroy:
operation: conversations_tickets_destroy
enabled: false