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: keep legacy secret tokens on legacy paths after PSAK backfill (#111078)

Patricioa64fabf41f2f
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 201b98f8f5fb..2d6243378695 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -326,6 +326,7 @@ rules:
|QuarantinedIdentifier
|QueryTabState
|QueueJob
+ |RevokedTeamSecretToken
|QueueSchedulerDecision
|QueueSchedulerState
|QuickFilter
@@ -763,6 +764,7 @@ rules:
|QuarantinedIdentifier
|QueryTabState
|QueueJob
+ |RevokedTeamSecretToken
|QueueSchedulerDecision
|QueueSchedulerState
|QuickFilter
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index af237b963fe5..50e25291ef9a 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4622,7 +4622,7 @@ export interface UploadedMediaUploadStartedApi {
export interface LeakedKeyReportApi {
/**
- * The leaked PostHog personal API key, project secret API key, or OAuth access/refresh token to revoke.
+ * The leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token to revoke.
* @maxLength 200
*/
token: string
@@ -4631,6 +4631,7 @@ export interface LeakedKeyReportApi {
/**
* * `personal_api_key` - personal_api_key
* * `project_secret_api_key` - project_secret_api_key
+ * * `team_secret_token` - team_secret_token
* * `oauth_access_token` - oauth_access_token
* * `oauth_refresh_token` - oauth_refresh_token
*/
@@ -4640,17 +4641,19 @@ export type LeakedKeyReportResponseTypeEnumApi =
export const LeakedKeyReportResponseTypeEnumApi = {
PersonalApiKey: 'personal_api_key',
ProjectSecretApiKey: 'project_secret_api_key',
+ TeamSecretToken: 'team_secret_token',
OauthAccessToken: 'oauth_access_token',
OauthRefreshToken: 'oauth_refresh_token',
} as const
export interface LeakedKeyReportResponseApi {
- /** Whether a matching PostHog key or token was found and revoked. */
+ /** Whether a matching PostHog key or token was found. It was revoked, or, for team_secret_token, its project admins were told to rotate it. */
found: boolean
- /** The type of key that was found and revoked, or null if no match was found.
+ /** The type of key that was found and revoked, or null if no match was found. team_secret_token means the string is a legacy feature flags secure API key: its migrated project secret API key row was removed, but the legacy key itself cannot be auto-rotated, so project admins are emailed to rotate it.
*
* * `personal_api_key` - personal_api_key
* * `project_secret_api_key` - project_secret_api_key
+ * * `team_secret_token` - team_secret_token
* * `oauth_access_token` - oauth_access_token
* * `oauth_refresh_token` - oauth_refresh_token */
type: LeakedKeyReportResponseTypeEnumApi | null
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 8f442c4446fb..686c1210d5cb 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -2792,7 +2792,7 @@ export const getRevokeLeakedKeyCreateUrl = () => {
}
/**
- * Public, unauthenticated endpoint for self-service revocation of a leaked PostHog personal API key, project secret API key, or OAuth access/refresh token. If the token matches a real credential, it is revoked immediately and the owner is notified by email. This includes an expired OAuth access token: the paired refresh token it protects may still be live.
+ * Public, unauthenticated endpoint for self-service revocation of a leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token. If the token matches a real credential, it is revoked immediately and the owner is notified by email. This includes an expired OAuth access token: the paired refresh token it protects may still be live. A legacy feature flags secure API key is matched through its migrated project secret API key row; it cannot be rotated automatically, so its project admins get an email to rotate it.
*
* This endpoint only checks the region it is running on. `"found": false` does not guarantee the token is safe. If you're not sure which region issued it, check both: https://app.posthog.com/api/revoke_leaked_key and https://eu.posthog.com/api/revoke_leaked_key.
* @summary Report and revoke a leaked PostHog API key or token
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 940c19a7f180..9d1835710214 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -1266,7 +1266,7 @@ export const UploadedMediaStartUploadCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Public, unauthenticated endpoint for self-service revocation of a leaked PostHog personal API key, project secret API key, or OAuth access/refresh token. If the token matches a real credential, it is revoked immediately and the owner is notified by email. This includes an expired OAuth access token: the paired refresh token it protects may still be live.
+ * Public, unauthenticated endpoint for self-service revocation of a leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token. If the token matches a real credential, it is revoked immediately and the owner is notified by email. This includes an expired OAuth access token: the paired refresh token it protects may still be live. A legacy feature flags secure API key is matched through its migrated project secret API key row; it cannot be rotated automatically, so its project admins get an email to rotate it.
*
* This endpoint only checks the region it is running on. `"found": false` does not guarantee the token is safe. If you're not sure which region issued it, check both: https://app.posthog.com/api/revoke_leaked_key and https://eu.posthog.com/api/revoke_leaked_key.
* @summary Report and revoke a leaked PostHog API key or token
@@ -1278,7 +1278,7 @@ export const RevokeLeakedKeyCreateBody = /* @__PURE__ */ zod.object({
.string()
.max(revokeLeakedKeyCreateBodyTokenMax)
.describe(
- 'The leaked PostHog personal API key, project secret API key, or OAuth access\/refresh token to revoke.'
+ 'The leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access\/refresh token to revoke.'
),
})
diff --git a/posthog/admin/admins/project_secret_api_key_admin.py b/posthog/admin/admins/project_secret_api_key_admin.py
index e59a58dbab41..85d3fd9bc9f8 100644
--- a/posthog/admin/admins/project_secret_api_key_admin.py
+++ b/posthog/admin/admins/project_secret_api_key_admin.py
@@ -6,13 +6,13 @@ from django.utils.html import format_html
from django.utils.safestring import SafeString
from posthog.admin.admins.api_key_roll_mixin import RollApiKeyAdminMixin
-from posthog.api.project_secret_api_key import roll_project_secret_api_key_and_notify
+from posthog.api.project_secret_api_key import revoke_exposed_project_secret_api_key
from posthog.models import ProjectSecretAPIKey
@admin.register(ProjectSecretAPIKey)
class ProjectSecretAPIKeyAdmin(RollApiKeyAdminMixin):
- roll_success_message = "Project secret API key rolled and project admins notified."
+ roll_success_message = "Project secret API key revoked and project admins notified."
fields = (
"id",
@@ -61,4 +61,6 @@ class ProjectSecretAPIKeyAdmin(RollApiKeyAdminMixin):
)
def roll_and_notify(self, key: ProjectSecretAPIKey, more_info: str) -> None:
- roll_project_secret_api_key_and_notify(key, more_info)
+ # A row mirroring a legacy team token (#63111) is deleted, not rolled, and the
+ # admins are told to rotate the legacy key — same semantics as the leak webhook.
+ revoke_exposed_project_secret_api_key(key, more_info)
diff --git a/posthog/api/github.py b/posthog/api/github.py
index 17a41c318982..9427c6551d9c 100644
--- a/posthog/api/github.py
+++ b/posthog/api/github.py
@@ -23,6 +23,7 @@ from posthog.api.secret_revocation import (
CANONICAL_OAUTH_REFRESH_TOKEN,
CANONICAL_PERSONAL_API_KEY,
CANONICAL_PROJECT_SECRET_API_KEY,
+ CANONICAL_TEAM_SECRET_TOKEN,
revoke_leaked_secret,
)
from posthog.egress.github.transport import github_request
@@ -260,13 +261,15 @@ class SecretAlert(APIView):
more_info = f"This key was detected by GitHub at {item['url']}."
revocation = revoke_leaked_secret(token, CANONICAL_PROJECT_SECRET_API_KEY, more_info)
local_found = revocation.found
- key_kind = "project_secret_api_key" if revocation.found else None
+ key_kind = revocation.key_type
+ # A leaked team token with a backfilled PSAK row (#63111) matches above, where
+ # _revoke_project_secret_api_key also sends the rotate-your-key notice.
if not revocation.found:
try:
team = Team.objects.get(Q(secret_api_token=token) | Q(secret_api_token_backup=token))
local_found = True
- key_kind = "team_secret_token"
+ key_kind = CANONICAL_TEAM_SECRET_TOKEN
send_feature_flags_secure_api_key_exposed(team.id, mask_key_value(token), more_info)
except Team.DoesNotExist:
diff --git a/posthog/api/leaked_key.py b/posthog/api/leaked_key.py
index 8a768b98b358..1303de4f2a93 100644
--- a/posthog/api/leaked_key.py
+++ b/posthog/api/leaked_key.py
@@ -14,6 +14,7 @@ from posthog.api.secret_revocation import (
CANONICAL_OAUTH_REFRESH_TOKEN,
CANONICAL_PERSONAL_API_KEY,
CANONICAL_PROJECT_SECRET_API_KEY,
+ CANONICAL_TEAM_SECRET_TOKEN,
revoke_leaked_secret,
)
from posthog.rate_limit import LeakedKeyReportThrottle
@@ -27,23 +28,24 @@ class LeakedKeyReportSerializer(serializers.Serializer):
# The longest key we issue is 51 characters. The cap rejects an oversized body
# before any hashing or lookup work happens.
max_length=200,
- help_text="The leaked PostHog personal API key, project secret API key, or OAuth access/refresh token to revoke.",
+ help_text="The leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token to revoke.",
)
class LeakedKeyReportResponseSerializer(serializers.Serializer):
found = serializers.BooleanField(
- help_text="Whether a matching PostHog key or token was found and revoked.",
+ help_text="Whether a matching PostHog key or token was found. It was revoked, or, for team_secret_token, its project admins were told to rotate it.",
)
type = serializers.ChoiceField(
choices=[
CANONICAL_PERSONAL_API_KEY,
CANONICAL_PROJECT_SECRET_API_KEY,
+ CANONICAL_TEAM_SECRET_TOKEN,
CANONICAL_OAUTH_ACCESS_TOKEN,
CANONICAL_OAUTH_REFRESH_TOKEN,
],
allow_null=True,
- help_text="The type of key that was found and revoked, or null if no match was found.",
+ help_text="The type of key that was found and revoked, or null if no match was found. team_secret_token means the string is a legacy feature flags secure API key: its migrated project secret API key row was removed, but the legacy key itself cannot be auto-rotated, so project admins are emailed to rotate it.",
)
@@ -52,8 +54,13 @@ class PublicLeakedKeyReport(APIView):
Public, unauthenticated self-service endpoint: submit a leaked PostHog token and,
if it matches a real credential, it's revoked immediately and the owner is
notified — even if the submitted OAuth access token has itself already expired,
- since the paired refresh token it protects may still be live. Safety relies on
- possession of the plaintext token, not a signature — see secret_revocation.py.
+ since the paired refresh token it protects may still be live. The one exception
+ is a legacy feature flags secure API key, matched through its migrated PSAK row:
+ that row is deleted and the project admins are emailed to rotate the key, which
+ cannot be rotated automatically. A legacy key with no migrated row (none exists
+ before the #63111 backfill) is simply not found.
+ Safety relies on possession of the plaintext token, not a signature — see
+ secret_revocation.py.
Region-local only, no cross-region relay: a "found": false result does not rule
out the token being live in the other region. See the endpoint description below.
@@ -79,10 +86,13 @@ class PublicLeakedKeyReport(APIView):
summary="Report and revoke a leaked PostHog API key or token",
description=(
"Public, unauthenticated endpoint for self-service revocation of a leaked PostHog "
- "personal API key, project secret API key, or OAuth access/refresh token. If the "
- "token matches a real credential, it is revoked immediately and the owner is "
- "notified by email. This includes an expired OAuth access token: the paired "
- "refresh token it protects may still be live.\n\n"
+ "personal API key, project secret API key, legacy feature flags secure API key, or "
+ "OAuth access/refresh token. If the token matches a real credential, it is revoked "
+ "immediately and the owner is notified by email. This includes an expired OAuth "
+ "access token: the paired refresh token it protects may still be live. A legacy "
+ "feature flags secure API key is matched through its migrated project secret API "
+ "key row; it cannot be rotated automatically, so its project admins get an email "
+ "to rotate it.\n\n"
'This endpoint only checks the region it is running on. `"found": false` does not '
"guarantee the token is safe. If you're not sure which region issued it, check "
"both: https://app.posthog.com/api/revoke_leaked_key and "
diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.py
index ff765de1b3b5..cb1aac4728c7 100644
--- a/posthog/api/project_secret_api_key.py
+++ b/posthog/api/project_secret_api_key.py
@@ -1,7 +1,7 @@
from collections.abc import Iterable
from typing import cast
-from django.db import IntegrityError
+from django.db import IntegrityError, transaction
from django.db.models import QuerySet
from django.utils import timezone
@@ -16,7 +16,7 @@ from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.models import User
-from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey, RevokedTeamSecretToken
from posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_value
from posthog.permissions import (
TeamMemberStrictManagementPermission,
@@ -30,7 +30,7 @@ from posthog.scopes import (
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
scopes_not_covered,
)
-from posthog.tasks.email import send_project_secret_api_key_exposed
+from posthog.tasks.email import send_feature_flags_secure_api_key_exposed, send_project_secret_api_key_exposed
MAX_PROJECT_SECRET_API_KEYS_PER_TEAM = 50
@@ -204,6 +204,31 @@ def roll_project_secret_api_key_and_notify(project_secret_api_key: ProjectSecret
)
+def revoke_exposed_project_secret_api_key(project_secret_api_key: ProjectSecretAPIKey, more_info: str) -> bool:
+ """Revoke an exposed key the right way for what it actually is, and return whether it
+ was a mirrored legacy team token.
+
+ A backfilled PSAK (#63111) mirrors the team's legacy secret token: deleting the row
+ is the revocation (rolling would mint an unrelated key that later rotation cannot
+ clean up), and the admins must still rotate the legacy token itself. Any other key
+ gets the ordinary roll-and-notify.
+ """
+ team = project_secret_api_key.team
+ for token in (team.secret_api_token, team.secret_api_token_backup):
+ if token and project_secret_api_key.secure_value == hash_key_value(token):
+ with transaction.atomic():
+ # Remember the hash: the pre-drop rerun of the #63111 backfill must not
+ # give this still-unrotated leaked token a fresh mirror row.
+ RevokedTeamSecretToken.objects.for_team(team.id).get_or_create(
+ team_id=team.id, secure_value=project_secret_api_key.secure_value
+ )
+ project_secret_api_key.delete()
+ send_feature_flags_secure_api_key_exposed(team.id, mask_key_value(token), more_info)
+ return True
+ roll_project_secret_api_key_and_notify(project_secret_api_key, more_info)
+ return False
+
+
@extend_schema(extensions={"x-product": "core"})
class ProjectSecretAPIKeyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "project"
diff --git a/posthog/api/secret_revocation.py b/posthog/api/secret_revocation.py
index c97fa16f1e44..31100178fea9 100644
--- a/posthog/api/secret_revocation.py
+++ b/posthog/api/secret_revocation.py
@@ -2,7 +2,7 @@ import re
from typing import Literal
from posthog.api.personal_api_key import PersonalAPIKeySerializer
-from posthog.api.project_secret_api_key import roll_project_secret_api_key_and_notify
+from posthog.api.project_secret_api_key import revoke_exposed_project_secret_api_key
from posthog.dataclasses import frozen
from posthog.models.oauth import find_oauth_access_token, find_oauth_refresh_token, revoke_oauth_token_session
from posthog.models.personal_api_key import find_personal_api_key
@@ -18,6 +18,9 @@ from posthog.tasks.email import send_oauth_token_exposed, send_personal_api_key_
CANONICAL_PERSONAL_API_KEY = "personal_api_key"
CANONICAL_PROJECT_SECRET_API_KEY = "project_secret_api_key"
+# Never a lookup key for revoke_leaked_secret (team tokens can't be auto-rotated); only
+# reported back when the matched PSAK row turns out to mirror a team token.
+CANONICAL_TEAM_SECRET_TOKEN = "team_secret_token"
CANONICAL_OAUTH_ACCESS_TOKEN = "oauth_access_token"
CANONICAL_OAUTH_REFRESH_TOKEN = "oauth_refresh_token"
@@ -31,27 +34,27 @@ class RevocationResult:
return self.key_type is not None
-def _revoke_personal_api_key(token: str, more_info: str) -> bool:
+def _revoke_personal_api_key(token: str, more_info: str) -> str | None:
key_lookup = find_personal_api_key(token)
if key_lookup is None:
- return False
+ return None
key, _ = key_lookup
old_mask_value = key.mask_value
serializer = PersonalAPIKeySerializer(instance=key)
serializer.roll(key)
send_personal_api_key_exposed(key.user.id, key.id, old_mask_value, more_info)
- return True
+ return CANONICAL_PERSONAL_API_KEY
-def _revoke_project_secret_api_key(token: str, more_info: str) -> bool:
+def _revoke_project_secret_api_key(token: str, more_info: str) -> str | None:
project_secret_api_key = find_project_secret_api_key(token)
if project_secret_api_key is None:
- return False
- roll_project_secret_api_key_and_notify(project_secret_api_key, more_info)
- return True
+ return None
+ was_team_token = revoke_exposed_project_secret_api_key(project_secret_api_key, more_info)
+ return CANONICAL_TEAM_SECRET_TOKEN if was_team_token else CANONICAL_PROJECT_SECRET_API_KEY
-def _revoke_oauth_token(token: str, more_info: str, *, kind: Literal["access", "refresh"]) -> bool:
+def _revoke_oauth_token(token: str, more_info: str, *, kind: Literal["access", "refresh"]) -> str | None:
# Deliberately no expiry check on the access-token match: an already-expired token
# can't authenticate on its own, but revoking still matters if the same exposure
# also affects the paired refresh token (up to 30 days live). Gating this on
@@ -64,7 +67,7 @@ def _revoke_oauth_token(token: str, more_info: str, *, kind: Literal["access", "
if kind == "access":
access_token = find_oauth_access_token(token)
if access_token is None:
- return False
+ return None
# Scoped to this one access/refresh token pair, not every session the user has
# with the application - a leaked-token report is evidence about that one
# token, not the user's other sessions. See revoke_oauth_token_session.
@@ -73,19 +76,19 @@ def _revoke_oauth_token(token: str, more_info: str, *, kind: Literal["access", "
else:
refresh_token = find_oauth_refresh_token(token)
if refresh_token is None:
- return False
+ return None
revoke_oauth_token_session(refresh_token=refresh_token)
user = refresh_token.user
if user:
send_oauth_token_exposed(user.id, kind, mask_key_value(token), more_info)
- return True
+ return CANONICAL_OAUTH_ACCESS_TOKEN if kind == "access" else CANONICAL_OAUTH_REFRESH_TOKEN
-def _revoke_oauth_access_token(token: str, more_info: str) -> bool:
+def _revoke_oauth_access_token(token: str, more_info: str) -> str | None:
return _revoke_oauth_token(token, more_info, kind="access")
-def _revoke_oauth_refresh_token(token: str, more_info: str) -> bool:
+def _revoke_oauth_refresh_token(token: str, more_info: str) -> str | None:
return _revoke_oauth_token(token, more_info, kind="refresh")
@@ -118,7 +121,8 @@ _REVOKERS = {
# four, a match there can't be auto-rotated on the spot
# (Team.rotate_secret_token_and_save needs a user to attribute the rotation to), so
# github.py handles that case itself as a fallback rather than through this shared,
-# type-agnostic path.
+# type-agnostic path. A team token with a backfilled PSAK row (#63111) does match the
+# project-secret-api-key path, which then also sends the rotate-your-key notice.
_PREFIX_TO_CANONICAL_TYPE = {
PERSONAL_API_KEY_PREFIX: CANONICAL_PERSONAL_API_KEY,
SECRET_API_TOKEN_PREFIX: CANONICAL_PROJECT_SECRET_API_KEY,
@@ -163,10 +167,13 @@ def _detect_canonical_type(token: str) -> str | None:
def revoke_leaked_secret(token: str, key_type: str | None, more_info: str) -> RevocationResult:
"""Look up `token` as a leaked credential and revoke+notify on a match.
- If `key_type` is one of the CANONICAL_* constants, only that lookup runs.
- If `key_type` is None, the token's prefix determines which single lookup runs.
+ `key_type` must be one of the four lookup types (personal_api_key,
+ project_secret_api_key, oauth_access_token, oauth_refresh_token) or None, in which
+ case the token's prefix determines which single lookup runs. The result's key_type
+ can be narrower than the lookup: a "phs_" match that mirrors a team token comes
+ back as CANONICAL_TEAM_SECRET_TOKEN, which is never itself a valid lookup type.
"""
resolved_type = key_type if key_type is not None else _detect_canonical_type(token)
- if resolved_type is not None and _REVOKERS[resolved_type](token, more_info):
- return RevocationResult(key_type=resolved_type)
- return RevocationResult(key_type=None)
+ if resolved_type is None:
+ return RevocationResult(key_type=None)
+ return RevocationResult(key_type=_REVOKERS[resolved_type](token, more_info))
diff --git a/posthog/api/test/test_github.py b/posthog/api/test/test_github.py
index 62c5e3ab4ae7..8a3a53656b44 100644
--- a/posthog/api/test/test_github.py
+++ b/posthog/api/test/test_github.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
from django.test import TestCase, override_settings
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
from posthog import redis
@@ -23,6 +24,7 @@ from posthog.api.github import (
from posthog.models import PersonalAPIKey
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthRefreshToken
from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey, RevokedTeamSecretToken
from posthog.models.utils import (
generate_random_token_personal,
generate_random_token_secret,
@@ -626,6 +628,37 @@ class TestProjectSecretAPIKeySecretAlert(APIBaseTest):
mock_ff_exposed.assert_called_once()
mock_psak_exposed.assert_not_called()
+ @parameterized.expand([("primary", "secret_api_token"), ("backup", "secret_api_token_backup")])
+ @patch("posthog.api.github.posthoganalytics.capture")
+ @patch("posthog.api.github.verify_github_signature")
+ @patch("posthog.api.project_secret_api_key.send_feature_flags_secure_api_key_exposed")
+ @patch("posthog.api.project_secret_api_key.send_project_secret_api_key_exposed")
+ def test_leaked_team_token_with_backfilled_psak_deletes_the_row_and_notifies(
+ self, _name, token_field, mock_psak_exposed, mock_ff_exposed, mock_verify, mock_capture
+ ):
+ # The backfilled row IS the leaked legacy credential: revocation deletes it and
+ # tells the admins to rotate the still-valid team token, exactly once.
+ mock_verify.return_value = None
+ token = "phs_legacy_team_secret_token_123"
+ self.team.secret_api_token = "phs_some_current_primary_value" if token_field != "secret_api_token" else token
+ setattr(self.team, token_field, token)
+ self.team.save()
+ row, _ = create_project_secret_api_key(team=self.team, label="Migrated legacy secret API key", value=token)
+
+ response = self._post_alert([token])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()[0]["label"], "true_positive")
+ self.assertFalse(ProjectSecretAPIKey.objects.filter(pk=row.pk).exists())
+ self.assertTrue(
+ RevokedTeamSecretToken.objects.for_team(self.team.id).filter(secure_value=hash_key_value(token)).exists()
+ )
+ mock_psak_exposed.assert_not_called()
+ mock_ff_exposed.assert_called_once()
+ alert_events = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "github_secret_alert"]
+ self.assertEqual(len(alert_events), 1)
+ self.assertEqual(alert_events[0].kwargs["properties"]["key_kind"], "team_secret_token")
+
@patch("posthog.api.github.verify_github_signature")
@patch("posthog.api.github.send_feature_flags_secure_api_key_exposed")
@patch("posthog.api.project_secret_api_key.send_project_secret_api_key_exposed")
diff --git a/posthog/api/test/test_leaked_key.py b/posthog/api/test/test_leaked_key.py
index 456ac8114d0b..070daa0f3edb 100644
--- a/posthog/api/test/test_leaked_key.py
+++ b/posthog/api/test/test_leaked_key.py
@@ -27,7 +27,11 @@ from posthog.models.oauth import (
find_oauth_refresh_token,
)
from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, find_personal_api_key
-from posthog.models.project_secret_api_key import find_project_secret_api_key
+from posthog.models.project_secret_api_key import (
+ ProjectSecretAPIKey,
+ RevokedTeamSecretToken,
+ find_project_secret_api_key,
+)
from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value
from posthog.rate_limit import LeakedKeyReportThrottle
from posthog.test.api_keys import create_project_secret_api_key
@@ -204,6 +208,33 @@ class TestPublicLeakedKeyReport(APIBaseTest):
self.team.refresh_from_db()
self.assertEqual(self.team.secret_api_token, token)
+ @parameterized.expand([("primary", "secret_api_token"), ("backup", "secret_api_token_backup")])
+ @patch("posthog.api.project_secret_api_key.send_feature_flags_secure_api_key_exposed")
+ @patch("posthog.api.project_secret_api_key.send_project_secret_api_key_exposed")
+ def test_team_token_with_backfilled_psak_deletes_the_row_and_notifies_admins(
+ self, _name, token_field, mock_psak_exposed, mock_ff_exposed
+ ) -> None:
+ # The backfilled row IS the leaked legacy credential: revocation deletes it and
+ # tells the admins to rotate the still-valid team token.
+ token = "phs_legacy_team_secret_token_with_migrated_row"
+ self.team.secret_api_token = "phs_some_current_primary_value" if token_field != "secret_api_token" else token
+ setattr(self.team, token_field, token)
+ self.team.save()
+ row, _ = create_project_secret_api_key(team=self.team, label="Migrated legacy secret API key", value=token)
+
+ response = self._post(token)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": True, "type": "team_secret_token"})
+ self.assertFalse(ProjectSecretAPIKey.objects.filter(pk=row.pk).exists())
+ self.assertTrue(
+ RevokedTeamSecretToken.objects.for_team(self.team.id).filter(secure_value=hash_key_value(token)).exists()
+ )
+ self.team.refresh_from_db()
+ self.assertEqual(getattr(self.team, token_field), token)
+ mock_psak_exposed.assert_not_called()
+ mock_ff_exposed.assert_called_once()
+
def test_expired_oauth_access_token_still_revokes_the_paired_refresh_token(self) -> None:
# An expired access token can't authenticate on its own, but revoking still
# matters: if the same exposure also affects the longer-lived paired refresh
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 073256ff4249..b7da400ecd96 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -42,9 +42,11 @@ from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.product_intent import ProductIntent
from posthog.models.project import Project
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.api_keys import create_project_secret_api_key
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from posthog.utils import get_context_for_template, get_instance_realm
@@ -754,6 +756,47 @@ def team_api_test_factory():
]
)
+ def test_retiring_a_legacy_token_deletes_its_migrated_psak_row(self):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ primary = "phs_JVRb8fNi0XyIKGgUCyi29ZJUOXEr6NF2dKBy5Ws8XVeF11C"
+ backup = "phs_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ self.team.secret_api_token = primary
+ self.team.secret_api_token_backup = backup
+ self.team.save()
+ for token, label in ((primary, "Migrated legacy secret API key"), (backup, "Migrated legacy key (backup)")):
+ create_project_secret_api_key(team=self.team, label=label, value=token)
+
+ # Rotation drops the old backup; its PSAK row must stop authenticating with it.
+ response = self.client.patch(f"/api/environments/{self.team.id}/rotate_secret_token/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertFalse(ProjectSecretAPIKey.objects.filter(secure_value=hash_key_value(backup)).exists())
+ self.assertTrue(ProjectSecretAPIKey.objects.filter(secure_value=hash_key_value(primary)).exists())
+
+ # Deleting the backup (the rotated-out primary) retires its row too.
+ response = self.client.patch(f"/api/environments/{self.team.id}/delete_secret_token_backup/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertFalse(ProjectSecretAPIKey.objects.filter(secure_value=hash_key_value(primary)).exists())
+
+ def test_retiring_a_token_never_touches_another_teams_row(self):
+ # secure_value is globally unique, so when two teams hold the same string the
+ # single row belongs to one of them — retiring the other team's token must
+ # not delete it.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ token = "phs_string_shared_by_two_teams_somehow"
+ self.team.secret_api_token = "phs_this_teams_own_primary_token_value"
+ self.team.secret_api_token_backup = token
+ self.team.save()
+ other_team = Team.objects.create(organization=self.organization, project=self.project, name="other")
+ row, _ = create_project_secret_api_key(team=other_team, label="Twin value", value=token)
+
+ response = self.client.patch(f"/api/environments/{self.team.id}/delete_secret_token_backup/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(ProjectSecretAPIKey.objects.filter(pk=row.pk).exists())
+
@parameterized.expand(
[
("no_existing_token", None, False, status.HTTP_400_BAD_REQUEST),
diff --git a/posthog/auth.py b/posthog/auth.py
index 87e065765f75..9348cd0d2f86 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -484,6 +484,9 @@ class ProjectSecretAPIKeyAuthentication(ActivityCredentialMixin, authentication.
keyword = "Bearer"
activity_credential_type = "project_secret_key"
+ # True on routes where a backfilled PSAK (#63111) mirroring the team's legacy token
+ # must fall through to the route's legacy branch; transitional until #66179.
+ defer_migrated_team_tokens = False
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
token = _extract_phs_token(request)
@@ -494,6 +497,12 @@ class ProjectSecretAPIKeyAuthentication(ActivityCredentialMixin, authentication.
if psak is None:
return None
+ if self.defer_migrated_team_tokens and token in (
+ psak.team.secret_api_token,
+ psak.team.secret_api_token_backup,
+ ):
+ return None
+
now = timezone.now()
if psak.last_used_at is None or (now - psak.last_used_at > timedelta(hours=1)):
# Use .update() to bypass ModelActivityMixin save hooks and avoid
diff --git a/posthog/migrations/1393_revokedteamsecrettoken.py b/posthog/migrations/1393_revokedteamsecrettoken.py
new file mode 100644
index 000000000000..13b56f45f560
--- /dev/null
+++ b/posthog/migrations/1393_revokedteamsecrettoken.py
@@ -0,0 +1,45 @@
+# Generated by Django 5.2.17 on 2026-10-06 14:11
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1392_organization_member_notice"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="RevokedTeamSecretToken",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "secure_value",
+ models.CharField(editable=False, max_length=300, unique=True),
+ ),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="revoked_secret_token_hashes",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_revokedteamsecrettoken",
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index b283947272ca..16c58978aae0 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1392_organization_member_notice
+1393_revokedteamsecrettoken
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 5303ea01d1fd..cd502fc6c937 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -51,7 +51,7 @@ from .organization_invite import OrganizationInvite, InviteExpiredException
from .organization_provisioning import OrganizationProvisioning
from .person import Person, PersonDistinctId, PersonOverride, PersonOverrideMapping
from .personal_api_key import PersonalAPIKey
-from .project_secret_api_key import ProjectSecretAPIKey
+from .project_secret_api_key import ProjectSecretAPIKey, RevokedTeamSecretToken
from .product_intent import ProductIntent
from .project import Project
from .property import Property
@@ -146,6 +146,7 @@ __all__ = [
"PersonDistinctId",
"PersonalAPIKey",
"ProjectSecretAPIKey",
+ "RevokedTeamSecretToken",
"PersonOverride",
"PersonOverrideMapping",
"ProductIntent",
diff --git a/posthog/models/project_secret_api_key.py b/posthog/models/project_secret_api_key.py
index 559789ee03d5..ca7af3582138 100644
--- a/posthog/models/project_secret_api_key.py
+++ b/posthog/models/project_secret_api_key.py
@@ -6,6 +6,7 @@ from django.db import models
from django.utils import timezone
from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.scoping.manager import TeamScopedManager
from .utils import generate_random_token, hash_key_value
@@ -67,3 +68,35 @@ def find_project_secret_api_key(token: str) -> Optional["ProjectSecretAPIKey"]:
return ProjectSecretAPIKey.objects.select_related("team").get(secure_value=secure_value)
except ProjectSecretAPIKey.DoesNotExist:
return None
+
+
+class RevokedTeamSecretToken(models.Model):
+ """Hash of a legacy team secret token whose migrated PSAK mirror row (#63111) was
+ deleted by leak revocation. The pre-drop rerun of the backfill reads these, so a
+ leaked token that was never rotated does not get a fresh mirror row.
+
+ TeamScopedManager without RootTeamMixin: tokens are environment-scoped, and the
+ canonical-team save() rewrite would file a child environment's hash under its root.
+ """
+
+ # db_constraint=False: a real FK to the hot posthog_team table needs a parent lock
+ # to create. ORM-level CASCADE still removes rows when the team goes.
+ team = models.ForeignKey(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ related_name="revoked_secret_token_hashes",
+ db_constraint=False,
+ )
+ secure_value = models.CharField(max_length=300, unique=True, editable=False)
+ created_at = models.DateTimeField(default=timezone.now)
+
+ objects = TeamScopedManager["RevokedTeamSecretToken"]()
+
+ class Meta:
+ db_table = "posthog_revokedteamsecrettoken"
+
+
+def delete_project_secret_api_keys_for_token(team_id: int, token: str) -> None:
+ """A PSAK row whose hash equals a retired legacy token IS that credential: it must
+ stop authenticating when the token does (#63111 backfill)."""
+ ProjectSecretAPIKey.objects.filter(team_id=team_id, secure_value=hash_key_value(token)).delete()
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index 997cac5ad11c..7dce6d387001 100644
--- a/posthog/models/team/team.py
+++ b/posthog/models/team/team.py
@@ -24,6 +24,7 @@ from posthog.models.filters.mixins.utils import cached_property
from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.instance_setting import get_instance_setting
from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.project_secret_api_key import delete_project_secret_api_keys_for_token
from posthog.models.signals import mutable_receiver, secret_api_token_rotated
from posthog.models.utils import (
UUIDTClassicModel,
@@ -990,6 +991,10 @@ class Team(UUIDTClassicModel):
self.secret_api_token = new_token
self.secret_api_token_backup = old_primary_token
self.save()
+ if expired_token:
+ # The migrated PSAK row holding this exact token (#63111 backfill) must
+ # retire with it, or the dropped token keeps authenticating via PSAK.
+ delete_project_secret_api_keys_for_token(self.id, expired_token)
secret_api_token_rotated.send(sender=self.__class__, team=self)
except Exception:
# save() already cached this team (post_save) with the new tokens, which the
@@ -1120,7 +1125,6 @@ class Team(UUIDTClassicModel):
def delete_secret_token_backup_and_save(self, *, user: "User", is_impersonated_session: bool):
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
- from posthog.models.utils import mask_key_value
old_backup_token = self.secret_api_token_backup
if not old_backup_token:
@@ -1128,8 +1132,17 @@ class Team(UUIDTClassicModel):
return
masked_old_backup_token = mask_key_value(old_backup_token)
- self.secret_api_token_backup = None
- self.save()
+ try:
+ with transaction.atomic():
+ self.secret_api_token_backup = None
+ self.save()
+ delete_project_secret_api_keys_for_token(self.id, old_backup_token)
+ except Exception:
+ # save() already cached this team (post_save) with the cleared backup, which
+ # the rollback discarded. Rewrite that entry from the committed row.
+ self.refresh_from_db(fields=["secret_api_token_backup"])
+ set_team_in_cache(self.api_token, self)
+ raise
set_team_in_cache(old_backup_token, None)
log_activity(
diff --git a/posthog/test/api_keys.py b/posthog/test/api_keys.py
index ea95e7114a99..3079237fc42a 100644
--- a/posthog/test/api_keys.py
+++ b/posthog/test/api_keys.py
@@ -7,10 +7,12 @@ def create_project_secret_api_key(
created_by: User | None = None,
label: str = "Test key",
scopes: list[str] | None = None,
+ value: str | None = None,
) -> tuple[ProjectSecretAPIKey, str]:
"""Create a PSAK the way the API does (hashed secure_value, masked display value) and
- return it along with the plaintext token, which is never stored."""
- value = generate_random_token_secret()
+ return it along with the plaintext token, which is never stored. Pass ``value`` to
+ build the row the #63111 backfill writes for an existing legacy token."""
+ value = value or generate_random_token_secret()
key = ProjectSecretAPIKey.objects.create(
team=team,
label=label,
diff --git a/posthog/test/test_project_secret_api_key_admin.py b/posthog/test/test_project_secret_api_key_admin.py
index 5df3923b7b7f..634abd5a03a1 100644
--- a/posthog/test/test_project_secret_api_key_admin.py
+++ b/posthog/test/test_project_secret_api_key_admin.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patch
from django.test import Client, override_settings
+from posthog.models.project_secret_api_key import RevokedTeamSecretToken
from posthog.test.api_keys import create_project_secret_api_key
@@ -38,6 +39,26 @@ class TestProjectSecretAPIKeyAdmin(BaseTest):
self.team.id, self.key.id, old_mask_value, "This key was detected at https://github.com/some/leak."
)
+ @patch("posthog.api.project_secret_api_key.send_feature_flags_secure_api_key_exposed")
+ @patch("posthog.api.project_secret_api_key.send_project_secret_api_key_exposed")
+ def test_roll_deletes_mirrored_legacy_row_and_notifies_admins(
+ self, mock_psak_exposed: MagicMock, mock_ff_exposed: MagicMock
+ ):
+ token = "phs_legacy_token_mirrored_in_admin"
+ self.team.secret_api_token = token
+ self.team.save()
+ mirrored, _ = create_project_secret_api_key(team=self.team, label="Migrated legacy secret API key", value=token)
+
+ response = self.client.post(f"/admin/posthog/projectsecretapikey/{mirrored.pk}/roll/", data={"_roll_url": ""})
+
+ self.assertEqual(response.status_code, 302)
+ self.assertFalse(type(mirrored).objects.filter(pk=mirrored.pk).exists())
+ self.assertTrue(RevokedTeamSecretToken.objects.for_team(self.team.id).filter().exists())
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.secret_api_token, token)
+ mock_ff_exposed.assert_called_once()
+ mock_psak_exposed.assert_not_called()
+
@patch("posthog.api.project_secret_api_key.send_project_secret_api_key_exposed")
def test_roll_requires_post(self, mock_exposed: MagicMock):
response = self.client.get(self.roll_url)
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index 44244148631e..b243ec5920a7 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -59,6 +59,9 @@ class ExternalTicketProjectSecretAPIKeyAuthentication(ProjectSecretAPIKeyAuthent
such a key is indistinguishable from an unknown token."""
activity_credential_type = "project_secret_key"
+ # A migrated legacy token (#63111) must keep the legacy path: PATCH accepts it there
+ # but refuses PSAKs, and the legacy-usage counters would otherwise go silent.
+ defer_migrated_team_tokens = True
def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
result = super().authenticate(request)
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index 3d90263e4dec..072adc0a19df 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -70,6 +70,22 @@ class TestExternalTicketAPI(BaseTest):
self.ticket.refresh_from_db()
self.assertEqual(self.ticket.status, Status.NEW)
+ @parameterized.expand([("primary", "secret_api_token"), ("backup", "secret_api_token_backup")])
+ def test_patch_accepts_legacy_token_that_has_a_migrated_psak_row(self, _name, token_field):
+ # The #63111 backfill gives the legacy token a PSAK row with the same hash. The
+ # legacy string (primary or rotated-out backup) must keep the legacy path
+ # (PATCH allowed), not resolve as a PSAK.
+ token = generate_random_token_secret()
+ setattr(self.team, token_field, token)
+ self.team.save(update_fields=[token_field])
+ create_project_secret_api_key(self.team, label="Migrated legacy secret API key", value=token)
+ response = self.client.patch(
+ self.url, {"status": "resolved"}, content_type="application/json", **self._auth_headers(token)
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.ticket.refresh_from_db()
+ self.assertEqual(self.ticket.status, Status.RESOLVED)
+
@parameterized.expand(
[
("conversations_disabled", {"team": {"conversations_enabled": False}}),
diff --git a/products/conversations/backend/tests/test_signing_secret.py b/products/conversations/backend/tests/test_signing_secret.py
index 2b522916f4b6..810526f9fe46 100644
--- a/products/conversations/backend/tests/test_signing_secret.py
+++ b/products/conversations/backend/tests/test_signing_secret.py
@@ -5,8 +5,10 @@ from django.db import OperationalError
from parameterized import parameterized
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team import Team
from posthog.models.team.team_caching import get_team_in_cache
+from posthog.test.api_keys import create_project_secret_api_key
from products.conversations.backend.models import SigningSecret
@@ -43,6 +45,11 @@ class TestSigningSecret(BaseTest):
SigningSecret.objects.for_team(self.team.id).update_or_create(
team=self.team, defaults={"secret": "phs_previous_secret"}
)
+ # A migrated PSAK row (#63111) for the backup the rotation was about to retire
+ # must survive the rollback along with the backup token itself.
+ backup_row, _ = create_project_secret_api_key(
+ self.team, label="Migrated legacy key (backup)", value="phs_expired_backup"
+ )
with patch.object(SigningSecret.objects, "for_team", side_effect=OperationalError("connection lost")):
with self.assertRaises(OperationalError):
@@ -58,6 +65,29 @@ class TestSigningSecret(BaseTest):
assert cached is not None
self.assertEqual(cached.secret_api_token, "phs_previous_secret")
self.assertEqual(cached.secret_api_token_backup, "phs_expired_backup")
+ self.assertTrue(ProjectSecretAPIKey.objects.filter(pk=backup_row.pk).exists())
+
+ def test_failed_backup_cleanup_rolls_the_deletion_back(self):
+ self.team.secret_api_token = "phs_current_primary_value"
+ self.team.secret_api_token_backup = "phs_backup_pending_deletion"
+ self.team.save()
+ backup_row, _ = create_project_secret_api_key(
+ self.team, label="Migrated legacy key (backup)", value="phs_backup_pending_deletion"
+ )
+
+ with patch(
+ "posthog.models.team.team.delete_project_secret_api_keys_for_token",
+ side_effect=OperationalError("connection lost"),
+ ):
+ with self.assertRaises(OperationalError):
+ self.team.delete_secret_token_backup_and_save(user=self.user, is_impersonated_session=False)
+
+ # The rollback must restore the instance and the cache, so a retry actually retries.
+ self.assertEqual(self.team.secret_api_token_backup, "phs_backup_pending_deletion")
+ cached = get_team_in_cache(self.team.api_token)
+ assert cached is not None
+ self.assertEqual(cached.secret_api_token_backup, "phs_backup_pending_deletion")
+ self.assertTrue(ProjectSecretAPIKey.objects.filter(pk=backup_row.pk).exists())
def test_child_environment_keeps_its_own_team_on_save(self):
# Environment-scoped by design: a canonicalizing save() (RootTeamMixin) would rewrite
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 207c61e602a6..959f14e46e8b 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -141,6 +141,9 @@ class ExternalAccountProjectSecretAPIKeyAuthentication(ProjectSecretAPIKeyAuthen
cannot reveal that the key exists or which scopes it carries."""
activity_credential_type = "project_secret_key"
+ # A migrated legacy token (#63111) must keep the legacy path: account updates accept
+ # it there but refuse PSAKs.
+ defer_migrated_team_tokens = True
def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
result = super().authenticate(request)
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index f426f9e16467..639953e0b2c9 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -160,6 +160,20 @@ class TestExternalAccountAPI(APIBaseTest):
self.account.refresh_from_db()
self.assertIsNone(self.account.churned_at)
+ @parameterized.expand([("primary", "secret_api_token"), ("backup", "secret_api_token_backup")])
+ def test_patch_accepts_legacy_token_that_has_a_migrated_psak_row(self, _name: str, token_field: str) -> None:
+ # The #63111 backfill gives the legacy token a PSAK row with the same hash. The
+ # legacy string (primary or rotated-out backup) must keep the legacy path
+ # (updates allowed), not resolve as a PSAK.
+ token = generate_random_token_secret()
+ setattr(self.team, token_field, token)
+ self.team.save(update_fields=[token_field])
+ create_project_secret_api_key(self.team, label="Migrated legacy secret API key", value=token)
+ response = self._patch({"external_id": "acme-1", "churned_at": "2026-08-01"}, token=token)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.account.refresh_from_db()
+ self.assertIsNotNone(self.account.churned_at)
+
def test_post_accepts_project_secret_api_key_with_account_write_scope(self) -> None:
token = self._create_psak_token(scopes=["account:write"])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 99772ffe29d5..ff46a8215d9b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -59517,7 +59517,7 @@ export namespace Schemas {
export interface LeakedKeyReport {
/**
- * The leaked PostHog personal API key, project secret API key, or OAuth access/refresh token to revoke.
+ * The leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token to revoke.
* @maxLength 200
*/
token: string;
@@ -59526,6 +59526,7 @@ export namespace Schemas {
/**
* * `personal_api_key` - personal_api_key
* * `project_secret_api_key` - project_secret_api_key
+ * * `team_secret_token` - team_secret_token
* * `oauth_access_token` - oauth_access_token
* * `oauth_refresh_token` - oauth_refresh_token
*/
@@ -59535,17 +59536,19 @@ export namespace Schemas {
export const LeakedKeyReportResponseTypeEnum = {
PersonalApiKey: 'personal_api_key',
ProjectSecretApiKey: 'project_secret_api_key',
+ TeamSecretToken: 'team_secret_token',
OauthAccessToken: 'oauth_access_token',
OauthRefreshToken: 'oauth_refresh_token',
} as const;
export interface LeakedKeyReportResponse {
- /** Whether a matching PostHog key or token was found and revoked. */
+ /** Whether a matching PostHog key or token was found. It was revoked, or, for team_secret_token, its project admins were told to rotate it. */
found: boolean;
- /** The type of key that was found and revoked, or null if no match was found.
+ /** The type of key that was found and revoked, or null if no match was found. team_secret_token means the string is a legacy feature flags secure API key: its migrated project secret API key row was removed, but the legacy key itself cannot be auto-rotated, so project admins are emailed to rotate it.
*
* * `personal_api_key` - personal_api_key
* * `project_secret_api_key` - project_secret_api_key
+ * * `team_secret_token` - team_secret_token
* * `oauth_access_token` - oauth_access_token
* * `oauth_refresh_token` - oauth_refresh_token */
type: LeakedKeyReportResponseTypeEnum | null;