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(security): add public self-service leaked API key revocation (#81587)

Tom Piccirellodf60301591b8
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index b4f07b0a8963..0de6459eb400 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3845,6 +3845,42 @@ export interface BulkUpdateTagsResponseApi {
skipped: BulkUpdateTagsErrorApi[]
}
+export interface LeakedKeyReportApi {
+ /**
+ * The leaked PostHog personal API key, project secret API key, or OAuth access/refresh token to revoke.
+ * @maxLength 200
+ */
+ token: string
+}
+
+/**
+ * * `personal_api_key` - personal_api_key
+ * * `project_secret_api_key` - project_secret_api_key
+ * * `oauth_access_token` - oauth_access_token
+ * * `oauth_refresh_token` - oauth_refresh_token
+ */
+export type LeakedKeyReportResponseTypeEnumApi =
+ (typeof LeakedKeyReportResponseTypeEnumApi)[keyof typeof LeakedKeyReportResponseTypeEnumApi]
+
+export const LeakedKeyReportResponseTypeEnumApi = {
+ PersonalApiKey: 'personal_api_key',
+ ProjectSecretApiKey: 'project_secret_api_key',
+ OauthAccessToken: 'oauth_access_token',
+ OauthRefreshToken: 'oauth_refresh_token',
+} as const
+
+export interface LeakedKeyReportResponseApi {
+ /** Whether a matching PostHog key or token was found and revoked. */
+ found: boolean
+ /** The type of key that was found and revoked, or null if no match was found.
+ *
+ * * `personal_api_key` - personal_api_key
+ * * `project_secret_api_key` - project_secret_api_key
+ * * `oauth_access_token` - oauth_access_token
+ * * `oauth_refresh_token` - oauth_refresh_token */
+ type: LeakedKeyReportResponseTypeEnumApi | null
+}
+
/**
* * `disabled` - disabled
* * `toolbar` - toolbar
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 52d7242cf0dd..872d8467730f 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -31,6 +31,8 @@ import type {
IdentityProviderConfigApi,
IdentityProviderConfigsListParams,
InvitesListParams,
+ LeakedKeyReportApi,
+ LeakedKeyReportResponseApi,
OauthApplicationsListParams,
OnboardingSkipRequestApi,
OrganizationDomainApi,
@@ -2293,6 +2295,28 @@ export const sessionRecordingsSharingRefreshCreate = async (
})
}
+export const getRevokeLeakedKeyCreateUrl = () => {
+ return `/api/revoke_leaked_key/`
+}
+
+/**
+ * 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 is live it is revoked immediately and the owner is notified by email.
+ *
+ * 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
+ */
+export const revokeLeakedKeyCreate = async (
+ leakedKeyReportApi: LeakedKeyReportApi,
+ options?: RequestInit
+): Promise<LeakedKeyReportResponseApi> => {
+ return apiMutator<LeakedKeyReportResponseApi>(getRevokeLeakedKeyCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(leakedKeyReportApi),
+ })
+}
+
export const getUsersListUrl = (params?: UsersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index b189c78e7752..6bd32299ce22 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -916,6 +916,23 @@ export const SessionRecordingsSharingRefreshCreateBody = /* @__PURE__ */ zod
})
.describe('Mixin for serializers to add user access control fields')
+/**
+ * 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 is live it is revoked immediately and the owner is notified by email.
+ *
+ * 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
+ */
+export const revokeLeakedKeyCreateBodyTokenMax = 200
+
+export const RevokeLeakedKeyCreateBody = /* @__PURE__ */ zod.object({
+ token: zod
+ .string()
+ .max(revokeLeakedKeyCreateBodyTokenMax)
+ .describe(
+ 'The leaked PostHog personal API key, project secret API key, or OAuth access\/refresh token to revoke.'
+ ),
+})
+
/**
* Replace the authenticated user's profile and settings. Pass `@me` as the UUID to update the authenticated user. Prefer the PATCH endpoint for partial updates — PUT requires every writable field to be provided.
*/
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index ceefec652866..7f4147c34edc 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -743,11 +743,19 @@ def preprocess_exclude_path_format(endpoints, **kwargs):
for path, path_regex, method, callback in endpoints:
if getattr(callback.cls, "param_derived_from_user_current_team", None):
continue
- if not hasattr(callback.cls, "scope_object") or getattr(callback.cls, "hide_api_docs", False):
+ has_scope_object = hasattr(callback.cls, "scope_object")
+ # A view with no scope_object is normally excluded - the schema is built around
+ # team/org-scoped resources. include_in_api_docs is the explicit opt-in for a
+ # deliberately unscoped view (e.g. a public, unauthenticated endpoint) that still
+ # wants to appear in the docs.
+ if not has_scope_object and not getattr(callback.cls, "include_in_api_docs", False):
continue
- scope = callback.cls.scope_object
- if scope == "INTERNAL" and not include_internal:
+ if getattr(callback.cls, "hide_api_docs", False):
continue
+ if has_scope_object:
+ scope = callback.cls.scope_object
+ if scope == "INTERNAL" and not include_internal:
+ continue
included.append((path, path_regex, method, callback))
suffix = _extract_root_suffix(_PROJECTS_PREFIX_RE, path)
diff --git a/posthog/api/github.py b/posthog/api/github.py
index dc49f1c4c10d..27ed1c453497 100644
--- a/posthog/api/github.py
+++ b/posthog/api/github.py
@@ -18,19 +18,17 @@ from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
-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.secret_revocation import (
+ CANONICAL_OAUTH_ACCESS_TOKEN,
+ CANONICAL_OAUTH_REFRESH_TOKEN,
+ CANONICAL_PERSONAL_API_KEY,
+ CANONICAL_PROJECT_SECRET_API_KEY,
+ revoke_leaked_secret,
+)
from posthog.models import Team
-from posthog.models.oauth import find_oauth_access_token, find_oauth_refresh_token, revoke_oauth_session
-from posthog.models.personal_api_key import find_personal_api_key
-from posthog.models.project_secret_api_key import find_project_secret_api_key
from posthog.models.utils import mask_key_value
from posthog.redis import get_client
-from posthog.tasks.email import (
- send_feature_flags_secure_api_key_exposed,
- send_oauth_token_exposed,
- send_personal_api_key_exposed,
-)
+from posthog.tasks.email import send_feature_flags_secure_api_key_exposed
from posthog.utils import get_instance_region
logger = structlog.get_logger(__name__)
@@ -238,8 +236,9 @@ class SecretAlert(APIView):
local_found = False
if item["type"] == GITHUB_TYPE_FOR_PERSONAL_API_KEY:
- key_lookup = find_personal_api_key(token)
- local_found = key_lookup is not None
+ more_info = f"This key was detected by GitHub at {item['url']}."
+ revocation = revoke_leaked_secret(token, CANONICAL_PERSONAL_API_KEY, more_info)
+ local_found = revocation.found
pending_events.append(
{
@@ -252,36 +251,20 @@ class SecretAlert(APIView):
}
)
- if key_lookup is not None:
+ if revocation.found:
result["label"] = "true_positive"
- more_info = f"This key was detected by GitHub at {item['url']}."
-
- 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)
elif item["type"] == GITHUB_TYPE_FOR_SECURE_API_KEY:
- key_kind = None
+ 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
- project_secret_api_key = find_project_secret_api_key(token)
- if project_secret_api_key is not None:
- local_found = True
- key_kind = "project_secret_api_key"
- result["label"] = "true_positive"
-
- more_info = f"This key was detected by GitHub at {item['url']}."
- roll_project_secret_api_key_and_notify(project_secret_api_key, more_info)
- else:
+ 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"
- result["label"] = "true_positive"
-
- more_info = f"This key was detected by GitHub at {item['url']}."
send_feature_flags_secure_api_key_exposed(team.id, mask_key_value(token), more_info)
except Team.DoesNotExist:
@@ -299,9 +282,13 @@ class SecretAlert(APIView):
}
)
+ if local_found:
+ result["label"] = "true_positive"
+
elif item["type"] == GITHUB_TYPE_FOR_OAUTH_ACCESS_TOKEN:
- access_token = find_oauth_access_token(token)
- local_found = access_token is not None
+ more_info = f"This token was detected by GitHub at {item['url']}."
+ revocation = revoke_leaked_secret(token, CANONICAL_OAUTH_ACCESS_TOKEN, more_info)
+ local_found = revocation.found
pending_events.append(
{
@@ -314,19 +301,13 @@ class SecretAlert(APIView):
}
)
- if access_token is not None:
+ if revocation.found:
result["label"] = "true_positive"
- more_info = f"This token was detected by GitHub at {item['url']}."
-
- user = access_token.user
- revoke_oauth_session(access_token=access_token)
-
- if user:
- send_oauth_token_exposed(user.id, "access", mask_key_value(token), more_info)
elif item["type"] == GITHUB_TYPE_FOR_OAUTH_REFRESH_TOKEN:
- refresh_token = find_oauth_refresh_token(token)
- local_found = refresh_token is not None
+ more_info = f"This token was detected by GitHub at {item['url']}."
+ revocation = revoke_leaked_secret(token, CANONICAL_OAUTH_REFRESH_TOKEN, more_info)
+ local_found = revocation.found
pending_events.append(
{
@@ -339,15 +320,8 @@ class SecretAlert(APIView):
}
)
- if refresh_token is not None:
+ if revocation.found:
result["label"] = "true_positive"
- more_info = f"This token was detected by GitHub at {item['url']}."
-
- user = refresh_token.user
- revoke_oauth_session(refresh_token=refresh_token)
-
- if user:
- send_oauth_token_exposed(user.id, "refresh", mask_key_value(token), more_info)
else:
raise ValidationError(detail="Unexpected alert type")
diff --git a/posthog/api/leaked_key.py b/posthog/api/leaked_key.py
new file mode 100644
index 000000000000..657b1d383782
--- /dev/null
+++ b/posthog/api/leaked_key.py
@@ -0,0 +1,113 @@
+from hashlib import sha256
+
+import posthoganalytics
+from drf_spectacular.utils import OpenApiResponse
+from rest_framework import serializers
+from rest_framework.parsers import JSONParser
+from rest_framework.permissions import AllowAny
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.secret_revocation import (
+ CANONICAL_OAUTH_ACCESS_TOKEN,
+ CANONICAL_OAUTH_REFRESH_TOKEN,
+ CANONICAL_PERSONAL_API_KEY,
+ CANONICAL_PROJECT_SECRET_API_KEY,
+ revoke_leaked_secret,
+)
+from posthog.rate_limit import LeakedKeyReportThrottle
+from posthog.utils import get_instance_region
+
+PUBLIC_REPORT_MORE_INFO = "This key was reported as leaked via PostHog's public key-revocation API."
+
+
+class LeakedKeyReportSerializer(serializers.Serializer):
+ token = serializers.CharField(
+ # 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.",
+ )
+
+
+class LeakedKeyReportResponseSerializer(serializers.Serializer):
+ found = serializers.BooleanField(
+ help_text="Whether a matching PostHog key or token was found and revoked.",
+ )
+ type = serializers.ChoiceField(
+ choices=[
+ CANONICAL_PERSONAL_API_KEY,
+ CANONICAL_PROJECT_SECRET_API_KEY,
+ 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.",
+ )
+
+
+class PublicLeakedKeyReport(APIView):
+ """
+ Public, unauthenticated self-service endpoint: submit a leaked PostHog token and,
+ if it's live, it's revoked immediately and the owner is notified. 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.
+ """
+
+ authentication_classes = []
+ permission_classes = [AllowAny]
+ throttle_classes = [LeakedKeyReportThrottle]
+ parser_classes = [JSONParser]
+
+ # No scope_object: this endpoint is intentionally public and unscoped, not tied to
+ # a team/org resource, so APIScopePermission's scope model doesn't apply here. It
+ # opts into the public API docs directly instead.
+ include_in_api_docs = True
+
+ @validated_request(
+ request_serializer=LeakedKeyReportSerializer,
+ responses={
+ 200: OpenApiResponse(response=LeakedKeyReportResponseSerializer, description="Lookup result."),
+ 400: OpenApiResponse(description="The token is missing, blank, or longer than 200 characters."),
+ 429: OpenApiResponse(description="Too many requests from this IP."),
+ },
+ 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 is live it is revoked immediately and the owner is notified by email.\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 "
+ "https://eu.posthog.com/api/revoke_leaked_key."
+ ),
+ extensions={"x-product": "core"},
+ )
+ def post(self, request: ValidatedRequest) -> Response:
+ token = request.validated_data["token"]
+
+ result = revoke_leaked_secret(token, key_type=None, more_info=PUBLIC_REPORT_MORE_INFO)
+
+ # Unlike github_secret_alert, no token_prefix/token_suffix here: GitHub already
+ # confirmed the string is a real PostHog-shaped secret before that event fires,
+ # but this endpoint's callers are the whole internet, and people will paste
+ # things that aren't PostHog keys at all. token_sha256 alone is enough for
+ # dedup/monitoring without persisting fragments of third-party secrets.
+ posthoganalytics.capture(
+ distinct_id=None,
+ event="public_leaked_key_report",
+ properties={
+ "found": result.found,
+ "type": result.key_type,
+ "token_length": len(token),
+ "token_sha256": sha256(token.encode("utf-8")).hexdigest(),
+ # With no cross-region relay, this is the only signal showing whether
+ # callers in one region are reporting keys the other region issued.
+ "region": get_instance_region(),
+ },
+ )
+
+ return Response({"found": result.found, "type": result.key_type})
diff --git a/posthog/api/secret_revocation.py b/posthog/api/secret_revocation.py
new file mode 100644
index 000000000000..3f37f45a2c6d
--- /dev/null
+++ b/posthog/api/secret_revocation.py
@@ -0,0 +1,167 @@
+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.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
+from posthog.models.project_secret_api_key import find_project_secret_api_key
+from posthog.models.utils import (
+ OAUTH_ACCESS_TOKEN_PREFIX,
+ OAUTH_REFRESH_TOKEN_PREFIX,
+ PERSONAL_API_KEY_PREFIX,
+ SECRET_API_TOKEN_PREFIX,
+ mask_key_value,
+)
+from posthog.tasks.email import send_oauth_token_exposed, send_personal_api_key_exposed
+
+CANONICAL_PERSONAL_API_KEY = "personal_api_key"
+CANONICAL_PROJECT_SECRET_API_KEY = "project_secret_api_key"
+CANONICAL_OAUTH_ACCESS_TOKEN = "oauth_access_token"
+CANONICAL_OAUTH_REFRESH_TOKEN = "oauth_refresh_token"
+
+
+@frozen
+class RevocationResult:
+ key_type: str | None
+
+ @property
+ def found(self) -> bool:
+ return self.key_type is not None
+
+
+def _revoke_personal_api_key(token: str, more_info: str) -> bool:
+ key_lookup = find_personal_api_key(token)
+ if key_lookup is None:
+ return False
+ 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
+
+
+def _revoke_project_secret_api_key(token: str, more_info: str) -> bool:
+ 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
+
+
+def _revoke_oauth_token(token: str, more_info: str, *, kind: Literal["access", "refresh"]) -> bool:
+ if kind == "access":
+ access_token = find_oauth_access_token(token)
+ # An expired access token no longer authenticates, so possessing one doesn't
+ # give its holder the "already has full use of this credential" standing this
+ # endpoint's lack of a signature check relies on. Without this, anyone who once
+ # saw a since-expired token could still force-revoke the holder's live session.
+ if access_token is None or access_token.is_expired():
+ return False
+ # 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.
+ revoke_oauth_token_session(access_token=access_token)
+ user = access_token.user
+ else:
+ refresh_token = find_oauth_refresh_token(token)
+ if refresh_token is None:
+ return False
+ 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
+
+
+def _revoke_oauth_access_token(token: str, more_info: str) -> bool:
+ return _revoke_oauth_token(token, more_info, kind="access")
+
+
+def _revoke_oauth_refresh_token(token: str, more_info: str) -> bool:
+ return _revoke_oauth_token(token, more_info, kind="refresh")
+
+
+_REVOKERS = {
+ CANONICAL_PERSONAL_API_KEY: _revoke_personal_api_key,
+ CANONICAL_PROJECT_SECRET_API_KEY: _revoke_project_secret_api_key,
+ CANONICAL_OAUTH_ACCESS_TOKEN: _revoke_oauth_access_token,
+ CANONICAL_OAUTH_REFRESH_TOKEN: _revoke_oauth_refresh_token,
+}
+
+# Every key type issued today has a reserved prefix (posthog/models/utils.py) enforced
+# at generation time. Auto-detect uses it to run exactly one lookup instead of trying
+# every type in turn — a token matching no known prefix costs nothing beyond these
+# string comparisons, instead of paying for a personal-API-key lookup's SHA-256 +
+# two rounds of PBKDF2 (PERSONAL_API_KEY_MODES_TO_TRY) on every unrecognized string
+# an anonymous caller submits.
+#
+# Personal API keys are the one exception: those issued before the prefix existed have
+# none, so the map alone would leave the fleet's oldest keys unrevocable.
+# _looks_like_legacy_personal_api_key covers them by shape instead. That widens what
+# reaches the personal-key lookup — any 43-character URL-safe string qualifies,
+# including legacy unprefixed Team.api_token values, which simply miss. That shape
+# check only narrows *which* strings pay the expensive lookup, not how many times a
+# caller can pay it: on the public endpoint, a caller can construct a matching string
+# on purpose, so per-request cost is still bounded only by LeakedKeyReportThrottle's
+# per-IP rate limit, not by this check.
+#
+# Team-level secret tokens (Team.secret_api_token) share SECRET_API_TOKEN_PREFIX
+# with project secret API keys but are deliberately not in this map: unlike these
+# 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.
+_PREFIX_TO_CANONICAL_TYPE = {
+ PERSONAL_API_KEY_PREFIX: CANONICAL_PERSONAL_API_KEY,
+ SECRET_API_TOKEN_PREFIX: CANONICAL_PROJECT_SECRET_API_KEY,
+ OAUTH_ACCESS_TOKEN_PREFIX: CANONICAL_OAUTH_ACCESS_TOKEN,
+ OAUTH_REFRESH_TOKEN_PREFIX: CANONICAL_OAUTH_REFRESH_TOKEN,
+}
+
+# The non-personal-key prefixes above, re-exported so other prefix-based key-type checks
+# (e.g. the admin key-search view in posthog/views.py) can stay in sync with this map
+# instead of re-listing the same three prefixes by hand.
+NON_PERSONAL_SECRET_PREFIXES = (
+ SECRET_API_TOKEN_PREFIX,
+ OAUTH_ACCESS_TOKEN_PREFIX,
+ OAUTH_REFRESH_TOKEN_PREFIX,
+)
+
+
+_LEGACY_PERSONAL_API_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{43}$")
+
+
+def _looks_like_legacy_personal_api_key(token: str) -> bool:
+ """Personal API keys created before the phx_ prefix (2021-06-23, commit
+ 6c9bb2db0fb) are bare secrets.token_urlsafe(32) output: exactly 43 URL-safe
+ base64 characters, no prefix. They're still valid today — PERSONAL_API_KEY_MODES_TO_TRY
+ exists specifically to authenticate them via their legacy hash. This exact
+ length+charset check keeps auto-detect's cost bound intact: only a token
+ matching this precise shape reaches the expensive personal-key lookup,
+ not every unrecognized string.
+ """
+ return bool(_LEGACY_PERSONAL_API_KEY_PATTERN.match(token))
+
+
+def _detect_canonical_type(token: str) -> str | None:
+ for prefix, canonical_type in _PREFIX_TO_CANONICAL_TYPE.items():
+ if token.startswith(prefix):
+ return canonical_type
+ if _looks_like_legacy_personal_api_key(token):
+ return CANONICAL_PERSONAL_API_KEY
+ return 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.
+ """
+ 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)
diff --git a/posthog/api/test/test_github.py b/posthog/api/test/test_github.py
index bff0d9dc4466..ac84334e50f1 100644
--- a/posthog/api/test/test_github.py
+++ b/posthog/api/test/test_github.py
@@ -312,7 +312,7 @@ dYtHUlWNMx0y6YwVG8nlBiJk2e0n+zpzs2WwszrnC7wfCqgU6rU3TkDvBQ==
self.assertIn("Github-Public-Key-Identifier", str(data))
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_personal_api_key_exposed")
+ @patch("posthog.api.secret_revocation.send_personal_api_key_exposed")
def test_secret_alert_finds_and_rolls_existing_personal_api_key(self, mock_send_email, mock_verify):
"""Test that an existing personal API key is found, rolled, and email is sent."""
mock_verify.return_value = None
@@ -390,7 +390,7 @@ dYtHUlWNMx0y6YwVG8nlBiJk2e0n+zpzs2WwszrnC7wfCqgU6rU3TkDvBQ==
self.assertEqual(data[0]["label"], "false_positive")
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_personal_api_key_exposed")
+ @patch("posthog.api.secret_revocation.send_personal_api_key_exposed")
def test_secret_alert_finds_key_with_legacy_pbkdf2_hash(self, mock_send_email, mock_verify):
"""Test that keys stored with legacy PBKDF2 hash are still found."""
mock_verify.return_value = None
@@ -987,7 +987,7 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
)
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_oauth_token_exposed")
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
def test_oauth_access_token_found_and_revoked(self, mock_send_email, mock_verify):
mock_verify.return_value = None
@@ -1032,7 +1032,7 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
self.assertEqual(call_args[0][1], "access")
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_oauth_token_exposed")
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
def test_oauth_refresh_token_found_and_revoked(self, mock_send_email, mock_verify):
mock_verify.return_value = None
@@ -1125,8 +1125,8 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
self.assertEqual(data[0]["label"], "false_positive")
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_oauth_token_exposed")
- def test_oauth_access_token_revocation_also_revokes_related_artifacts(self, mock_send_email, mock_verify):
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
+ def test_oauth_access_token_revocation_revokes_paired_refresh_token_not_grant(self, mock_send_email, mock_verify):
mock_verify.return_value = None
oauth_app = self._create_oauth_app()
@@ -1184,11 +1184,14 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
refresh_token.refresh_from_db()
self.assertIsNotNone(refresh_token.revoked)
- self.assertFalse(OAuthGrant.objects.filter(id=grant_id).exists())
+ # A leaked-token report is evidence about this one token, not the user's other
+ # sessions or in-flight authorizations - revoke_oauth_token_session only revokes
+ # the paired access/refresh token, not other grants for the same user+app.
+ self.assertTrue(OAuthGrant.objects.filter(id=grant_id).exists())
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_oauth_token_exposed")
- def test_oauth_refresh_token_revocation_also_revokes_related_artifacts(self, mock_send_email, mock_verify):
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
+ def test_oauth_refresh_token_revocation_revokes_paired_access_token_not_grant(self, mock_send_email, mock_verify):
mock_verify.return_value = None
oauth_app = self._create_oauth_app()
@@ -1246,7 +1249,9 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
self.assertFalse(OAuthAccessToken.objects.filter(id=access_token_id).exists())
- self.assertFalse(OAuthGrant.objects.filter(id=grant_id).exists())
+ # See the access-token variant above: the narrow revocation doesn't sweep other
+ # grants for the same user+app.
+ self.assertTrue(OAuthGrant.objects.filter(id=grant_id).exists())
@patch("posthog.api.github.verify_github_signature")
def test_revoked_oauth_refresh_token_returns_false_positive(self, mock_verify):
@@ -1283,7 +1288,7 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
self.assertEqual(data[0]["label"], "false_positive")
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_oauth_token_exposed")
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
def test_initial_access_token_revokes_paired_refresh_token(self, mock_send_email, mock_verify):
"""Initial access token (no source_refresh_token) should still revoke paired refresh token."""
mock_verify.return_value = None
@@ -1350,11 +1355,12 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
refresh_token.refresh_from_db()
self.assertIsNotNone(refresh_token.revoked)
- # Grant should be deleted
- self.assertFalse(OAuthGrant.objects.filter(id=grant_id).exists())
+ # Grant is untouched - it's not part of this token's session (see
+ # revoke_oauth_token_session's docstring)
+ self.assertTrue(OAuthGrant.objects.filter(id=grant_id).exists())
@patch("posthog.api.github.verify_github_signature")
- @patch("posthog.api.github.send_oauth_token_exposed")
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
def test_initial_refresh_token_revokes_paired_access_token(self, mock_send_email, mock_verify):
"""Initial refresh token should still revoke paired access token."""
mock_verify.return_value = None
@@ -1421,5 +1427,5 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
refresh_token.refresh_from_db()
self.assertIsNotNone(refresh_token.revoked)
- # Grant should be deleted
- self.assertFalse(OAuthGrant.objects.filter(id=grant_id).exists())
+ # Grant is untouched - see the access-token variant above.
+ self.assertTrue(OAuthGrant.objects.filter(id=grant_id).exists())
diff --git a/posthog/api/test/test_leaked_key.py b/posthog/api/test/test_leaked_key.py
new file mode 100644
index 000000000000..5167a74ddc6f
--- /dev/null
+++ b/posthog/api/test/test_leaked_key.py
@@ -0,0 +1,331 @@
+import json
+import secrets
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.leaked_key import PUBLIC_REPORT_MORE_INFO
+from posthog.api.secret_revocation import (
+ CANONICAL_OAUTH_ACCESS_TOKEN,
+ CANONICAL_OAUTH_REFRESH_TOKEN,
+ CANONICAL_PERSONAL_API_KEY,
+ CANONICAL_PROJECT_SECRET_API_KEY,
+)
+from posthog.models import PersonalAPIKey
+from posthog.models.oauth import (
+ OAuthAccessToken,
+ OAuthApplication,
+ OAuthRefreshToken,
+ find_oauth_access_token,
+ 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.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
+
+
+class TestPublicLeakedKeyReport(APIBaseTest):
+ # Every case must exercise the anonymous path this endpoint exists to serve. With the
+ # default force-login, dropping `authentication_classes`/`permission_classes` from the
+ # view would fall back to DRF's authenticated-only defaults and no test would notice.
+ CONFIG_AUTO_LOGIN = False
+
+ def _create_oauth_app(self) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ name="Test OAuth App",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ skip_authorization=False,
+ organization=self.organization,
+ user=self.user,
+ )
+
+ def _post(self, token: str) -> Any:
+ return self.client.post(
+ "/api/revoke_leaked_key",
+ data=json.dumps({"token": token}),
+ content_type="application/json",
+ )
+
+ @parameterized.expand(
+ [
+ ("personal_api_key", CANONICAL_PERSONAL_API_KEY),
+ ("legacy_personal_api_key", CANONICAL_PERSONAL_API_KEY),
+ ("project_secret_api_key", CANONICAL_PROJECT_SECRET_API_KEY),
+ ("oauth_access_token", CANONICAL_OAUTH_ACCESS_TOKEN),
+ ("oauth_refresh_token", CANONICAL_OAUTH_REFRESH_TOKEN),
+ ]
+ )
+ @patch("posthog.api.project_secret_api_key.send_project_secret_api_key_exposed")
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
+ @patch("posthog.api.secret_revocation.send_personal_api_key_exposed")
+ def test_auto_detects_and_revokes_each_key_type(
+ self,
+ kind: str,
+ expected_type: str,
+ mock_send_personal_api_key_exposed: MagicMock,
+ mock_send_oauth_token_exposed: MagicMock,
+ mock_send_project_secret_api_key_exposed: MagicMock,
+ ) -> None:
+ if kind == "personal_api_key":
+ token = generate_random_token_personal()
+ key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="leaked",
+ secure_value=hash_key_value(token),
+ mask_value=mask_key_value(token),
+ scopes=["*"],
+ )
+
+ def still_present() -> bool:
+ return find_personal_api_key(token) is not None
+
+ def assert_owner_notified() -> None:
+ mock_send_personal_api_key_exposed.assert_called_once_with(
+ self.user.id, key.id, mask_key_value(token), PUBLIC_REPORT_MORE_INFO
+ )
+ elif kind == "legacy_personal_api_key":
+ # Keys issued before the phx_ prefix are bare secrets.token_urlsafe(32) output
+ # stored under the legacy PBKDF2 hash. They still authenticate, so they must
+ # still be revocable here.
+ token = secrets.token_urlsafe(32)
+ key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="leaked legacy",
+ secure_value=hash_key_value(
+ token, mode="pbkdf2", legacy_salt=LEGACY_PERSONAL_API_KEY_SALT, iterations=260000
+ ),
+ mask_value=mask_key_value(token),
+ scopes=["*"],
+ )
+
+ def still_present() -> bool:
+ return find_personal_api_key(token) is not None
+
+ def assert_owner_notified() -> None:
+ mock_send_personal_api_key_exposed.assert_called_once_with(
+ self.user.id, key.id, mask_key_value(token), PUBLIC_REPORT_MORE_INFO
+ )
+ elif kind == "project_secret_api_key":
+ project_secret_api_key, token = create_project_secret_api_key(team=self.team, created_by=self.user)
+
+ def still_present() -> bool:
+ return find_project_secret_api_key(token) is not None
+
+ def assert_owner_notified() -> None:
+ mock_send_project_secret_api_key_exposed.assert_called_once_with(
+ self.team.id, project_secret_api_key.id, mask_key_value(token), PUBLIC_REPORT_MORE_INFO
+ )
+ elif kind == "oauth_access_token":
+ oauth_app = self._create_oauth_app()
+ token = "pha_test_leaked_access_token"
+ OAuthAccessToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token=token,
+ expires=timezone.now() + timedelta(hours=1),
+ scope="openid profile",
+ )
+
+ def still_present() -> bool:
+ return find_oauth_access_token(token) is not None
+
+ def assert_owner_notified() -> None:
+ mock_send_oauth_token_exposed.assert_called_once_with(
+ self.user.id, "access", mask_key_value(token), PUBLIC_REPORT_MORE_INFO
+ )
+ else:
+ oauth_app = self._create_oauth_app()
+ token = "phr_test_leaked_refresh_token"
+ OAuthRefreshToken.objects.create(user=self.user, application=oauth_app, token=token)
+
+ def still_present() -> bool:
+ return find_oauth_refresh_token(token) is not None
+
+ def assert_owner_notified() -> None:
+ mock_send_oauth_token_exposed.assert_called_once_with(
+ self.user.id, "refresh", mask_key_value(token), PUBLIC_REPORT_MORE_INFO
+ )
+
+ response = self._post(token)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": True, "type": expected_type})
+ self.assertFalse(still_present())
+ assert_owner_notified()
+
+ @parameterized.expand(
+ [
+ # Recognized prefix, but no such key exists — exercises the one lookup
+ # that runs and misses.
+ ("known_prefix_but_key_does_not_exist", "phx_this_is_not_a_real_key"),
+ # No PostHog key prefix at all — exercises _detect_canonical_type
+ # returning None and skipping every lookup entirely.
+ ("no_recognized_prefix_at_all", "not-a-posthog-key-at-all"),
+ # Matches the legacy unprefixed personal-key shape (43 URL-safe chars), so the
+ # personal-key lookup runs and misses. Guards the shape fallback against
+ # false positives.
+ ("legacy_shape_but_not_a_real_key", "x" * 43),
+ ]
+ )
+ def test_unrecognized_token_is_not_found(self, _name: str, token: str) -> None:
+ response = self._post(token)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": False, "type": None})
+
+ def test_team_secret_token_is_not_auto_detected(self) -> None:
+ # Team.secret_api_token shares the "phs_" prefix with project secret API
+ # keys, but it's a different model (Team, not ProjectSecretAPIKey), so the
+ # single lookup the "phs_" prefix triggers (find_project_secret_api_key)
+ # naturally misses — it's intentionally excluded from auto-detect (see
+ # _PREFIX_TO_CANONICAL_TYPE in secret_revocation.py) since it can't be
+ # auto-rotated without a user to attribute the rotation to.
+ token = "phs_legacy_team_secret_token_for_public_endpoint_test"
+ self.team.secret_api_token = token
+ self.team.save()
+
+ response = self._post(token)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": False, "type": None})
+
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.secret_api_token, token)
+
+ def test_expired_oauth_access_token_does_not_revoke_the_live_session(self) -> None:
+ # An expired access token authenticates nothing, so possessing one grants no
+ # capability beyond what the endpoint's "possession = already usable" argument
+ # relies on. It must not be able to force-revoke a session its holder can no
+ # longer use.
+ oauth_app = self._create_oauth_app()
+ expired_token = "pha_expired_leaked_access_token"
+ OAuthAccessToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token=expired_token,
+ expires=timezone.now() - timedelta(hours=1),
+ scope="openid profile",
+ )
+ live_refresh_token = OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token="phr_live_session_refresh_token",
+ )
+
+ response = self._post(expired_token)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": False, "type": None})
+ live_refresh_token.refresh_from_db()
+ self.assertIsNone(live_refresh_token.revoked)
+
+ def test_oauth_access_token_revocation_does_not_touch_other_sessions_with_same_app(self) -> None:
+ # A leaked token is evidence about that one token, not the user's other sessions
+ # with the same app (e.g. the same app authorized from a second device) - a
+ # report about one session must not revoke another.
+ oauth_app = self._create_oauth_app()
+
+ leaked_refresh_token = OAuthRefreshToken.objects.create(
+ user=self.user, application=oauth_app, token="phr_leaked_session_refresh"
+ )
+ leaked_access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token="pha_leaked_session_access",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="openid profile",
+ source_refresh_token=leaked_refresh_token,
+ )
+
+ other_refresh_token = OAuthRefreshToken.objects.create(
+ user=self.user, application=oauth_app, token="phr_other_session_refresh"
+ )
+ other_access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token="pha_other_session_access",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="openid profile",
+ source_refresh_token=other_refresh_token,
+ )
+
+ response = self._post("pha_leaked_session_access")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": True, "type": CANONICAL_OAUTH_ACCESS_TOKEN})
+ self.assertFalse(OAuthAccessToken.objects.filter(id=leaked_access_token.id).exists())
+ leaked_refresh_token.refresh_from_db()
+ self.assertIsNotNone(leaked_refresh_token.revoked)
+
+ self.assertTrue(OAuthAccessToken.objects.filter(id=other_access_token.id).exists())
+ other_refresh_token.refresh_from_db()
+ self.assertIsNone(other_refresh_token.revoked)
+
+ def test_leaked_non_rotating_refresh_token_revokes_every_derived_access_token(self) -> None:
+ # DCR/CIMD clients get non-rotating refreshes: every refresh inserts a new access
+ # token row with no link back to the refresh token that minted it, instead of
+ # updating one row in place. Reporting the refresh token must still catch every
+ # access token it could have produced, not just whichever one (if any) happens to
+ # still be linked.
+ dcr_app = OAuthApplication.objects.create(
+ name="Test DCR App",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ skip_authorization=False,
+ organization=self.organization,
+ user=self.user,
+ is_dcr_client=True,
+ )
+ leaked_refresh_token = OAuthRefreshToken.objects.create(
+ user=self.user, application=dcr_app, token="phr_dcr_refresh_token"
+ )
+ first_access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=dcr_app,
+ token="pha_dcr_access_token_1",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="openid profile",
+ )
+ second_access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=dcr_app,
+ token="pha_dcr_access_token_2",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="openid profile",
+ )
+
+ response = self._post("phr_dcr_refresh_token")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"found": True, "type": CANONICAL_OAUTH_REFRESH_TOKEN})
+ leaked_refresh_token.refresh_from_db()
+ self.assertIsNotNone(leaked_refresh_token.revoked)
+ self.assertFalse(OAuthAccessToken.objects.filter(id=first_access_token.id).exists())
+ self.assertFalse(OAuthAccessToken.objects.filter(id=second_access_token.id).exists())
+
+ def test_blank_token_returns_400(self) -> None:
+ response = self._post("")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_repeated_reports_from_one_ip_are_throttled(self) -> None:
+ with patch.object(LeakedKeyReportThrottle, "rate", "1/minute"):
+ first = self._post("phx_not_a_real_key")
+ second = self._post("phx_not_a_real_key")
+
+ self.assertEqual(first.status_code, status.HTTP_200_OK)
+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 079c960d9833..a8db7d05b360 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -655,7 +655,15 @@ def find_oauth_refresh_token(token: str) -> OAuthRefreshToken | None:
def revoke_oauth_session(
access_token: OAuthAccessToken | None = None, refresh_token: OAuthRefreshToken | None = None
) -> None:
- """Revoke all OAuth artifacts related to a session (access token, refresh token, and grant)."""
+ """Revoke all OAuth artifacts for the token's (user, application) pair - every access
+ token, every refresh token, and every grant, not just the given one.
+
+ Use this where the user or client explicitly asked to disconnect the whole app
+ (connected_apps.py, RFC 7009 revoke_token) - there, sweeping every session for that
+ (user, application) is the correct, intentional scope. For a report that ONE specific
+ credential leaked, use revoke_oauth_token_session instead: a leaked token is evidence
+ about that one token, not about the user's other sessions with the app.
+ """
from django.utils import timezone
now = timezone.now()
@@ -689,6 +697,66 @@ def revoke_oauth_session(
OAuthGrant.objects.filter(user=user, application=application).delete()
+def _refresh_token_may_have_untracked_access_tokens(refresh_token: OAuthRefreshToken) -> bool:
+ """True for a non-rotating refresh token (DCR/CIMD clients - see
+ OAuthTokenView._save_bearer_token in posthog/api/oauth/views.py), which inserts a new,
+ unlinked OAuthAccessToken row on every refresh instead of updating one access token in
+ place. Those rows carry no queryable link back to the refresh token that minted them
+ (source_refresh_token is left None specifically so sibling rows stay addressable), so
+ there's no way to enumerate every access token a given non-rotating refresh token could
+ have produced.
+ """
+ application = refresh_token.application
+ if application.is_dcr_client or application.is_cimd_client:
+ return True
+ return not oauth2_settings.ROTATE_REFRESH_TOKEN
+
+
+def revoke_oauth_token_session(
+ access_token: OAuthAccessToken | None = None, refresh_token: OAuthRefreshToken | None = None
+) -> None:
+ """Revoke only the one access/refresh token pair the given token belongs to, not
+ every session the user has with the application.
+
+ Use this for a report that identifies ONE specific leaked credential (github.py, the
+ public leaked-key endpoint) - see revoke_oauth_session for where the broader sweep is
+ the correct, intentional scope instead.
+
+ Doesn't touch OAuthGrant: a grant is a single-use authorization code consumed at
+ token exchange, not part of an ongoing session, so there's no "this token's grant" to
+ revoke alongside it.
+ """
+ from django.utils import timezone
+
+ now = timezone.now()
+
+ if access_token:
+ # Neither direction of the access_token <-> refresh_token OneToOne is reliably
+ # populated on its own (our non-rotating _save_bearer_token branch leaves
+ # source_refresh_token None - see revoke_token's docstring in
+ # posthog/api/oauth/views.py - and callers that create a refresh token before
+ # its access token don't always back-fill refresh_token.access_token either), so
+ # check both directions instead of trusting one.
+ OAuthRefreshToken.objects.filter(
+ Q(access_token=access_token) | Q(pk=access_token.source_refresh_token_id), revoked__isnull=True
+ ).update(revoked=now)
+ access_token.delete()
+ elif refresh_token:
+ if _refresh_token_may_have_untracked_access_tokens(refresh_token):
+ # A leaked non-rotating refresh token can have minted any number of access
+ # tokens with no durable link back to it (see
+ # _refresh_token_may_have_untracked_access_tokens), so a per-token revoke can't
+ # guarantee all of them are caught. Fall back to the same (user, application)
+ # sweep revoke_token already uses for this exact case via RFC 7009.
+ revoke_oauth_session(refresh_token=refresh_token)
+ return
+ OAuthAccessToken.objects.filter(
+ Q(pk=refresh_token.access_token_id) | Q(source_refresh_token=refresh_token)
+ ).delete()
+ refresh_token.revoked = now
+ refresh_token.save(update_fields=["revoked"])
+
+
def revoke_application_sessions(application: "OAuthApplication") -> None:
"""Force-invalidate every outstanding token and grant for an application, across all users.
diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.py
index ad19d08d80e8..6b035e6b40c1 100644
--- a/posthog/models/test/test_oauth.py
+++ b/posthog/models/test/test_oauth.py
@@ -19,6 +19,7 @@ from posthog.models.oauth import (
normalize_cimd_url,
revoke_application_sessions,
revoke_oauth_session,
+ revoke_oauth_token_session,
)
from posthog.models.oauth_provisioning import ProvisioningConfig
@@ -508,6 +509,91 @@ class TestOAuthModels(TestCase):
self.assertFalse(OAuthAccessToken.objects.filter(id=token_id).exists())
+ def test_revoke_oauth_token_session_revokes_only_the_paired_tokens(self):
+ app = OAuthApplication.objects.create(
+ name="Narrow Revoke Test App",
+ client_id="narrow_revoke_test_client_id",
+ client_secret="narrow_revoke_test_client_secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ organization=self.organization,
+ algorithm="RS256",
+ )
+ refresh_token = OAuthRefreshToken.objects.create(application=app, user=self.user, token="narrow_refresh_1")
+ access_token = OAuthAccessToken.objects.create(
+ application=app,
+ user=self.user,
+ token="narrow_access_1",
+ expires=timezone.now() + timedelta(minutes=5),
+ source_refresh_token=refresh_token,
+ )
+ # A second, unrelated session for the same user+application - must survive.
+ other_access_token = OAuthAccessToken.objects.create(
+ application=app,
+ user=self.user,
+ token="narrow_access_2",
+ expires=timezone.now() + timedelta(minutes=5),
+ )
+ grant = OAuthGrant.objects.create(
+ application=app,
+ user=self.user,
+ code="narrow_grant_code",
+ code_challenge="challenge",
+ code_challenge_method="S256",
+ expires=timezone.now() + timedelta(minutes=5),
+ )
+
+ revoke_oauth_token_session(access_token=access_token)
+
+ self.assertFalse(OAuthAccessToken.objects.filter(id=access_token.id).exists())
+ refresh_token.refresh_from_db()
+ self.assertIsNotNone(refresh_token.revoked)
+
+ self.assertTrue(OAuthAccessToken.objects.filter(id=other_access_token.id).exists())
+ self.assertTrue(OAuthGrant.objects.filter(id=grant.id).exists())
+
+ def test_revoke_oauth_token_session_sweeps_all_access_tokens_for_non_rotating_refresh(self):
+ # DCR/CIMD clients get non-rotating refreshes: _save_bearer_token inserts a new,
+ # unlinked OAuthAccessToken row per refresh instead of updating one in place, so
+ # source_refresh_token stays None on every one of them and there's no queryable
+ # link back to the refresh token that minted them. A per-token revoke can't find
+ # tokens it has no link to, so this must fall back to the full sweep instead.
+ app = OAuthApplication.objects.create(
+ name="DCR Non-Rotating Test App",
+ client_id="dcr_non_rotating_client_id",
+ client_secret="dcr_non_rotating_client_secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ organization=self.organization,
+ algorithm="RS256",
+ is_dcr_client=True,
+ )
+ refresh_token = OAuthRefreshToken.objects.create(application=app, user=self.user, token="dcr_refresh_1")
+ first_access_token = OAuthAccessToken.objects.create(
+ application=app, user=self.user, token="dcr_access_1", expires=timezone.now() + timedelta(minutes=5)
+ )
+ second_access_token = OAuthAccessToken.objects.create(
+ application=app, user=self.user, token="dcr_access_2", expires=timezone.now() + timedelta(minutes=5)
+ )
+ grant = OAuthGrant.objects.create(
+ application=app,
+ user=self.user,
+ code="dcr_grant_code",
+ code_challenge="challenge",
+ code_challenge_method="S256",
+ expires=timezone.now() + timedelta(minutes=5),
+ )
+
+ revoke_oauth_token_session(refresh_token=refresh_token)
+
+ self.assertFalse(OAuthAccessToken.objects.filter(id=first_access_token.id).exists())
+ self.assertFalse(OAuthAccessToken.objects.filter(id=second_access_token.id).exists())
+ self.assertFalse(OAuthGrant.objects.filter(id=grant.id).exists())
+ refresh_token.refresh_from_db()
+ self.assertIsNotNone(refresh_token.revoked)
+
@freeze_time("2026-01-01 00:00:00")
def test_revoke_application_sessions_revokes_across_all_users_and_leaves_other_apps(self):
app = self._make_app("Narrowed App", "narrowed_client_id")
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index b251bf887c64..9cb87a7ad0b1 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -346,6 +346,19 @@ class WebAuthnSignupRegistrationThrottle(IPThrottle):
rate = "10/minute"
+class LeakedKeyReportThrottle(IPThrottle):
+ """
+ Rate limit the public leaked-key revocation endpoint by IP address.
+
+ This isn't an authorization gate — guessing a valid high-entropy PostHog token
+ is computationally infeasible regardless of rate. It just bounds nuisance load
+ (hashing + DB lookups against garbage strings) from a single IP.
+ """
+
+ scope = "leaked_key_report"
+ rate = "10/minute"
+
+
class SignupEmailPrecheckThrottle(IPThrottle):
"""
Rate limit signup email precheck requests by IP.
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index 9b32e0d04acf..0cda551ca96c 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -893,6 +893,29 @@ class TestAIObservabilitySummarizationRateThrottle(SimpleTestCase):
self.assertFalse(throttle_class().allow_request(request, view))
+class TestLeakedKeyReportThrottle(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ def tearDown(self) -> None:
+ cache.clear()
+
+ def test_scope_and_rate(self) -> None:
+ throttle = rate_limit.LeakedKeyReportThrottle()
+ self.assertEqual(throttle.scope, "leaked_key_report")
+ self.assertEqual(throttle.rate, "10/minute")
+
+ def test_limits_requests_per_ip(self) -> None:
+ request = Mock(headers={}, META={"REMOTE_ADDR": "203.0.113.5"})
+ other_request = Mock(headers={}, META={"REMOTE_ADDR": "203.0.113.6"})
+ view = Mock()
+
+ with patch.object(rate_limit.LeakedKeyReportThrottle, "rate", "1/minute"):
+ self.assertTrue(rate_limit.LeakedKeyReportThrottle().allow_request(request, view))
+ self.assertFalse(rate_limit.LeakedKeyReportThrottle().allow_request(request, view))
+ self.assertTrue(rate_limit.LeakedKeyReportThrottle().allow_request(other_request, view))
+
+
class _PSAKTeamThrottleForTest(rate_limit.ProjectSecretApiKeyTeamRateThrottle):
scope = "test_psak_team"
rate = "100/minute"
diff --git a/posthog/urls.py b/posthog/urls.py
index 2c0b6f27ef88..4681da348794 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -20,6 +20,7 @@ from posthog.api import (
api_not_found,
authentication,
github,
+ leaked_key,
playwright_setup,
report,
router,
@@ -476,6 +477,7 @@ urlpatterns = [
# api
path("api/unsubscribe", unsubscribe.unsubscribe),
path("api/alerts/github", github.SecretAlert.as_view()),
+ opt_slash_path("api/revoke_leaked_key", leaked_key.PublicLeakedKeyReport.as_view()),
path(
"api/legal_documents/pandadoc",
csrf_exempt(legal_document_pandadoc_webhook),
diff --git a/posthog/views.py b/posthog/views.py
index 89e6d266bbb7..d4cd3f4567cf 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -26,6 +26,7 @@ import structlog
from opentelemetry import trace
from posthog.api.capture import capture_internal
+from posthog.api.secret_revocation import NON_PERSONAL_SECRET_PREFIXES
from posthog.auth import AUTH_BRAND_COOKIE, apply_auth_brand_cookie, normalize_auth_brand
from posthog.cloud_utils import is_cloud
from posthog.email import is_email_available
@@ -467,12 +468,7 @@ def api_key_search_view(request: HttpRequest):
personal_api_key_hash_mode = None
# Legacy personal API keys predate the phx_ prefix, so any query without another known
# prefix is also treated as a personal key candidate (matching authentication behavior).
- non_personal_api_key_prefixes = (
- SECRET_API_TOKEN_PREFIX,
- OAUTH_ACCESS_TOKEN_PREFIX,
- OAUTH_REFRESH_TOKEN_PREFIX,
- PROJECT_API_TOKEN_PREFIX,
- )
+ non_personal_api_key_prefixes = (*NON_PERSONAL_SECRET_PREFIXES, PROJECT_API_TOKEN_PREFIX)
if query and not query.startswith(non_personal_api_key_prefixes):
result = find_personal_api_key(query)
if result is not None:
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index abc945d0f0d1..3a580f2435e4 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -387,6 +387,9 @@ tools:
reset-token-partial-update:
operation: organizations_projects_reset_token_partial_update
enabled: false
+ revoke-leaked-key-create:
+ operation: revoke_leaked_key_create
+ enabled: false
rotate-secret-token-partial-update:
operation: organizations_projects_rotate_secret_token_partial_update
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 38577b06621e..f56685bf13da 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42071,6 +42071,42 @@ export namespace Schemas {
FullWidth: 'full_width',
} as const;
+ export interface LeakedKeyReport {
+ /**
+ * The leaked PostHog personal API key, project secret API key, or OAuth access/refresh token to revoke.
+ * @maxLength 200
+ */
+ token: string;
+ }
+
+ /**
+ * * `personal_api_key` - personal_api_key
+ * * `project_secret_api_key` - project_secret_api_key
+ * * `oauth_access_token` - oauth_access_token
+ * * `oauth_refresh_token` - oauth_refresh_token
+ */
+ export type LeakedKeyReportResponseTypeEnum = typeof LeakedKeyReportResponseTypeEnum[keyof typeof LeakedKeyReportResponseTypeEnum];
+
+
+ export const LeakedKeyReportResponseTypeEnum = {
+ PersonalApiKey: 'personal_api_key',
+ ProjectSecretApiKey: 'project_secret_api_key',
+ OauthAccessToken: 'oauth_access_token',
+ OauthRefreshToken: 'oauth_refresh_token',
+ } as const;
+
+ export interface LeakedKeyReportResponse {
+ /** Whether a matching PostHog key or token was found and revoked. */
+ found: boolean;
+ /** The type of key that was found and revoked, or null if no match was found.
+ *
+ * * `personal_api_key` - personal_api_key
+ * * `project_secret_api_key` - project_secret_api_key
+ * * `oauth_access_token` - oauth_access_token
+ * * `oauth_refresh_token` - oauth_refresh_token */
+ type: LeakedKeyReportResponseTypeEnum | null;
+ }
+
export interface LegalDocumentCreator {
first_name: string;
email: string;