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): accept project secret API key on ticket GET (#107942)

Patricioaaa22d9e2d02
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index d7ebc7046d6f..a7008bece416 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -213,6 +213,7 @@ export const API_SCOPES: APIScope[] = [
},
{ key: 'sharing_configuration', objectName: 'Sharing configuration', objectPlural: 'sharing configurations' },
{ key: 'subscription', objectName: 'Subscription', objectPlural: 'subscriptions' },
+ { key: 'support_ticket', objectName: 'Support ticket', objectPlural: 'support tickets' },
{
key: 'survey',
objectName: 'Survey',
@@ -290,6 +291,7 @@ export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = [
'feature_flag:read',
'account:read',
'account:write',
+ 'support_ticket:read',
'loop:write',
'experiment:read',
'offline_evaluation_ingestion:write',
@@ -522,6 +524,7 @@ export const API_SCOPE_GROUPS: APIScopeGroup[] = [
'customer_profile_config',
'usage_metric',
'ticket',
+ 'support_ticket',
],
},
{
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 97a8a408edb6..b28aab6c8b48 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -125,6 +125,7 @@ APIScopeObject = Literal[
"stamphog",
"streamlit_app",
"subscription",
+ "support_ticket",
"survey",
"tagger",
"ticket",
@@ -254,6 +255,9 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS
# Lets a service create customer analytics accounts through the external account POST.
# Updates on that route stay team-token only.
("account", "write"),
+ # Conversations external ticket API reads, mirroring the account scope above so
+ # service integrations don't need the team-wide secret_api_token (#63111).
+ ("support_ticket", "read"),
# First write-capable PSAK scope: lets a service credential fire a loop via
# `loops/:id/trigger/`. PSAKs are project-wide, so a leaked key can fire any loop
# in the project (accepted and documented in products/tasks/docs/LOOPS.md).
diff --git a/products/access_control/frontend/generated/api.schemas.ts b/products/access_control/frontend/generated/api.schemas.ts
index 0cdcff5ad7dc..6436464762dd 100644
--- a/products/access_control/frontend/generated/api.schemas.ts
+++ b/products/access_control/frontend/generated/api.schemas.ts
@@ -137,6 +137,7 @@ export const ResolvedAccessSourceSubjectEnumApi = {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -254,6 +255,7 @@ export const ScopeObjectEnumApi = {
Stamphog: 'stamphog',
StreamlitApp: 'streamlit_app',
Subscription: 'subscription',
+ SupportTicket: 'support_ticket',
Survey: 'survey',
Tagger: 'tagger',
Ticket: 'ticket',
@@ -394,6 +396,7 @@ export interface ProjectAccessSourceApi {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -554,6 +557,7 @@ export interface AccessControlObjectRuleApi {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -936,6 +940,7 @@ export interface AccessControlObjectRuleResourceApi {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -1198,6 +1203,7 @@ export interface ResolvedAccessApi {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index 3f2b0a536828..44244148631e 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -10,8 +10,10 @@ route, api/internal.py). Both routes share the handlers in api/ticket_actions.py
"""
import hashlib
+from typing import Any, cast
from django.db.models import Q
+from django.http import HttpRequest
from rest_framework import status
from rest_framework.permissions import AllowAny
@@ -20,7 +22,9 @@ from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView
+from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.models import Team
+from posthog.permissions import get_authenticator_scopes, is_authenticated_via_project_secret_api_key
from products.conversations.backend.api.ticket_actions import (
handle_ticket_get,
@@ -50,6 +54,41 @@ class ExternalTicketSustainedThrottle(_ExternalTicketThrottle):
rate = "1200/hour"
+class ExternalTicketProjectSecretAPIKeyAuthentication(ProjectSecretAPIKeyAuthentication):
+ """Returns None instead of raising when the key's team has conversations disabled, so
+ such a key is indistinguishable from an unknown token."""
+
+ activity_credential_type = "project_secret_key"
+
+ def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
+ result = super().authenticate(request)
+ if result is None:
+ return None
+ team = self.project_secret_api_key.team
+ # This AllowAny view never runs ActiveOrganizationPermission, so the organization
+ # state must be enforced here or a key outlives its deactivated organization.
+ organization = team.organization
+ if not team.conversations_enabled or not organization.is_active or organization.is_pending_deletion:
+ return None
+ return result
+
+
+def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:
+ """Resolve the team from a project secret API key with the ``support_ticket:read`` scope."""
+ if not is_authenticated_via_project_secret_api_key(request):
+ return None, Response({"error": "Missing or invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+
+ authenticator = cast(ExternalTicketProjectSecretAPIKeyAuthentication, request.successful_authenticator)
+ key_scopes = set(get_authenticator_scopes(authenticator) or [])
+ if "*" not in key_scopes and "support_ticket:read" not in key_scopes:
+ return None, Response(
+ {"error": "API key missing required scope 'support_ticket:read'"},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+ return authenticator.project_secret_api_key.team, None
+
+
def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:
"""Extract Bearer token from Authorization header and validate against team."""
auth_header = request.headers.get("Authorization", "")
@@ -80,15 +119,22 @@ class ExternalTicketView(APIView):
GET /api/conversations/external/ticket/<ticket_id> — Fetch ticket data
PATCH /api/conversations/external/ticket/<ticket_id> — Update ticket fields
- Authenticated via Bearer token (team secret_api_token) in Authorization header.
+ GET accepts the team secret_api_token or a project secret API key with the
+ ``support_ticket:read`` scope as a Bearer token. PATCH accepts only the team
+ secret_api_token.
"""
- authentication_classes = []
+ authentication_classes = [ExternalTicketProjectSecretAPIKeyAuthentication]
permission_classes = [AllowAny]
throttle_classes = [ExternalTicketBurstThrottle, ExternalTicketSustainedThrottle]
def get(self, request: Request, ticket_id: str) -> Response:
- team, error = _authenticate_team(request)
+ if is_authenticated_via_project_secret_api_key(request):
+ team, error = _authenticate_psak_team(request)
+ if not error:
+ TICKET_ACTION_AUTH_COUNTER.labels(auth_method="project_secret_api_key", http_method="get").inc()
+ else:
+ team, error = _authenticate_team(request)
if error:
return error
@@ -99,6 +145,11 @@ class ExternalTicketView(APIView):
)
def patch(self, request: Request, ticket_id: str) -> Response:
+ if is_authenticated_via_project_secret_api_key(request):
+ return Response(
+ {"error": "Project secret API keys can only read tickets on this route"},
+ status=status.HTTP_403_FORBIDDEN,
+ )
team, error = _authenticate_team(request)
if error:
return error
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index 1d757acaebd5..3d90263e4dec 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -15,6 +15,7 @@ from rest_framework.test import APIClient
from posthog.models import ActivityLog, Comment, Team
from posthog.models.utils import generate_random_token_secret
+from posthog.test.api_keys import create_project_secret_api_key
from products.conversations.backend.api.ticket_actions import _truncate_bytes
from products.conversations.backend.models import Ticket
@@ -43,8 +44,52 @@ class TestExternalTicketAPI(BaseTest):
def _auth_headers(self, token=None):
return {"HTTP_AUTHORIZATION": f"Bearer {token or self.team.secret_api_token}"}
+ def _create_psak_token(self, scopes, team=None, label="external-ticket"):
+ _, token = create_project_secret_api_key(team or self.team, label=label, scopes=scopes)
+ return token
+
# -- Authentication ---------------------------------------------------
+ def test_get_accepts_project_secret_api_key_with_support_ticket_read_scope(self):
+ response = self.client.get(self.url, **self._auth_headers(self._create_psak_token(["support_ticket:read"])))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["id"], str(self.ticket.id))
+
+ def test_get_rejects_project_secret_api_key_without_support_ticket_scope(self):
+ response = self.client.get(self.url, **self._auth_headers(self._create_psak_token(["endpoint:read"])))
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_patch_rejects_project_secret_api_key(self):
+ response = self.client.patch(
+ self.url,
+ {"status": "resolved"},
+ content_type="application/json",
+ **self._auth_headers(self._create_psak_token(["support_ticket:read"])),
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.ticket.refresh_from_db()
+ self.assertEqual(self.ticket.status, Status.NEW)
+
+ @parameterized.expand(
+ [
+ ("conversations_disabled", {"team": {"conversations_enabled": False}}),
+ ("organization_deactivated", {"organization": {"is_active": False}}),
+ ("organization_active_null", {"organization": {"is_active": None}}),
+ ("organization_pending_deletion", {"organization": {"is_pending_deletion": True}}),
+ ]
+ )
+ def test_psak_is_invisible_when_the_team_or_organization_is_blocked(self, _name, changes):
+ token = self._create_psak_token(["support_ticket:read"])
+ for field, value in changes.get("team", {}).items():
+ setattr(self.team, field, value)
+ self.team.save(update_fields=[field])
+ for field, value in changes.get("organization", {}).items():
+ setattr(self.organization, field, value)
+ self.organization.save(update_fields=[field])
+
+ response = self.client.get(self.url, **self._auth_headers(token))
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
def test_get_requires_auth(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 08f4a27e89eb..7d5158307e5d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -277,6 +277,7 @@ export namespace Schemas {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -395,6 +396,7 @@ export namespace Schemas {
Stamphog: 'stamphog',
StreamlitApp: 'streamlit_app',
Subscription: 'subscription',
+ SupportTicket: 'support_ticket',
Survey: 'survey',
Tagger: 'tagger',
Ticket: 'ticket',
@@ -513,6 +515,7 @@ export namespace Schemas {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -735,6 +738,7 @@ export namespace Schemas {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -1136,6 +1140,7 @@ export namespace Schemas {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
@@ -62079,6 +62084,7 @@ export namespace Schemas {
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
+ * * `support_ticket` - support_ticket
* * `survey` - survey
* * `tagger` - tagger
* * `ticket` - ticket
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index 85eb08f24f15..3fb18ce8a50d 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -190,6 +190,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'streamlit_app:write',
'subscription:read',
'subscription:write',
+ 'support_ticket:read',
+ 'support_ticket:write',
'survey:read',
'survey:write',
'tagger:read',