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.

feat(conversations): add JWT-only internal ticket route (#87669)

Harley Alexander141728ed2582
diff --git a/posthog/auth.py b/posthog/auth.py
index 98fb8e9f2df1..c792ef633310 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -1174,6 +1174,8 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
The request authenticates as a synthetic InternalAPIUser bound to the token's team.
When the URL carries a team_id, the token's team_id claim must match it, so a token
minted for one team can never read another's data even if both hit the same route.
+ The verified claims become request.auth, so views can enforce entity-level claims
+ (e.g. that the token's ticket_id matches the URL's).
require_team=False is for fleet-scoped purposes (cron-style calls with no team in the
URL or claims); team-scoped purposes must keep the default so a token without a team
@@ -1183,7 +1185,7 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
purpose: ClassVar[ScopedServiceJwtPurpose]
require_team: ClassVar[bool] = True
- def authenticate(self, request: Request) -> Optional[tuple[Any, None]]:
+ def authenticate(self, request: Request) -> Optional[tuple[Any, dict[str, Any]]]:
header = authentication.get_authorization_header(request).split()
# No bearer header: return None (not raise) so the view's other authenticators,
# if any, still get their turn.
@@ -1216,13 +1218,13 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
return self._authenticate_claims(request, claims)
- def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, None]:
+ def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, dict[str, Any]]:
claim_team_id = claims.get("team_id")
if claim_team_id is None:
if self.require_team:
raise AuthenticationFailed("Service token is missing its team claim.")
- return InternalAPIUser(), None
+ return InternalAPIUser(), claims
url_team_id = _team_id_from_request_path(request)
if url_team_id is not None and str(claim_team_id) != url_team_id:
@@ -1234,7 +1236,7 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
except (Team.DoesNotExist, ValueError, TypeError):
raise AuthenticationFailed("Invalid service token team.")
- return InternalAPIUser(current_organization_id=team.organization_id, current_team_id=team.id), None
+ return InternalAPIUser(current_organization_id=team.organization_id, current_team_id=team.id), claims
def authenticate_header(self, request: Request) -> str:
# Without a challenge value DRF renders every AuthenticationFailed from this class as
diff --git a/posthog/jwt.py b/posthog/jwt.py
index d7c2c0a4e906..201d14f554ca 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -25,6 +25,7 @@ class PosthogJwtAudience(Enum):
WORKFLOWS_CANCEL_BATCH = "posthog:workflows:cancel_batch"
INTEGRATION_SERVICE = "posthog:integration_service"
TASKS_CREATE = "posthog:tasks:create"
+ CONVERSATIONS_TICKETS = "posthog:conversations:tickets"
def signing_key_fingerprint(key: str) -> str:
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index f1da14060b89..50a60eb7869a 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -578,6 +578,14 @@ TASKS_CREATE_JWT_SECRETS = get_list(
get_from_env("TASKS_CREATE_JWT_SECRET", "local-dev-tasks-create-jwt" if DEBUG or TEST else "")
)
+# Verifies the scoped JWTs the CDP worker's conversations ticket actions send to the internal
+# ticket route (the worker mints, Django verifies; products/conversations/backend/api/internal.py).
+# Comma-separated, newest first. Empty outside dev/test, so the internal route rejects every
+# request until the secret is provisioned and the worker stays on its legacy auth path (#82564).
+CONVERSATIONS_TICKETS_JWT_SECRETS = get_list(
+ get_from_env("CONVERSATIONS_TICKETS_JWT_SECRET", "local-dev-conversations-tickets-jwt" if DEBUG or TEST else "")
+)
+
EMBEDDING_API_URL = get_from_env("EMBEDDING_API_URL", "")
# Used to generate embeddings on the fly, for use with the document embeddings table
diff --git a/posthog/test/test_scoped_service_jwt.py b/posthog/test/test_scoped_service_jwt.py
index de845d2656cd..7805d5df9bf3 100644
--- a/posthog/test/test_scoped_service_jwt.py
+++ b/posthog/test/test_scoped_service_jwt.py
@@ -133,7 +133,7 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):
user, auth = self._authenticate(self.authentication, self._request(token, url_team_id=self.team.id))
- assert auth is None
+ assert auth["team_id"] == self.team.id
assert user.is_authenticated
assert user.current_team_id == self.team.id
assert user.current_organization_id == self.team.organization_id
diff --git a/posthog/urls.py b/posthog/urls.py
index 52625b069187..5bd1c35e39b5 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -52,6 +52,7 @@ from posthog.web_bot_auth import http_message_signatures_directory
from products.ai_observability.backend.api.personal_spend import PersonalSpendEUProxyViewSet
from products.canvas.backend.artifacts import canvas_artifact
from products.cdp.backend.api import hog_function_template
+from products.conversations.backend.api.internal import InternalTicketView as ConversationsInternalTicketView
from products.demo.backend.facade.api import demo_route
from products.early_access_features.backend.api import early_access_features
from products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook
@@ -626,6 +627,11 @@ urlpatterns = [
"api/projects/<str:team_id>/internal/signals/emit",
csrf_exempt(signals_views.InternalSignalViewSet.as_view({"post": "emit"})),
),
+ # Ticket route for the CDP worker's workflow actions (auth: scoped service JWT)
+ path(
+ "api/projects/<str:team_id>/internal/conversations/tickets/<uuid:ticket_id>",
+ csrf_exempt(ConversationsInternalTicketView.as_view()),
+ ),
# Test setup endpoint (only available in TEST mode)
path("api/setup_test/<str:test_name>/", csrf_exempt(playwright_setup.setup_test)),
opt_slash_path(
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index e13dd279a308..231e0cb980bc 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -4,36 +4,26 @@ External API endpoints for the Conversations product.
These endpoints are used by the CDP worker for workflow actions and can be opened
to third-party developers in the future.
Authenticated via team secret API token passed as a Bearer token in the Authorization header.
+
+This auth path is legacy (#82564 tracks the worker's move to the scoped-JWT internal
+route, api/internal.py). Both routes share the handlers in api/ticket_actions.py.
"""
-import uuid
import hashlib
-from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django.db.models import Q
-from django.utils import timezone
-import structlog
-from rest_framework import serializers, status
+from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView
-from posthog.exceptions_capture import capture_exception
-from posthog.models import Tag, Team
-from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
-from posthog.models.activity_logging.model_activity import ActivityTriggerContext
-from posthog.models.tag import tagify
-
-from products.conversations.backend.api.tickets import assign_ticket
-from products.conversations.backend.cache import invalidate_unread_count_cache
-from products.conversations.backend.models import Ticket
-from products.conversations.backend.models.constants import Priority, Status
-from products.conversations.backend.services.sla import WEEKDAYS, compute_sla_deadline
+from posthog.models import Team
-logger = structlog.get_logger(__name__)
+from products.conversations.backend.api.ticket_actions import handle_ticket_get, handle_ticket_patch
+from products.conversations.backend.metrics import TICKET_ACTION_AUTH_COUNTER
class _ExternalTicketThrottle(SimpleRateThrottle):
@@ -76,100 +66,10 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Resp
except (Team.DoesNotExist, Team.MultipleObjectsReturned):
return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+ TICKET_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method=(request.method or "").lower()).inc()
return team, None
-class ExternalTicketUpdateSerializer(serializers.Serializer):
- status = serializers.ChoiceField(choices=[s.value for s in Status], required=False)
- priority = serializers.ChoiceField(choices=[p.value for p in Priority], required=False)
- sla_due_at = serializers.DateTimeField(required=False, allow_null=True)
- # `sla_amount`/`sla_unit`/`sla_business_hours` are the raw workflow inputs;
- # the backend computes `sla_due_at` from them so the calculation stays
- # testable and timezone-aware. Clear still routes through `sla_due_at: null`.
- sla_amount = serializers.FloatField(required=False, min_value=0.000001)
- sla_unit = serializers.ChoiceField(choices=["minute", "hour", "day"], required=False, default="hour")
- sla_business_hours = serializers.JSONField(required=False, allow_null=True)
- snoozed_until = serializers.DateTimeField(required=False, allow_null=True)
- assignee = serializers.JSONField(required=False, allow_null=True)
- tags = serializers.ListField(child=serializers.CharField(max_length=200), required=False, max_length=100)
- tags_mode = serializers.ChoiceField(choices=["add", "set", "remove"], required=False, default="add")
-
- def validate_sla_business_hours(self, value):
- if value is None:
- return value
- if not isinstance(value, dict):
- raise serializers.ValidationError("sla_business_hours must be an object")
-
- days = value.get("days")
- if not isinstance(days, list) or not days:
- raise serializers.ValidationError("sla_business_hours.days must be a non-empty list")
- unknown = [d for d in days if d not in WEEKDAYS]
- if unknown:
- raise serializers.ValidationError(f"Unknown weekday names: {unknown}")
-
- time_cfg = value.get("time", "any")
- if time_cfg != "any":
- if not (isinstance(time_cfg, list) and len(time_cfg) == 2):
- raise serializers.ValidationError("sla_business_hours.time must be 'any' or [start, end]")
- if not isinstance(time_cfg[0], str) or not isinstance(time_cfg[1], str):
- raise serializers.ValidationError("sla_business_hours.time entries must be HH:MM strings")
- if time_cfg[0] >= time_cfg[1]:
- raise serializers.ValidationError("sla_business_hours.time start must be strictly before end")
-
- tz_name = value.get("timezone") or "UTC"
- if not isinstance(tz_name, str):
- raise serializers.ValidationError("sla_business_hours.timezone must be a string")
- try:
- ZoneInfo(tz_name)
- except ZoneInfoNotFoundError:
- raise serializers.ValidationError(f"Invalid timezone: {tz_name}")
- return value
-
- def validate(self, attrs):
- if "sla_due_at" in attrs and "sla_amount" in attrs:
- raise serializers.ValidationError(
- {"sla_amount": "Cannot set both sla_due_at and sla_amount in the same request"}
- )
- return attrs
-
-
-def _validate_ticket_id(ticket_id: str | uuid.UUID) -> Response | None:
- """Return an error Response if ticket_id is not a valid UUID, else None."""
- # Django's <uuid:ticket_id> converter passes uuid.UUID; uuid.UUID(uuid_obj)
- # wrongly treats it as ``hex`` and raises AttributeError.
- if isinstance(ticket_id, uuid.UUID):
- return None
- try:
- uuid.UUID(str(ticket_id))
- except (ValueError, AttributeError, TypeError):
- return Response({"error": "Invalid ticket_id format"}, status=status.HTTP_400_BAD_REQUEST)
- return None
-
-
-# Header a HogFlow workflow step forwards so activity entries can attribute the change to it.
-HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"
-
-
-def _workflow_trigger_from_request(request: Request) -> Trigger | None:
- """Build an activity-log Trigger when the request originates from a HogFlow workflow step.
-
- Only the workflow id is taken from the (caller-supplied) header, and only as a well-formed
- UUID. The display name is resolved from the workflow itself on the frontend, so a token
- holder can't spoof an arbitrary workflow name into the audit log. Module boundaries keep
- conversations independent of workflows, so we can't validate id ownership here; the endpoint
- is team-token authenticated, so the worst case is a token holder pointing attribution at
- another workflow id within its own team — no cross-team or privilege impact.
- """
- hog_flow_id = request.headers.get(HOG_FLOW_ID_HEADER)
- if not hog_flow_id:
- return None
- try:
- uuid.UUID(hog_flow_id)
- except (ValueError, TypeError):
- return None
- return Trigger(job_type="hog_flow", job_id=hog_flow_id, payload={})
-
-
class ExternalTicketView(APIView):
"""
GET /api/conversations/external/ticket/<ticket_id> — Fetch ticket data
@@ -189,63 +89,7 @@ class ExternalTicketView(APIView):
assert team is not None
- if error := _validate_ticket_id(ticket_id):
- return error
-
- try:
- ticket = Ticket.objects.select_related(
- "assignment", "assignment__user", "assignment__role", "email_config"
- ).get(id=ticket_id, team_id=team.id)
- except Ticket.DoesNotExist:
- return Response({"error": "Ticket not found"}, status=status.HTTP_404_NOT_FOUND)
-
- assignee = None
- assignment = getattr(ticket, "assignment", None)
- if assignment:
- assignee = {
- "id": assignment.user_id
- if assignment.user_id
- else str(assignment.role_id)
- if assignment.role_id
- else None,
- "type": "role" if assignment.role_id else "user",
- "user": {"email": assignment.user.email} if assignment.user_id and assignment.user else None,
- "role": {"name": assignment.role.name} if assignment.role_id and assignment.role else None,
- }
-
- session_context = ticket.session_context or {}
- tags = list(ticket.tagged_items.values_list("tag__name", flat=True))
-
- return Response(
- {
- "id": str(ticket.id),
- "number": ticket.ticket_number,
- "status": ticket.status,
- "priority": ticket.priority,
- "channel_source": ticket.channel_source,
- "channel_detail": ticket.channel_detail,
- "distinct_id": ticket.distinct_id,
- "created_at": ticket.created_at.isoformat(),
- "updated_at": ticket.updated_at.isoformat(),
- "message_count": ticket.message_count,
- "last_message_at": ticket.last_message_at.isoformat() if ticket.last_message_at else None,
- "last_message_text": ticket.last_message_text,
- "unread_team_count": ticket.unread_team_count,
- "unread_customer_count": ticket.unread_customer_count,
- "sla": ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
- "snoozed_until": ticket.snoozed_until.isoformat() if ticket.snoozed_until else None,
- "assignee": assignee,
- "url": session_context.get("current_url"),
- "slack_channel_id": ticket.slack_channel_id,
- "slack_thread_ts": ticket.slack_thread_ts,
- "slack_team_id": ticket.slack_team_id,
- "email_subject": ticket.email_subject,
- "email_from": ticket.email_from,
- "email_to": ticket.email_config.from_email if ticket.email_config else None,
- "cc_participants": ticket.cc_participants,
- "tags": tags,
- }
- )
+ return handle_ticket_get(team, ticket_id)
def patch(self, request: Request, ticket_id: str) -> Response:
team, error = _authenticate_team(request)
@@ -254,212 +98,4 @@ class ExternalTicketView(APIView):
assert team is not None
- # When a HogFlow workflow step makes the change, it forwards its identity via
- # headers so the activity log can attribute (and link to) the workflow.
- workflow_trigger = _workflow_trigger_from_request(request)
-
- if error := _validate_ticket_id(ticket_id):
- return error
-
- serializer = ExternalTicketUpdateSerializer(data=request.data)
- if not serializer.is_valid():
- return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
-
- try:
- ticket = Ticket.objects.get(id=ticket_id, team_id=team.id)
- except Ticket.DoesNotExist:
- return Response({"error": "Ticket not found"}, status=status.HTTP_404_NOT_FOUND)
-
- update_fields: list[str] = []
- changes: list[Change] = []
-
- new_status = serializer.validated_data.get("status")
- old_status = ticket.status
- if new_status is not None:
- ticket.status = new_status
- update_fields.append("status")
-
- if old_status == "resolved" or new_status == "resolved":
- invalidate_unread_count_cache(team.id)
-
- if old_status != new_status:
- changes.append(
- Change(
- type="Ticket",
- field="status",
- before=old_status,
- after=new_status,
- action="changed",
- )
- )
-
- new_priority = serializer.validated_data.get("priority")
- old_priority = ticket.priority
- if new_priority is not None:
- ticket.priority = new_priority
- update_fields.append("priority")
-
- if old_priority != new_priority:
- changes.append(
- Change(
- type="Ticket",
- field="priority",
- before=old_priority,
- after=new_priority,
- action="changed",
- )
- )
-
- old_sla_due_at = ticket.sla_due_at
- if "sla_due_at" in serializer.validated_data:
- ticket.sla_due_at = serializer.validated_data["sla_due_at"]
- update_fields.append("sla_due_at")
-
- if old_sla_due_at != ticket.sla_due_at:
- changes.append(
- Change(
- type="Ticket",
- field="sla_due_at",
- before=old_sla_due_at.isoformat() if old_sla_due_at else None,
- after=ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
- action="changed",
- )
- )
- elif "sla_amount" in serializer.validated_data:
- try:
- new_sla_due_at = compute_sla_deadline(
- now=timezone.now(),
- amount=serializer.validated_data["sla_amount"],
- unit=serializer.validated_data.get("sla_unit", "hour"),
- business_hours=serializer.validated_data.get("sla_business_hours"),
- )
- except (ValueError, RuntimeError) as e:
- capture_exception(e, {"ticket_id": str(ticket.id)})
- return Response({"error": "Invalid SLA configuration."}, status=status.HTTP_400_BAD_REQUEST)
-
- ticket.sla_due_at = new_sla_due_at
- if "sla_due_at" not in update_fields:
- update_fields.append("sla_due_at")
-
- if old_sla_due_at != ticket.sla_due_at:
- changes.append(
- Change(
- type="Ticket",
- field="sla_due_at",
- before=old_sla_due_at.isoformat() if old_sla_due_at else None,
- after=ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
- action="changed",
- )
- )
-
- old_snoozed_until = ticket.snoozed_until
- if "snoozed_until" in serializer.validated_data:
- ticket.snoozed_until = serializer.validated_data["snoozed_until"]
- update_fields.append("snoozed_until")
-
- if old_snoozed_until != ticket.snoozed_until:
- changes.append(
- Change(
- type="Ticket",
- field="snoozed_until",
- before=old_snoozed_until.isoformat() if old_snoozed_until else None,
- after=ticket.snoozed_until.isoformat() if ticket.snoozed_until else None,
- action="changed",
- )
- )
-
- # Auto-status on snooze transitions (only when status wasn't explicitly set)
- if new_status is None:
- auto_status = None
- if old_snoozed_until is None and ticket.snoozed_until is not None:
- auto_status = "on_hold"
- elif old_snoozed_until is not None and ticket.snoozed_until is None:
- auto_status = "open"
-
- if auto_status and ticket.status != auto_status:
- auto_old_status = ticket.status
- ticket.status = auto_status
- if "status" not in update_fields:
- update_fields.append("status")
- changes.append(
- Change(
- type="Ticket",
- field="status",
- before=auto_old_status,
- after=auto_status,
- action="changed",
- )
- )
-
- if update_fields:
- ticket.save(update_fields=[*update_fields, "updated_at"])
-
- if changes:
- try:
- log_activity(
- organization_id=team.organization_id,
- team_id=team.id,
- user=None,
- was_impersonated=False,
- item_id=str(ticket.id),
- scope="Ticket",
- activity="updated",
- detail=Detail(
- name=f"Ticket #{ticket.ticket_number}",
- changes=changes,
- trigger=workflow_trigger,
- ),
- )
- except Exception as e:
- capture_exception(e, {"ticket_id": str(ticket.id)})
-
- if "assignee" in serializer.validated_data:
- try:
- assign_ticket(
- ticket=ticket,
- assignee=serializer.validated_data.get("assignee"),
- organization=team.organization,
- user=None,
- team_id=team.id,
- was_impersonated=False,
- trigger=workflow_trigger,
- )
- except Exception as e:
- capture_exception(e, {"ticket_id": str(ticket.id)})
- return Response({"error": "Failed to assign ticket"}, status=status.HTTP_400_BAD_REQUEST)
-
- if "tags" in serializer.validated_data:
- try:
- tags_mode = serializer.validated_data.get("tags_mode", "add")
- normalized_tags = {tagify(t) for t in serializer.validated_data["tags"]}
-
- # Tag adds and removes are both logged by the TaggedItem model activity signal
- # (to the ticket's timeline and the Tag audit stream). Removals must go through
- # the per-instance delete() so the signal fires for them too; a bulk queryset
- # delete would skip it. The trigger context attributes every resulting entry
- # to the workflow that made the change.
- with ActivityTriggerContext(workflow_trigger):
- if tags_mode == "remove":
- for tagged_item in ticket.tagged_items.filter(tag__name__in=normalized_tags).select_related(
- "tag__team", "ticket"
- ):
- tagged_item.delete()
- Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
- elif tags_mode == "set":
- for tag_name in normalized_tags:
- tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
- ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
- for tagged_item in ticket.tagged_items.exclude(tag__name__in=normalized_tags).select_related(
- "tag__team", "ticket"
- ):
- tagged_item.delete()
- Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
- else:
- for tag_name in normalized_tags:
- tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
- ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
- except Exception as e:
- capture_exception(e, {"ticket_id": str(ticket.id)})
- return Response({"error": "Failed to update tags"}, status=status.HTTP_400_BAD_REQUEST)
-
- return Response({"ok": True})
+ return handle_ticket_patch(request, team, ticket_id)
diff --git a/products/conversations/backend/api/internal.py b/products/conversations/backend/api/internal.py
new file mode 100644
index 000000000000..534d8cc04bc5
--- /dev/null
+++ b/products/conversations/backend/api/internal.py
@@ -0,0 +1,91 @@
+"""
+Internal ticket endpoints for the Conversations product.
+
+The service-to-service surface the CDP worker's ticket workflow actions call. Callers
+authenticate with a short-lived scoped service JWT pinned to one team and one ticket
+(#82564 tracks retiring the legacy secret_api_token route in api/external.py). Mounted
+under /api/projects/<team_id>/internal/ in posthog/urls.py, a namespace Contour ingress
+does not expose, so the route is unreachable from the public internet.
+"""
+
+import uuid
+from typing import Any, cast
+
+from rest_framework import status
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.auth import ScopedServiceJWTAuthentication
+from posthog.jwt import PosthogJwtAudience
+from posthog.models import Team
+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
+
+from products.conversations.backend.api.ticket_actions import handle_ticket_get, handle_ticket_patch
+from products.conversations.backend.metrics import TICKET_ACTION_AUTH_COUNTER
+
+CONVERSATIONS_TICKETS_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.CONVERSATIONS_TICKETS,
+ settings_name="CONVERSATIONS_TICKETS_JWT_SECRETS",
+)
+
+
+class ConversationsTicketJWTAuthentication(ScopedServiceJWTAuthentication):
+ purpose = CONVERSATIONS_TICKETS_PURPOSE
+
+
+class InternalTicketView(APIView):
+ """
+ GET /api/projects/<team_id>/internal/conversations/tickets/<ticket_id> — Fetch ticket data
+ PATCH /api/projects/<team_id>/internal/conversations/tickets/<ticket_id> — Update ticket fields
+
+ JWT-only from birth: there is no legacy-token fallback here, so this route never
+ accepts secret_api_token. The auth class binds the request to the token's team and
+ rejects tokens whose team differs from the URL's.
+ """
+
+ authentication_classes = [ConversationsTicketJWTAuthentication]
+ permission_classes = [IsAuthenticated]
+
+ def get(self, request: Request, team_id: str, ticket_id: uuid.UUID) -> Response:
+ team, error = _check_ticket_access(request, ticket_id)
+ if error:
+ return error
+ assert team is not None
+ TICKET_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="get").inc()
+ return handle_ticket_get(team, ticket_id)
+
+ def patch(self, request: Request, team_id: str, ticket_id: uuid.UUID) -> Response:
+ team, error = _check_ticket_access(request, ticket_id)
+ if error:
+ return error
+ assert team is not None
+ TICKET_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="patch").inc()
+ return handle_ticket_patch(request, team, ticket_id)
+
+
+def _check_ticket_access(request: Request, ticket_id: uuid.UUID) -> tuple[Team, None] | tuple[None, Response]:
+ """Enforce the per-entity claim and the product gate after JWT authentication.
+
+ The worker mints each token for one specific ticket, so a token replayed against a
+ different ticket URL is refused even within its own team. Missing claim fails closed.
+ """
+ claims = cast(dict[str, Any], request.auth or {})
+ if str(claims.get("ticket_id")) != str(ticket_id):
+ return None, Response(
+ {"error": "Service token does not grant access to this ticket"}, status=status.HTTP_403_FORBIDDEN
+ )
+
+ # The auth class already verified the team claim exists, matches the URL, and names a real
+ # team; fetch the full row because the handlers need organization access for activity
+ # logging and assignment. The team can still vanish between the two reads, so a clean 404
+ # beats an unhandled 500.
+ try:
+ team = Team.objects.get(id=claims["team_id"])
+ except Team.DoesNotExist:
+ return None, Response({"error": "Team not found"}, status=status.HTTP_404_NOT_FOUND)
+ if not team.conversations_enabled:
+ return None, Response({"error": "Conversations is not enabled for this team"}, status=status.HTTP_403_FORBIDDEN)
+
+ return team, None
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index 17acc2ad28a6..17a38cb0b479 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -3,6 +3,7 @@ import uuid
from posthog.test.base import BaseTest
from parameterized import parameterized
+from prometheus_client import REGISTRY
from rest_framework import status
from rest_framework.test import APIClient
@@ -72,6 +73,13 @@ class TestExternalTicketAPI(BaseTest):
response = self.client.get(self.url, **self._auth_headers())
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ def test_authenticated_requests_increment_the_legacy_auth_counter(self):
+ labels = {"auth_method": "secret_api_token", "http_method": "get"}
+ before = REGISTRY.get_sample_value("posthog_conversations_ticket_action_auth_total", labels) or 0
+ self.client.get(self.url, **self._auth_headers())
+ after = REGISTRY.get_sample_value("posthog_conversations_ticket_action_auth_total", labels)
+ self.assertEqual(after, before + 1)
+
# -- GET ticket -------------------------------------------------------
def test_get_ticket_returns_all_fields(self):
@@ -246,7 +254,7 @@ class TestExternalTicketAPI(BaseTest):
# 2026-01-05 10:00 UTC is a Monday.
frozen_now = datetime(2026, 1, 5, 10, 0, tzinfo=UTC)
- with patch("products.conversations.backend.api.external.timezone.now", return_value=frozen_now):
+ with patch("products.conversations.backend.api.ticket_actions.timezone.now", return_value=frozen_now):
response = self.client.patch(
self.url,
{"sla_amount": 4, "sla_unit": "hour"},
@@ -264,7 +272,7 @@ class TestExternalTicketAPI(BaseTest):
from unittest.mock import patch
frozen_now = datetime(2026, 1, 8, 16, 0, tzinfo=UTC) # Thursday 16:00 UTC
- with patch("products.conversations.backend.api.external.timezone.now", return_value=frozen_now):
+ with patch("products.conversations.backend.api.ticket_actions.timezone.now", return_value=frozen_now):
response = self.client.patch(
self.url,
{
diff --git a/products/conversations/backend/api/tests/test_internal.py b/products/conversations/backend/api/tests/test_internal.py
new file mode 100644
index 000000000000..9fec790dd277
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_internal.py
@@ -0,0 +1,134 @@
+import uuid
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.jwt import PosthogJwtAudience
+from posthog.models.utils import generate_random_token_secret
+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
+
+from products.conversations.backend.api.internal import CONVERSATIONS_TICKETS_PURPOSE
+from products.conversations.backend.models import Ticket
+from products.conversations.backend.models.constants import Status
+
+# Signed with this route's key but carrying another surface's audience — a token minted for a
+# different purpose must never authenticate here even when the signing key checks out.
+OTHER_AUDIENCE_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.RECORDING_API,
+ settings_name="CONVERSATIONS_TICKETS_JWT_SECRETS",
+)
+
+
+class TestInternalTicketAPI(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.team.conversations_enabled = True
+ self.team.secret_api_token = generate_random_token_secret()
+ self.team.save(update_fields=["conversations_enabled", "secret_api_token"])
+ self.client = APIClient()
+ self.ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=str(uuid.uuid4()),
+ distinct_id="user-int-123",
+ channel_source="widget",
+ status=Status.NEW,
+ )
+ self.url = f"/api/projects/{self.team.id}/internal/conversations/tickets/{self.ticket.id}"
+
+ def _claims(self) -> dict:
+ return {"team_id": self.team.id, "ticket_id": str(self.ticket.id)}
+
+ def _headers(self, claims: dict | None = None) -> dict:
+ return self._bearer(CONVERSATIONS_TICKETS_PURPOSE.mint(claims if claims is not None else self._claims()))
+
+ @staticmethod
+ def _bearer(token: str) -> dict:
+ return {"HTTP_AUTHORIZATION": f"Bearer {token}"}
+
+ def test_get_returns_ticket_for_minted_token(self):
+ response = self.client.get(self.url, **self._headers())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["id"], str(self.ticket.id))
+ self.assertEqual(data["status"], "new")
+ self.assertEqual(data["distinct_id"], "user-int-123")
+
+ def test_patch_updates_ticket(self):
+ response = self.client.patch(
+ self.url, {"status": "resolved"}, content_type="application/json", **self._headers()
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.ticket.refresh_from_db()
+ self.assertEqual(self.ticket.status, "resolved")
+
+ @parameterized.expand(
+ [
+ (
+ "token_for_another_team",
+ lambda self: self._headers({"team_id": self.team.id + 1, "ticket_id": str(self.ticket.id)}),
+ status.HTTP_401_UNAUTHORIZED,
+ ),
+ (
+ "legacy_secret_api_token",
+ lambda self: {"HTTP_AUTHORIZATION": f"Bearer {self.team.secret_api_token}"},
+ status.HTTP_401_UNAUTHORIZED,
+ ),
+ (
+ "expired_token",
+ lambda self: self._bearer(
+ CONVERSATIONS_TICKETS_PURPOSE.mint(self._claims(), ttl=timedelta(minutes=-1))
+ ),
+ status.HTTP_401_UNAUTHORIZED,
+ ),
+ (
+ "token_for_another_purpose",
+ lambda self: self._bearer(OTHER_AUDIENCE_PURPOSE.mint(self._claims())),
+ status.HTTP_401_UNAUTHORIZED,
+ ),
+ (
+ "missing_ticket_claim",
+ lambda self: self._headers({"team_id": self.team.id}),
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "token_for_another_ticket",
+ lambda self: self._headers({"team_id": self.team.id, "ticket_id": str(uuid.uuid4())}),
+ status.HTTP_403_FORBIDDEN,
+ ),
+ ("no_credentials", lambda self: {}, status.HTTP_401_UNAUTHORIZED),
+ ]
+ )
+ def test_rejected_credentials(self, _name, make_headers, expected_status):
+ headers = make_headers(self)
+ get_response = self.client.get(self.url, **headers)
+ self.assertEqual(get_response.status_code, expected_status)
+ patch_response = self.client.patch(self.url, {"status": "resolved"}, content_type="application/json", **headers)
+ self.assertEqual(patch_response.status_code, expected_status)
+ self.ticket.refresh_from_db()
+ self.assertEqual(self.ticket.status, Status.NEW)
+
+ def test_unprovisioned_secret_rejects_even_a_well_formed_token(self):
+ headers = self._headers()
+ with override_settings(CONVERSATIONS_TICKETS_JWT_SECRETS=[]):
+ response = self.client.get(self.url, **headers)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_conversations_disabled_is_rejected(self):
+ self.team.conversations_enabled = False
+ self.team.save(update_fields=["conversations_enabled"])
+ response = self.client.get(self.url, **self._headers())
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_authenticated_get_increments_the_scoped_jwt_counter(self):
+ labels = {"auth_method": "scoped_jwt", "http_method": "get"}
+ before = REGISTRY.get_sample_value("posthog_conversations_ticket_action_auth_total", labels) or 0
+ self.client.get(self.url, **self._headers())
+ after = REGISTRY.get_sample_value("posthog_conversations_ticket_action_auth_total", labels)
+ self.assertEqual(after, before + 1)
diff --git a/products/conversations/backend/api/ticket_actions.py b/products/conversations/backend/api/ticket_actions.py
new file mode 100644
index 000000000000..a4d96386e1ad
--- /dev/null
+++ b/products/conversations/backend/api/ticket_actions.py
@@ -0,0 +1,393 @@
+"""Shared implementation of the ticket API called by CDP workflow actions.
+
+Two routes wrap these handlers with different authentication: the public external route
+(legacy Team.secret_api_token bearer, api/external.py) and the internal service route
+(scoped service JWT, api/internal.py). The worker selects between them per environment
+by config presence (#82564), so the two must behave identically.
+"""
+
+import uuid
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+from django.utils import timezone
+
+from rest_framework import serializers, status
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Tag, Team
+from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
+from posthog.models.activity_logging.model_activity import ActivityTriggerContext
+from posthog.models.tag import tagify
+
+from products.conversations.backend.api.tickets import assign_ticket
+from products.conversations.backend.cache import invalidate_unread_count_cache
+from products.conversations.backend.models import Ticket
+from products.conversations.backend.models.constants import Priority, Status
+from products.conversations.backend.services.sla import WEEKDAYS, compute_sla_deadline
+
+
+class TicketActionUpdateSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(choices=[s.value for s in Status], required=False)
+ priority = serializers.ChoiceField(choices=[p.value for p in Priority], required=False)
+ sla_due_at = serializers.DateTimeField(required=False, allow_null=True)
+ # `sla_amount`/`sla_unit`/`sla_business_hours` are the raw workflow inputs;
+ # the backend computes `sla_due_at` from them so the calculation stays
+ # testable and timezone-aware. Clear still routes through `sla_due_at: null`.
+ sla_amount = serializers.FloatField(required=False, min_value=0.000001)
+ sla_unit = serializers.ChoiceField(choices=["minute", "hour", "day"], required=False, default="hour")
+ sla_business_hours = serializers.JSONField(required=False, allow_null=True)
+ snoozed_until = serializers.DateTimeField(required=False, allow_null=True)
+ assignee = serializers.JSONField(required=False, allow_null=True)
+ tags = serializers.ListField(child=serializers.CharField(max_length=200), required=False, max_length=100)
+ tags_mode = serializers.ChoiceField(choices=["add", "set", "remove"], required=False, default="add")
+
+ def validate_sla_business_hours(self, value):
+ if value is None:
+ return value
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("sla_business_hours must be an object")
+
+ days = value.get("days")
+ if not isinstance(days, list) or not days:
+ raise serializers.ValidationError("sla_business_hours.days must be a non-empty list")
+ unknown = [d for d in days if d not in WEEKDAYS]
+ if unknown:
+ raise serializers.ValidationError(f"Unknown weekday names: {unknown}")
+
+ time_cfg = value.get("time", "any")
+ if time_cfg != "any":
+ if not (isinstance(time_cfg, list) and len(time_cfg) == 2):
+ raise serializers.ValidationError("sla_business_hours.time must be 'any' or [start, end]")
+ if not isinstance(time_cfg[0], str) or not isinstance(time_cfg[1], str):
+ raise serializers.ValidationError("sla_business_hours.time entries must be HH:MM strings")
+ if time_cfg[0] >= time_cfg[1]:
+ raise serializers.ValidationError("sla_business_hours.time start must be strictly before end")
+
+ tz_name = value.get("timezone") or "UTC"
+ if not isinstance(tz_name, str):
+ raise serializers.ValidationError("sla_business_hours.timezone must be a string")
+ try:
+ ZoneInfo(tz_name)
+ except ZoneInfoNotFoundError:
+ raise serializers.ValidationError(f"Invalid timezone: {tz_name}")
+ return value
+
+ def validate(self, attrs):
+ if "sla_due_at" in attrs and "sla_amount" in attrs:
+ raise serializers.ValidationError(
+ {"sla_amount": "Cannot set both sla_due_at and sla_amount in the same request"}
+ )
+ return attrs
+
+
+def validate_ticket_id(ticket_id: str | uuid.UUID) -> Response | None:
+ """Return an error Response if ticket_id is not a valid UUID, else None."""
+ # Django's <uuid:ticket_id> converter passes uuid.UUID; uuid.UUID(uuid_obj)
+ # wrongly treats it as ``hex`` and raises AttributeError.
+ if isinstance(ticket_id, uuid.UUID):
+ return None
+ try:
+ uuid.UUID(str(ticket_id))
+ except (ValueError, AttributeError, TypeError):
+ return Response({"error": "Invalid ticket_id format"}, status=status.HTTP_400_BAD_REQUEST)
+ return None
+
+
+# Header a HogFlow workflow step forwards so activity entries can attribute the change to it.
+HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"
+
+
+def workflow_trigger_from_request(request: Request) -> Trigger | None:
+ """Build an activity-log Trigger when the request originates from a HogFlow workflow step.
+
+ Only the workflow id is taken from the (caller-supplied) header, and only as a well-formed
+ UUID. The display name is resolved from the workflow itself on the frontend, so a token
+ holder can't spoof an arbitrary workflow name into the audit log. Module boundaries keep
+ conversations independent of workflows, so we can't validate id ownership here; both routes
+ authenticate the caller to a single team, so the worst case is a caller pointing attribution
+ at another workflow id within its own team, with no cross-team or privilege impact.
+ """
+ hog_flow_id = request.headers.get(HOG_FLOW_ID_HEADER)
+ if not hog_flow_id:
+ return None
+ try:
+ uuid.UUID(hog_flow_id)
+ except (ValueError, TypeError):
+ return None
+ return Trigger(job_type="hog_flow", job_id=hog_flow_id, payload={})
+
+
+def handle_ticket_get(team: Team, ticket_id: str | uuid.UUID) -> Response:
+ """Fetch a ticket's data for an already-authenticated team."""
+ if error := validate_ticket_id(ticket_id):
+ return error
+
+ try:
+ ticket = Ticket.objects.select_related(
+ "assignment", "assignment__user", "assignment__role", "email_config"
+ ).get(id=ticket_id, team_id=team.id)
+ except Ticket.DoesNotExist:
+ return Response({"error": "Ticket not found"}, status=status.HTTP_404_NOT_FOUND)
+
+ assignee = None
+ assignment = getattr(ticket, "assignment", None)
+ if assignment:
+ assignee = {
+ "id": assignment.user_id if assignment.user_id else str(assignment.role_id) if assignment.role_id else None,
+ "type": "role" if assignment.role_id else "user",
+ "user": {"email": assignment.user.email} if assignment.user_id and assignment.user else None,
+ "role": {"name": assignment.role.name} if assignment.role_id and assignment.role else None,
+ }
+
+ session_context = ticket.session_context or {}
+ tags = list(ticket.tagged_items.values_list("tag__name", flat=True))
+
+ # Hand-built payload, deliberately: neither wrapping route is in the OpenAPI spec (plain
+ # APIViews without scope_object), so the schema-drift risk behind the rule cannot occur,
+ # and the wire shape must stay identical to the legacy external route while the worker
+ # migrates between them (a serializer would re-format datetimes).
+ return Response( # nosemgrep: api-response-must-match-schema
+ {
+ "id": str(ticket.id),
+ "number": ticket.ticket_number,
+ "status": ticket.status,
+ "priority": ticket.priority,
+ "channel_source": ticket.channel_source,
+ "channel_detail": ticket.channel_detail,
+ "distinct_id": ticket.distinct_id,
+ "created_at": ticket.created_at.isoformat(),
+ "updated_at": ticket.updated_at.isoformat(),
+ "message_count": ticket.message_count,
+ "last_message_at": ticket.last_message_at.isoformat() if ticket.last_message_at else None,
+ "last_message_text": ticket.last_message_text,
+ "unread_team_count": ticket.unread_team_count,
+ "unread_customer_count": ticket.unread_customer_count,
+ "sla": ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
+ "snoozed_until": ticket.snoozed_until.isoformat() if ticket.snoozed_until else None,
+ "assignee": assignee,
+ "url": session_context.get("current_url"),
+ "slack_channel_id": ticket.slack_channel_id,
+ "slack_thread_ts": ticket.slack_thread_ts,
+ "slack_team_id": ticket.slack_team_id,
+ "email_subject": ticket.email_subject,
+ "email_from": ticket.email_from,
+ "email_to": ticket.email_config.from_email if ticket.email_config else None,
+ "cc_participants": ticket.cc_participants,
+ "tags": tags,
+ }
+ )
+
+
+def handle_ticket_patch(request: Request, team: Team, ticket_id: str | uuid.UUID) -> Response:
+ """Apply a ticket update for an already-authenticated team."""
+ # When a HogFlow workflow step makes the change, it forwards its identity via
+ # headers so the activity log can attribute (and link to) the workflow.
+ workflow_trigger = workflow_trigger_from_request(request)
+
+ if error := validate_ticket_id(ticket_id):
+ return error
+
+ serializer = TicketActionUpdateSerializer(data=request.data)
+ if not serializer.is_valid():
+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
+
+ try:
+ ticket = Ticket.objects.get(id=ticket_id, team_id=team.id)
+ except Ticket.DoesNotExist:
+ return Response({"error": "Ticket not found"}, status=status.HTTP_404_NOT_FOUND)
+
+ update_fields: list[str] = []
+ changes: list[Change] = []
+
+ new_status = serializer.validated_data.get("status")
+ old_status = ticket.status
+ if new_status is not None:
+ ticket.status = new_status
+ update_fields.append("status")
+
+ if old_status == "resolved" or new_status == "resolved":
+ invalidate_unread_count_cache(team.id)
+
+ if old_status != new_status:
+ changes.append(
+ Change(
+ type="Ticket",
+ field="status",
+ before=old_status,
+ after=new_status,
+ action="changed",
+ )
+ )
+
+ new_priority = serializer.validated_data.get("priority")
+ old_priority = ticket.priority
+ if new_priority is not None:
+ ticket.priority = new_priority
+ update_fields.append("priority")
+
+ if old_priority != new_priority:
+ changes.append(
+ Change(
+ type="Ticket",
+ field="priority",
+ before=old_priority,
+ after=new_priority,
+ action="changed",
+ )
+ )
+
+ old_sla_due_at = ticket.sla_due_at
+ if "sla_due_at" in serializer.validated_data:
+ ticket.sla_due_at = serializer.validated_data["sla_due_at"]
+ update_fields.append("sla_due_at")
+
+ if old_sla_due_at != ticket.sla_due_at:
+ changes.append(
+ Change(
+ type="Ticket",
+ field="sla_due_at",
+ before=old_sla_due_at.isoformat() if old_sla_due_at else None,
+ after=ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
+ action="changed",
+ )
+ )
+ elif "sla_amount" in serializer.validated_data:
+ try:
+ new_sla_due_at = compute_sla_deadline(
+ now=timezone.now(),
+ amount=serializer.validated_data["sla_amount"],
+ unit=serializer.validated_data.get("sla_unit", "hour"),
+ business_hours=serializer.validated_data.get("sla_business_hours"),
+ )
+ except (ValueError, RuntimeError) as e:
+ capture_exception(e, {"ticket_id": str(ticket.id)})
+ return Response({"error": "Invalid SLA configuration."}, status=status.HTTP_400_BAD_REQUEST)
+
+ ticket.sla_due_at = new_sla_due_at
+ if "sla_due_at" not in update_fields:
+ update_fields.append("sla_due_at")
+
+ if old_sla_due_at != ticket.sla_due_at:
+ changes.append(
+ Change(
+ type="Ticket",
+ field="sla_due_at",
+ before=old_sla_due_at.isoformat() if old_sla_due_at else None,
+ after=ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
+ action="changed",
+ )
+ )
+
+ old_snoozed_until = ticket.snoozed_until
+ if "snoozed_until" in serializer.validated_data:
+ ticket.snoozed_until = serializer.validated_data["snoozed_until"]
+ update_fields.append("snoozed_until")
+
+ if old_snoozed_until != ticket.snoozed_until:
+ changes.append(
+ Change(
+ type="Ticket",
+ field="snoozed_until",
+ before=old_snoozed_until.isoformat() if old_snoozed_until else None,
+ after=ticket.snoozed_until.isoformat() if ticket.snoozed_until else None,
+ action="changed",
+ )
+ )
+
+ # Auto-status on snooze transitions (only when status wasn't explicitly set)
+ if new_status is None:
+ auto_status = None
+ if old_snoozed_until is None and ticket.snoozed_until is not None:
+ auto_status = "on_hold"
+ elif old_snoozed_until is not None and ticket.snoozed_until is None:
+ auto_status = "open"
+
+ if auto_status and ticket.status != auto_status:
+ auto_old_status = ticket.status
+ ticket.status = auto_status
+ if "status" not in update_fields:
+ update_fields.append("status")
+ changes.append(
+ Change(
+ type="Ticket",
+ field="status",
+ before=auto_old_status,
+ after=auto_status,
+ action="changed",
+ )
+ )
+
+ if update_fields:
+ ticket.save(update_fields=[*update_fields, "updated_at"])
+
+ if changes:
+ try:
+ log_activity(
+ organization_id=team.organization_id,
+ team_id=team.id,
+ user=None,
+ was_impersonated=False,
+ item_id=str(ticket.id),
+ scope="Ticket",
+ activity="updated",
+ detail=Detail(
+ name=f"Ticket #{ticket.ticket_number}",
+ changes=changes,
+ trigger=workflow_trigger,
+ ),
+ )
+ except Exception as e:
+ capture_exception(e, {"ticket_id": str(ticket.id)})
+
+ if "assignee" in serializer.validated_data:
+ try:
+ assign_ticket(
+ ticket=ticket,
+ assignee=serializer.validated_data.get("assignee"),
+ organization=team.organization,
+ user=None,
+ team_id=team.id,
+ was_impersonated=False,
+ trigger=workflow_trigger,
+ )
+ except Exception as e:
+ capture_exception(e, {"ticket_id": str(ticket.id)})
+ return Response({"error": "Failed to assign ticket"}, status=status.HTTP_400_BAD_REQUEST)
+
+ if "tags" in serializer.validated_data:
+ try:
+ tags_mode = serializer.validated_data.get("tags_mode", "add")
+ normalized_tags = {tagify(t) for t in serializer.validated_data["tags"]}
+
+ # Tag adds and removes are both logged by the TaggedItem model activity signal
+ # (to the ticket's timeline and the Tag audit stream). Removals must go through
+ # the per-instance delete() so the signal fires for them too; a bulk queryset
+ # delete would skip it. The trigger context attributes every resulting entry
+ # to the workflow that made the change.
+ with ActivityTriggerContext(workflow_trigger):
+ if tags_mode == "remove":
+ for tagged_item in ticket.tagged_items.filter(tag__name__in=normalized_tags).select_related(
+ "tag__team", "ticket"
+ ):
+ tagged_item.delete()
+ Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
+ elif tags_mode == "set":
+ for tag_name in normalized_tags:
+ tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
+ ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
+ for tagged_item in ticket.tagged_items.exclude(tag__name__in=normalized_tags).select_related(
+ "tag__team", "ticket"
+ ):
+ tagged_item.delete()
+ Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
+ else:
+ for tag_name in normalized_tags:
+ tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
+ ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
+ except Exception as e:
+ capture_exception(e, {"ticket_id": str(ticket.id)})
+ return Response({"error": "Failed to update tags"}, status=status.HTTP_400_BAD_REQUEST)
+
+ return Response({"ok": True})
diff --git a/products/conversations/backend/metrics.py b/products/conversations/backend/metrics.py
index f76e3fbaa3fa..6f9819db702d 100644
--- a/products/conversations/backend/metrics.py
+++ b/products/conversations/backend/metrics.py
@@ -1,4 +1,13 @@
-from prometheus_client import Histogram
+from prometheus_client import Counter, Histogram
+
+# Cutover observability for #82564: the CDP worker's ticket actions move from
+# secret_api_token on the external route to scoped JWTs on the internal route.
+# The legacy worker path can be removed once auth_method="secret_api_token" stays at zero.
+TICKET_ACTION_AUTH_COUNTER = Counter(
+ "posthog_conversations_ticket_action_auth_total",
+ "Successful authentications on the ticket routes called by CDP workflow actions, by auth method",
+ labelnames=["auth_method", "http_method"], # auth_method: secret_api_token | scoped_jwt
+)
TICKET_SEARCH_DURATION_SECONDS = Histogram(
"posthog_support_ticket_search_duration_seconds",