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): let projects mint the secret key identity verification needs (#74497)

posthog[bot]aa2b03fa0fa7
diff --git a/posthog/api/team.py b/posthog/api/team.py
index ca73034ac5b9..25f637015b9e 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -225,6 +225,11 @@ def validate_secret_token_generation(team: Team, user: User) -> None:
first one is blocked once the team has access to project secret API keys."""
if team.secret_api_token or team.secret_api_token_backup:
return
+ if team.conversations_enabled:
+ # Support signs widget identity hashes with the raw token and authenticates its external
+ # API against it. Project secret API keys are only ever stored hashed, so they cannot
+ # replace it, which would leave Support with no way to verify identity at all.
+ return
if posthoganalytics.feature_enabled(
"project-secret-api-keys",
str(user.distinct_id),
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index c4c6494c6e82..d16f172dbca8 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -704,38 +704,37 @@ def team_api_test_factory():
]
)
+ @parameterized.expand(
+ [
+ ("no_existing_token", None, False, status.HTTP_400_BAD_REQUEST),
+ ("existing_token", "phs_JVRb8fNi0XyIKGgUCyi29ZJUOXEr6NF2dKBy5Ws8XVeF11C", False, status.HTTP_200_OK),
+ # Support has no alternative to this token for signing widget identity hashes
+ ("no_existing_token_conversations_enabled", None, True, status.HTTP_200_OK),
+ ]
+ )
@patch("posthog.api.team.posthoganalytics.feature_enabled", return_value=True)
- def test_generate_first_secret_token_blocked_when_psak_enabled(self, _mock_flag):
- self.organization_membership.level = OrganizationMembership.Level.ADMIN
- self.organization_membership.save()
-
- self.team.secret_api_token = None
- self.team.secret_api_token_backup = None
- self.team.save()
-
- response = self.client.patch(f"/api/environments/{self.team.id}/rotate_secret_token/")
-
- self.team.refresh_from_db()
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("project secret API key", response.json()["detail"])
- self.assertIsNone(self.team.secret_api_token)
-
- @patch("posthog.api.team.posthoganalytics.feature_enabled", return_value=True)
- def test_rotate_existing_secret_token_allowed_when_psak_enabled(self, _mock_flag):
+ def test_secret_token_generation_when_psak_enabled(
+ self, _name, existing_token, conversations_enabled, expected_status, _mock_flag
+ ):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
- secret_api_token = "phs_JVRb8fNi0XyIKGgUCyi29ZJUOXEr6NF2dKBy5Ws8XVeF11C"
- self.team.secret_api_token = secret_api_token
+ self.team.secret_api_token = existing_token
self.team.secret_api_token_backup = None
+ self.team.conversations_enabled = conversations_enabled
self.team.save()
response = self.client.patch(f"/api/environments/{self.team.id}/rotate_secret_token/")
self.team.refresh_from_db()
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertNotEqual(self.team.secret_api_token, secret_api_token)
- self.assertEqual(self.team.secret_api_token_backup, secret_api_token)
+ self.assertEqual(response.status_code, expected_status)
+ if expected_status == status.HTTP_400_BAD_REQUEST:
+ self.assertIn("project secret API key", response.json()["detail"])
+ self.assertIsNone(self.team.secret_api_token)
+ else:
+ self.assertNotEqual(self.team.secret_api_token, existing_token)
+ self.assertTrue((self.team.secret_api_token or "").startswith("phs_"))
+ self.assertEqual(self.team.secret_api_token_backup, existing_token)
@freeze_time("2022-02-08")
def test_delete_secret_backup_token(self):
diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.py
index 70338f4b83fb..5f5240404c64 100644
--- a/products/conversations/backend/api/tests/test_widget.py
+++ b/products/conversations/backend/api/tests/test_widget.py
@@ -654,6 +654,43 @@ class TestWidgetIdentityVerification(BaseTest):
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ def test_list_tickets_without_secret_api_token_is_indistinguishable_from_bad_hash(self):
+ # The widget API is AllowAny, so the "no key configured" response must not reveal
+ # config state to anonymous callers — it stays identical to a signature mismatch.
+ self.team.secret_api_token = None
+ self.team.save()
+
+ response = self.client.get(
+ "/api/conversations/v1/widget/tickets",
+ {
+ "identity_distinct_id": self.distinct_id,
+ "identity_hash": self.identity_hash,
+ },
+ **self._get_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["error"], "Forbidden")
+
+ def test_list_tickets_with_rotated_backup_token(self):
+ # A hash signed with the old secret keeps verifying after rotation moves it to backup.
+ old_secret = self.secret
+ old_hash = compute_identity_hash(self.distinct_id, old_secret)
+ self.team.secret_api_token = "rotated_new_secret"
+ self.team.secret_api_token_backup = old_secret
+ self.team.save()
+ self._create_ticket()
+
+ response = self.client.get(
+ "/api/conversations/v1/widget/tickets",
+ {
+ "identity_distinct_id": self.distinct_id,
+ "identity_hash": old_hash,
+ },
+ **self._get_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["count"], 1)
+
def test_list_tickets_missing_identity_fields_uses_session(self):
self._create_ticket()
response = self.client.get(
diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.py
index b84e4eb8f862..93729d7c7f87 100644
--- a/products/conversations/backend/api/widget.py
+++ b/products/conversations/backend/api/widget.py
@@ -57,10 +57,21 @@ logger = logging.getLogger(__name__)
class IdentityVerificationFailed(Exception):
"""Raised when identity fields are present but HMAC verification fails."""
+ # Surfaced to the widget. Keep it generic so a signature mismatch reveals nothing.
+ public_error = "Forbidden"
+
+
+class IdentityVerificationNotConfigured(IdentityVerificationFailed):
+ """Raised when the team has no secret API key to verify identity hashes against."""
+
+ # The widget API is AllowAny — reachable by anyone with the public widget token — so the
+ # response can't name the cause without leaking config state. Stays "Forbidden" (inherited);
+ # the specific reason is logged server-side for the team's own admins to see.
+
def _verify_identity(data: dict, team: Team) -> str | None:
"""
- Verify HMAC identity fields against team.secret_api_token.
+ Verify HMAC identity fields against the team's secret API token.
Returns the verified distinct_id, or None if identity fields not present.
Raises IdentityVerificationFailed if identity was attempted but failed.
"""
@@ -71,9 +82,15 @@ def _verify_identity(data: dict, team: Team) -> str | None:
if not team.secret_api_token:
logger.warning("Identity verification attempted but team has no secret_api_token")
- raise IdentityVerificationFailed("Team has no secret_api_token")
+ raise IdentityVerificationNotConfigured("Team has no secret_api_token")
+
+ # Accept the backup token during rotation so in-flight verified sessions keep working,
+ # matching the external API's grace period (external.py checks both tokens too).
+ tokens = [team.secret_api_token]
+ if team.secret_api_token_backup:
+ tokens.append(team.secret_api_token_backup)
- if not verify_identity_hash(distinct_id, hash_value, team.secret_api_token):
+ if not any(verify_identity_hash(distinct_id, hash_value, token) for token in tokens):
raise IdentityVerificationFailed("Invalid identity hash")
return distinct_id
@@ -144,8 +161,8 @@ class WidgetMessageView(APIView):
try:
verified_distinct_id = _verify_identity(serializer.validated_data, team)
- except IdentityVerificationFailed:
- return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)
+ except IdentityVerificationFailed as e:
+ return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)
if verified_distinct_id is not None:
distinct_id = verified_distinct_id
@@ -320,8 +337,8 @@ class WidgetMessagesView(APIView):
# Verify ownership: identity mode uses distinct_id, legacy uses widget_session_id
try:
verified_distinct_id = _verify_identity(query_serializer.validated_data, team)
- except IdentityVerificationFailed:
- return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)
+ except IdentityVerificationFailed as e:
+ return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)
if verified_distinct_id is not None:
allowed_ids = get_person_distinct_ids(team.id, verified_distinct_id)
@@ -434,8 +451,8 @@ class WidgetTicketsView(APIView):
try:
verified_distinct_id = _verify_identity(query_serializer.validated_data, team)
- except IdentityVerificationFailed:
- return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)
+ except IdentityVerificationFailed as e:
+ return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)
if verified_distinct_id is not None:
cache_key_id = f"iv:{verified_distinct_id}"
@@ -540,8 +557,8 @@ class WidgetMarkReadView(APIView):
# Verify ownership: identity mode uses distinct_id, legacy uses widget_session_id
try:
verified_distinct_id = _verify_identity(body_serializer.validated_data, team)
- except IdentityVerificationFailed:
- return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)
+ except IdentityVerificationFailed as e:
+ return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)
if verified_distinct_id is not None:
allowed_ids = get_person_distinct_ids(team.id, verified_distinct_id)
diff --git a/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx b/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx
index 205bc3f8a560..17e3060ee6d9 100644
--- a/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx
+++ b/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx
@@ -34,7 +34,7 @@ export function SecretApiKeySection(): JSX.Element {
<SceneSection
title="Secret API key"
titleSize="sm"
- description="Used to sign identity hashes for identity verification and to authenticate external API requests for workflows."
+ description="Signs identity hashes for identity verification, and authenticates external API requests for workflows. Project secret API keys can't be used for either."
>
<LemonCard hoverEffect={false} className="flex flex-col gap-y-2 max-w-[800px] px-4 py-3">
<div>