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(security): address post-merge findings on leaked-key revocation (#81631)

Tom Piccirello88df11ce27a7
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 872d8467730f..efe5cf3635cd 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -2300,7 +2300,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 is live it is revoked immediately and the owner is notified by email.
+ * 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.
*
* 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 6bd32299ce22..fb21335b2589 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -917,7 +917,7 @@ 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.
+ * 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.
*
* 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/posthog/api/leaked_key.py b/posthog/api/leaked_key.py
index 657b1d383782..8a768b98b358 100644
--- a/posthog/api/leaked_key.py
+++ b/posthog/api/leaked_key.py
@@ -50,7 +50,9 @@ class LeakedKeyReportResponseSerializer(serializers.Serializer):
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
+ 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.
Region-local only, no cross-region relay: a "found": false result does not rule
@@ -78,7 +80,9 @@ class PublicLeakedKeyReport(APIView):
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"
+ "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"
'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 "
@@ -94,20 +98,27 @@ class PublicLeakedKeyReport(APIView):
# 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.
+ # things that aren't PostHog keys at all.
+ properties: dict[str, str | int | bool | None] = {
+ "found": result.found,
+ "type": result.key_type,
+ "token_length": len(token),
+ # 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(),
+ }
+ if result.found:
+ # Only hash a token once it matched a real PostHog credential: those are
+ # high-entropy and this hash isn't practically reversible. For the common
+ # case of a caller pasting something that isn't a PostHog secret at all, an
+ # unsalted SHA-256 of a low-entropy string (a password, a short token) is
+ # dictionary/rainbow-table reversible, so we don't persist a recoverable
+ # copy of a third party's actual secret.
+ properties["token_sha256"] = sha256(token.encode("utf-8")).hexdigest()
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(),
- },
+ properties=properties,
)
return Response({"found": result.found, "type": result.key_type})
diff --git a/posthog/api/secret_revocation.py b/posthog/api/secret_revocation.py
index 3f37f45a2c6d..c97fa16f1e44 100644
--- a/posthog/api/secret_revocation.py
+++ b/posthog/api/secret_revocation.py
@@ -52,13 +52,18 @@ def _revoke_project_secret_api_key(token: str, more_info: str) -> bool:
def _revoke_oauth_token(token: str, more_info: str, *, kind: Literal["access", "refresh"]) -> bool:
+ # 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
+ # expiry would only block that revocation, not close any capability - both this
+ # endpoint and github.py's webhook are triggerable by anyone holding a copy of a
+ # token, dead or alive (a public GitHub commit gets scanned and reported the same
+ # as an anonymous POST here), so there is no less-exposed path to gate in favor of.
+ # The only real consequence of a match either way is forcing a re-authentication,
+ # not a confidentiality or integrity loss.
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():
+ if access_token is None:
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
diff --git a/posthog/api/test/test_github.py b/posthog/api/test/test_github.py
index ac84334e50f1..e60f52ce70c2 100644
--- a/posthog/api/test/test_github.py
+++ b/posthog/api/test/test_github.py
@@ -1031,6 +1031,58 @@ class TestOAuthTokenSecretAlert(APIBaseTest):
self.assertEqual(call_args[0][0], self.user.id)
self.assertEqual(call_args[0][1], "access")
+ @patch("posthog.api.github.verify_github_signature")
+ @patch("posthog.api.secret_revocation.send_oauth_token_exposed")
+ def test_expired_oauth_access_token_report_still_revokes_and_notifies(self, mock_send_email, mock_verify):
+ # An already-expired access token can't authenticate on its own, but revoking
+ # still matters if the same exposure also affects the longer-lived paired
+ # refresh token - and GitHub's scan-to-report latency for historical commits
+ # routinely exceeds the access token's own lifetime, so a report for an
+ # already-expired token is the common case here, not an edge case.
+ mock_verify.return_value = None
+
+ oauth_app = self._create_oauth_app()
+ token = "pha_expired_access_token_github_alert"
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token=token,
+ expires=timezone.now() - timedelta(hours=1),
+ scope="openid profile",
+ )
+ access_token_id = access_token.id
+ refresh_token = OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=oauth_app,
+ token="phr_live_session_for_expired_access",
+ access_token=access_token,
+ )
+
+ response = self.client.post(
+ "/api/alerts/github",
+ data=json.dumps(
+ [
+ {
+ "token": token,
+ "type": GITHUB_TYPE_FOR_OAUTH_ACCESS_TOKEN,
+ "url": "https://github.com/test/repo/blob/main/secrets.txt",
+ "source": "github",
+ }
+ ]
+ ),
+ content_type="application/json",
+ headers={"github-public-key-identifier": "test_kid", "github-public-key-signature": "test_sig"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data[0]["label"], "true_positive")
+
+ self.assertFalse(OAuthAccessToken.objects.filter(id=access_token_id).exists())
+ refresh_token.refresh_from_db()
+ self.assertIsNotNone(refresh_token.revoked)
+ mock_send_email.assert_called_once()
+
@patch("posthog.api.github.verify_github_signature")
@patch("posthog.api.secret_revocation.send_oauth_token_exposed")
def test_oauth_refresh_token_found_and_revoked(self, mock_send_email, mock_verify):
diff --git a/posthog/api/test/test_leaked_key.py b/posthog/api/test/test_leaked_key.py
index 5167a74ddc6f..00fe8371698d 100644
--- a/posthog/api/test/test_leaked_key.py
+++ b/posthog/api/test/test_leaked_key.py
@@ -204,32 +204,37 @@ class TestPublicLeakedKeyReport(APIBaseTest):
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.
+ 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
+ # token (up to 30 days), that's the only way to close it. Gating this on
+ # expiry wouldn't close any capability either way - this endpoint and
+ # github.py's webhook are both triggerable by anyone holding a copy of a
+ # token, dead or alive (a public GitHub commit gets scanned and reported the
+ # same as an anonymous POST here) - so there's no less-exposed path to prefer.
oauth_app = self._create_oauth_app()
expired_token = "pha_expired_leaked_access_token"
- OAuthAccessToken.objects.create(
+ 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(
+ refresh_token = OAuthRefreshToken.objects.create(
user=self.user,
application=oauth_app,
- token="phr_live_session_refresh_token",
+ token="phr_session_paired_with_expired_access",
+ access_token=access_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)
+ self.assertEqual(response.json(), {"found": True, "type": CANONICAL_OAUTH_ACCESS_TOKEN})
+ self.assertFalse(OAuthAccessToken.objects.filter(id=access_token.id).exists())
+ refresh_token.refresh_from_db()
+ self.assertIsNotNone(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
@@ -317,6 +322,36 @@ class TestPublicLeakedKeyReport(APIBaseTest):
self.assertFalse(OAuthAccessToken.objects.filter(id=first_access_token.id).exists())
self.assertFalse(OAuthAccessToken.objects.filter(id=second_access_token.id).exists())
+ @patch("posthog.api.secret_revocation.send_personal_api_key_exposed")
+ @patch("posthog.api.leaked_key.posthoganalytics.capture")
+ def test_analytics_capture_includes_token_hash_only_when_found(
+ self, mock_capture: MagicMock, mock_send_personal_api_key_exposed: MagicMock
+ ) -> None:
+ # A real PostHog key is high-entropy, so hashing it is safe to persist. An
+ # unrecognized string might be a low-entropy third-party secret pasted by
+ # mistake (a password, a short token) - an unsalted SHA-256 of that is
+ # dictionary/rainbow-table reversible, so it must not be persisted.
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="leaked",
+ secure_value=hash_key_value(token),
+ mask_value=mask_key_value(token),
+ scopes=["*"],
+ )
+
+ self._post(token)
+ found_properties = mock_capture.call_args.kwargs["properties"]
+ self.assertTrue(found_properties["found"])
+ self.assertIn("token_sha256", found_properties)
+
+ mock_capture.reset_mock()
+
+ self._post("not-a-posthog-key-at-all")
+ not_found_properties = mock_capture.call_args.kwargs["properties"]
+ self.assertFalse(not_found_properties["found"])
+ self.assertNotIn("token_sha256", not_found_properties)
+
def test_blank_token_returns_400(self) -> None:
response = self._post("")
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index a8db7d05b360..fed75b26e6c8 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -687,14 +687,21 @@ def revoke_oauth_session(
refresh_token.revoked = now
refresh_token.save(update_fields=["revoked"])
else:
- # Delete all access tokens for this user+application
- OAuthAccessToken.objects.filter(user=user, application=application).delete()
+ # Same ordering as revoke_application_sessions below, for the same two reasons:
+ # grants deleted first so this blocks on a racing code exchange's grant-row lock
+ # instead of missing tokens it mints; refresh revoked before access deleted so a
+ # mid-way failure can't leave a refresh token live after its access token is gone.
+ with transaction.atomic():
+ # Delete all grants for this user+application
+ OAuthGrant.objects.filter(user=user, application=application).delete()
- # Revoke all refresh tokens for this user+application
- OAuthRefreshToken.objects.filter(user=user, application=application, revoked__isnull=True).update(revoked=now)
+ # Revoke all refresh tokens for this user+application
+ OAuthRefreshToken.objects.filter(user=user, application=application, revoked__isnull=True).update(
+ revoked=now
+ )
- # Delete all grants for this user+application
- OAuthGrant.objects.filter(user=user, application=application).delete()
+ # Delete all access tokens for this user+application
+ OAuthAccessToken.objects.filter(user=user, application=application).delete()
def _refresh_token_may_have_untracked_access_tokens(refresh_token: OAuthRefreshToken) -> bool:
@@ -737,10 +744,15 @@ def revoke_oauth_token_session(
# 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()
+ #
+ # Revoke the refresh token before deleting the access token, in one transaction,
+ # so a mid-way failure can't leave the refresh token live after its access token
+ # is already gone (same reasoning as revoke_application_sessions below).
+ with transaction.atomic():
+ 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
@@ -750,11 +762,15 @@ def revoke_oauth_token_session(
# 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"])
+ # Revoke before deleting the linked access token(s), in one transaction, so a
+ # mid-way failure can't leave this refresh token live (and able to mint a new
+ # access token) after its access token is already gone.
+ with transaction.atomic():
+ refresh_token.revoked = now
+ refresh_token.save(update_fields=["revoked"])
+ OAuthAccessToken.objects.filter(
+ Q(pk=refresh_token.access_token_id) | Q(source_refresh_token=refresh_token)
+ ).delete()
def revoke_application_sessions(application: "OAuthApplication") -> None: