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(oauth): count refresh tokens as live application access (#84974)

Rafael Audibert313df67fd905
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d334d3e57db4..6b9c6f95de17 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8076,6 +8076,14 @@ snapshots:
hash: v1.k794b7964.f347e4ff8f76a746a240161e8323fde6febf434555caecefad6f5e0cd2264ee6.UkoGJ7GaxDEB3dtD8EAWEStRL9WgDIxMLi31doNFR_4
scenes-other-billing-product--billing-product-without-addons--light:
hash: v1.k794b7964.04856a286b0b3933aa364d7f73c56420e890f19d7f490a5aa12ae5616bf3258b.xQP5mvdnr6fC8UHtO4XZU4e-_cG8ZLzhKbnq_Ezmv10
+ scenes-other-credential-review--all-credential-types--dark:
+ hash: v1.k794b7964.502de2b6676b7b578c902d3cbb62f51e35ddf348bb0cd2807162528bcce4c376.qbegw_vWoSN2EqdVGYyc55BMKO6jz8LhMU5ssJP9qY4
+ scenes-other-credential-review--all-credential-types--light:
+ hash: v1.k794b7964.95a77379640830486e534a182ff6ec6937e65aab9945f38596c4e422bc4bdf1c.Lqw7L3IhU-tm8Zq7_QQzpHD2uTOt1chCfXG8ZuCbebY
+ scenes-other-credential-review--only-a-connected-application--dark:
+ hash: v1.k794b7964.14e0bfc13bd434fb412e7688322ffe805598d812bda148ccfee38a59742b7f5b.BHnYq5Ccs1ZeM0XTA0fy1U6yFZIdtPweyitDoVvQhPw
+ scenes-other-credential-review--only-a-connected-application--light:
+ hash: v1.k794b7964.6f1328f34df3a352191dd7620d0d17b014f1ef6ae9f360cb2652e37f4bb1fe70.aPWGUNuNHG6RO7SE2PQbah7SnpcQOFcKY3N1mX-Y8HU
scenes-other-integration-landing-page--connected--dark:
hash: v1.k794b7964.1a2abf46a5f43ec0e9bcf1f02115c68f3fab54fc8e8aec6f903e2481689d9a8c.oi6z4uOWfKTWAHVA_UhnCwGg-Zjal3CQ1Se4fDLVOMQ
scenes-other-integration-landing-page--connected--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 0dc96b266ea1..adb3559fbf6d 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4239,7 +4239,7 @@ export interface UserApi {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types: readonly string[]
readonly pending_invites: readonly PendingInviteApi[]
- /** True if the user has at least one Personal API Key or passkey and has not yet acknowledged their existing credentials. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
+ /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review: boolean
}
@@ -4348,7 +4348,7 @@ export interface PatchedUserApi {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types?: readonly string[]
readonly pending_invites?: readonly PendingInviteApi[]
- /** True if the user has at least one Personal API Key or passkey and has not yet acknowledged their existing credentials. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
+ /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review?: boolean
}
diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsx
new file mode 100644
index 000000000000..052cf5fe147d
--- /dev/null
+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsx
@@ -0,0 +1,91 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { urls } from 'scenes/urls'
+
+import { useStorybookMocks } from '~/mocks/browser'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+
+import { CredentialReview } from './CredentialReview'
+
+const meta: Meta<typeof CredentialReview> = {
+ title: 'Scenes-Other/Credential Review',
+ component: CredentialReview,
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ pageUrl: urls.credentialReview(),
+ testOptions: { waitForLoadersToDisappear: true },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof CredentialReview>
+
+const cloudPreflight = {
+ ...preflightJson,
+ cloud: true,
+ realm: 'cloud',
+}
+
+const partnerApiKey = {
+ id: 'key-1',
+ label: 'Partner setup key',
+ description: null,
+ created_at: '2026-08-01T09:12:00Z',
+ last_used_at: null,
+ last_rolled_at: null,
+ user_id: 1,
+ is_legacy_hashing: false,
+ scopes: ['insight:read', 'event:read', 'feature_flag:write'],
+ scoped_organizations: [],
+ scoped_teams: [2],
+ mask_value: 'phx_...abcd',
+}
+
+const partnerApp = {
+ id: '0192f0e4-1f2a-7000-8000-000000000001',
+ name: 'Acme Deploy',
+ logo_uri: null,
+ scopes: ['insight:read', 'event:read', 'feature_flag:write', 'dashboard:read'],
+ authorized_at: '2026-08-01T09:12:00Z',
+ is_verified: false,
+ is_first_party: false,
+}
+
+const passkey = {
+ id: 'passkey-1',
+ label: 'MacBook Pro',
+ credential_id: 'credential-1',
+ authenticator_type: 'platform',
+ created_at: '2026-08-01T09:14:00Z',
+ last_used_at: null,
+ verified: true,
+}
+
+export const AllCredentialTypes: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ '/_preflight': cloudPreflight,
+ '/api/personal_api_keys': [partnerApiKey],
+ '/api/webauthn/credentials/': [passkey],
+ '/api/oauth/connected-apps/': [partnerApp],
+ },
+ })
+ return <CredentialReview />
+ },
+}
+
+export const OnlyAConnectedApplication: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ '/_preflight': cloudPreflight,
+ '/api/personal_api_keys': [],
+ '/api/webauthn/credentials/': [],
+ '/api/oauth/connected-apps/': [partnerApp],
+ },
+ })
+ return <CredentialReview />
+ },
+}
diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx
index ac96fb99ea93..256832708b21 100644
--- a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx
+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx
@@ -5,6 +5,7 @@ import { LemonButton } from '@posthog/lemon-ui'
import { BridgePage } from 'lib/components/BridgePage/BridgePage'
import { HeartHog } from 'lib/components/hedgehogs'
import { SceneExport } from 'scenes/sceneTypes'
+import { connectedAppsLogic } from 'scenes/settings/user/connectedAppsLogic'
import { passkeySettingsLogic } from 'scenes/settings/user/passkeySettingsLogic'
import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'
@@ -20,6 +21,9 @@ export function CredentialReview(): JSX.Element {
const { markComplete } = useActions(credentialReviewLogic)
const { keysLoading } = useValues(personalAPIKeysLogic)
const { passkeysLoading } = useValues(passkeySettingsLogic)
+ const { connectedAppsLoading } = useValues(connectedAppsLogic)
+
+ const loading = keysLoading || passkeysLoading || connectedAppsLoading
return (
<BridgePage view="credential-review" fixedWidth={false}>
@@ -30,8 +34,8 @@ export function CredentialReview(): JSX.Element {
<HeartHog className="w-full h-full" />
</div>
<p className="mb-6 max-w-xl">
- Your account was set up with the credentials listed below. Review each one and revoke anything you
- don't recognize before continuing.
+ Your account was set up with the credentials and connected apps listed below. Review them and revoke
+ anything you don't recognize before continuing.
</p>
<div className="w-full mb-6 text-left">
<CredentialsReviewList />
@@ -40,7 +44,7 @@ export function CredentialReview(): JSX.Element {
type="primary"
size="large"
onClick={() => markComplete()}
- disabledReason={keysLoading || passkeysLoading ? 'Loading your credentials…' : null}
+ disabledReason={loading ? 'Loading your credentials…' : null}
>
Continue to PostHog
</LemonButton>
diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx
index 6cfb56821ee6..db0036f873a2 100644
--- a/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx
+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx
@@ -3,6 +3,8 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonDialog, LemonTable, Tooltip } from '@posthog/lemon-ui'
import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { ConnectedApps } from 'scenes/settings/user/ConnectedApps'
+import { connectedAppsLogic } from 'scenes/settings/user/connectedAppsLogic'
import { type PasskeyCredential, passkeySettingsLogic } from 'scenes/settings/user/passkeySettingsLogic'
import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'
@@ -55,9 +57,11 @@ export function CredentialsReviewList(): JSX.Element {
const { deleteKey } = useActions(personalAPIKeysLogic)
const { passkeys, passkeysLoading } = useValues(passkeySettingsLogic)
const { deletePasskey } = useActions(passkeySettingsLogic)
+ const { connectedApps, connectedAppsLoading } = useValues(connectedAppsLogic)
const showKeys = keysLoading || keys.length > 0
const showPasskeys = passkeysLoading || passkeys.length > 0
+ const showConnectedApps = connectedAppsLoading || connectedApps.length > 0
return (
<div className="flex flex-col gap-6">
@@ -169,6 +173,12 @@ export function CredentialsReviewList(): JSX.Element {
/>
</section>
)}
+ {showConnectedApps && (
+ <section>
+ <h3 className="text-base font-semibold mb-2">Connected applications</h3>
+ <ConnectedApps />
+ </section>
+ )}
</div>
)
}
diff --git a/posthog/api/oauth/connected_apps.py b/posthog/api/oauth/connected_apps.py
index 44a26f1f638c..1ba6838b2d99 100644
--- a/posthog/api/oauth/connected_apps.py
+++ b/posthog/api/oauth/connected_apps.py
@@ -1,4 +1,6 @@
-from django.utils import timezone
+import uuid
+from datetime import datetime
+from typing import cast
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status, viewsets
@@ -6,7 +8,13 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.auth import SessionAuthentication
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, revoke_oauth_session
+from posthog.models.oauth import (
+ OAuthApplication,
+ live_oauth_access_tokens,
+ live_oauth_refresh_tokens,
+ revoke_oauth_session,
+)
+from posthog.models.user import User
class ConnectedAppSerializer(serializers.Serializer):
@@ -31,27 +39,32 @@ class ConnectedAppsViewSet(viewsets.ViewSet):
@extend_schema(
responses={200: ConnectedAppSerializer(many=True)},
summary="List connected OAuth applications",
- description="Returns all OAuth applications that have active (non-expired) access tokens for the current user.",
+ description=(
+ "Returns all OAuth applications that can currently act as the requesting user, "
+ "whether they hold an unexpired access token or an unrevoked refresh token."
+ ),
)
def list(self, request: Request) -> Response:
- now = timezone.now()
+ user = cast(User, request.user)
+ app_map: dict[str, dict] = {}
- tokens = OAuthAccessToken.objects.filter(
- user=request.user,
- application__isnull=False,
- expires__gt=now,
- ).values("application_id", "scope", "created")
+ def record(application_id: uuid.UUID, created: datetime, scope: str | None) -> None:
+ entry = app_map.setdefault(str(application_id), {"authorized_at": created, "scopes": set()})
+ if created < entry["authorized_at"]:
+ entry["authorized_at"] = created
+ if scope:
+ entry["scopes"].update(scope.split())
- app_map: dict[str, dict] = {}
- for token in tokens:
- app_id = str(token["application_id"])
- if app_id not in app_map:
- app_map[app_id] = {"authorized_at": token["created"], "scopes": set()}
- else:
- if token["created"] < app_map[app_id]["authorized_at"]:
- app_map[app_id]["authorized_at"] = token["created"]
- if token["scope"]:
- app_map[app_id]["scopes"].update(token["scope"].split())
+ for access_token in live_oauth_access_tokens(user).values("application_id", "scope", "created"):
+ record(access_token["application_id"], access_token["created"], access_token["scope"])
+
+ # An unrevoked refresh token is standing access even in the windows where the app holds no
+ # unexpired access token, so listing on access tokens alone hides a connection the user
+ # still needs to see and revoke. Scope comes from the access token the refresh token was
+ # issued alongside, which survives its own expiry because `clear_expired` only deletes
+ # access tokens that have no refresh token.
+ for refresh_token in live_oauth_refresh_tokens(user).values("application_id", "created", "access_token__scope"):
+ record(refresh_token["application_id"], refresh_token["created"], refresh_token["access_token__scope"])
applications = OAuthApplication.objects.filter(id__in=app_map.keys())
@@ -80,20 +93,23 @@ class ConnectedAppsViewSet(viewsets.ViewSet):
description="Revokes all tokens and grants for the specified application for the current user.",
)
def revoke(self, request: Request, pk: str | None = None) -> Response:
- now = timezone.now()
-
- access_token = OAuthAccessToken.objects.filter(
- user=request.user,
- application_id=pk,
- expires__gt=now,
- ).first()
-
- if not access_token:
- return Response(
- {"detail": "No active connection found for this application."},
- status=status.HTTP_404_NOT_FOUND,
- )
-
- revoke_oauth_session(access_token=access_token)
-
- return Response(status=status.HTTP_204_NO_CONTENT)
+ user = cast(User, request.user)
+
+ access_token = live_oauth_access_tokens(user).filter(application_id=pk).first()
+ if access_token:
+ revoke_oauth_session(access_token=access_token)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ # Same reason the listing considers refresh tokens: without this fallback, an app the user
+ # can see in the list is un-revocable whenever its access token has lapsed, which is most
+ # of the time for a connection that refreshes on demand. Either entry point sweeps the
+ # whole (user, application) pair, so the outcome is identical.
+ refresh_token = live_oauth_refresh_tokens(user).filter(application_id=pk).first()
+ if refresh_token:
+ revoke_oauth_session(refresh_token=refresh_token)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ return Response(
+ {"detail": "No active connection found for this application."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
diff --git a/posthog/api/oauth/test_connected_apps.py b/posthog/api/oauth/test_connected_apps.py
index 0420868c86c8..55582deef9c0 100644
--- a/posthog/api/oauth/test_connected_apps.py
+++ b/posthog/api/oauth/test_connected_apps.py
@@ -6,6 +6,7 @@ from posthog.test.base import APIBaseTest
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
@@ -42,6 +43,20 @@ class TestConnectedAppsViewSet(APIBaseTest):
expires=timezone.now() + timedelta(hours=expires_hours),
)
+ def _create_refresh_token(
+ self,
+ app: OAuthApplication,
+ access_token: OAuthAccessToken | None = None,
+ revoked: bool = False,
+ ) -> OAuthRefreshToken:
+ return OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=app,
+ token=f"test-refresh-token-{OAuthRefreshToken.objects.count()}",
+ access_token=access_token,
+ revoked=timezone.now() if revoked else None,
+ )
+
def test_list_returns_apps_with_active_tokens(self):
app = self._create_app("Claude Code", logo_uri="https://example.com/logo.png")
self._create_token(app)
@@ -66,6 +81,29 @@ class TestConnectedAppsViewSet(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert len(response.json()) == 0
+ @parameterized.expand(
+ [
+ ("live_refresh_token", False, True),
+ ("revoked_refresh_token", True, False),
+ ]
+ )
+ def test_list_keys_on_live_refresh_tokens_not_only_access_tokens(
+ self, _name: str, revoked: bool, expected_listed: bool
+ ):
+ app = self._create_app()
+ access_token = self._create_token(app, scope="read write", expires_hours=-1)
+ self._create_refresh_token(app, access_token=access_token, revoked=revoked)
+
+ response = self.client.get("/api/oauth/connected-apps/")
+
+ assert response.status_code == status.HTTP_200_OK
+ if not expected_listed:
+ assert response.json() == []
+ return
+ assert len(response.json()) == 1
+ assert response.json()[0]["id"] == str(app.id)
+ assert set(response.json()[0]["scopes"]) == {"read", "write"}
+
def test_list_excludes_other_users_tokens(self):
other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
app = self._create_app()
@@ -149,6 +187,16 @@ class TestConnectedAppsViewSet(APIBaseTest):
assert OAuthGrant.objects.filter(user=self.user, application=app).count() == 0
+ def test_revoke_succeeds_when_only_a_refresh_token_is_live(self):
+ app = self._create_app()
+ access_token = self._create_token(app, expires_hours=-1)
+ refresh_token = self._create_refresh_token(app, access_token=access_token)
+
+ response = self.client.post(f"/api/oauth/connected-apps/{app.id}/revoke/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+
def test_revoke_does_not_affect_other_users_tokens(self):
other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
app = self._create_app()
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 48adc680bfa9..b5dec387550b 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -38,6 +38,7 @@ from posthog.models.oauth import (
OAuthGrant,
OAuthRefreshToken,
revoke_application_sessions,
+ revoke_oauth_session,
)
from posthog.models.team.team import Team
from posthog.scopes import get_oauth_scopes_supported
@@ -1745,6 +1746,58 @@ class TestOAuthAPI(APIBaseTest):
OAuthRefreshToken.objects.filter(application=self.confidential_application, revoked__isnull=True).exists()
)
+ @freeze_time("2026-01-01 00:00:00")
+ def test_refresh_racing_user_session_revoke_is_rejected(self):
+ # Same race as the app-wide case, on the per-connection revoke behind the connected-apps
+ # UI and RFC 7009. revoke_oauth_session deletes the pair's refresh tokens, so a refresh
+ # that validated before it committed cannot mint a replacement pair. Marking them revoked
+ # was not enough: the 120s grace period keeps a revoked token valid through
+ # validate_refresh_token, and RefreshToken.revoke() then returns silently on the
+ # already-revoked row, so DOT went on to mint a fresh access and refresh token.
+ refresh_token = self._create_refreshable_token_pair("openid")
+
+ with freeze_time("2026-01-01 00:00:05"):
+ revoke_oauth_session(refresh_token=refresh_token)
+
+ response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token.token,
+ "client_id": self.confidential_application.client_id,
+ "client_secret": "test_confidential_client_secret",
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "invalid_grant")
+ self._assert_no_live_tokens()
+
+ @freeze_time("2026-01-01 00:00:00")
+ def test_refresh_whose_token_is_deleted_while_waiting_for_the_lock_is_rejected(self):
+ # The reverse interleaving: the request passes validate_refresh_token in autocommit, then a
+ # revoke commits while it waits for the connection lock. Deleting the row from inside the
+ # lock call stands in for that commit, since the lock is where such a request waits. DOT
+ # re-reads the row with an unguarded .get(), which would surface as a 500.
+ refresh_token = self._create_refreshable_token_pair("openid")
+
+ def delete_the_connection(**kwargs: object) -> None:
+ OAuthRefreshToken.objects.filter(pk=refresh_token.pk).delete()
+
+ with patch("posthog.api.oauth.views.lock_oauth_connection", side_effect=delete_the_connection):
+ response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token.token,
+ "client_id": self.confidential_application.client_id,
+ "client_secret": "test_confidential_client_secret",
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "invalid_grant")
+
@freeze_time("2026-01-01 00:00:00")
def test_refresh_succeeds_for_token_issued_after_revoke(self):
# A token minted after the revoke stamp (i.e. the client re-authorized) refreshes normally.
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 17f87e643bb4..68fc3bb3f503 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -8,7 +8,7 @@ from urllib.parse import parse_qs, urlparse
from django.conf import settings
from django.core.exceptions import DisallowedRedirect
-from django.db import DatabaseError, OperationalError
+from django.db import DatabaseError, OperationalError, transaction
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils import timezone
@@ -67,6 +67,7 @@ from posthog.models.oauth import (
OAuthGrant,
OAuthRefreshToken,
TokenEndpointAuthMethod,
+ lock_oauth_connection,
revoke_oauth_session,
)
from posthog.scopes import (
@@ -752,7 +753,9 @@ class OAuthValidator(OAuth2Validator):
def save_bearer_token(self, token, request, *args, **kwargs):
"""
- Override to use custom token expiry for certain clients.
+ Override to use custom token expiry for certain clients, and to serialize a refresh
+ against a concurrent revoke of the same connection.
+
Sets token["expires_in"] before calling parent, which uses this value
when calculating the actual expiry datetime stored in the database.
"""
@@ -775,7 +778,28 @@ class OAuthValidator(OAuth2Validator):
refresh_token_suppressed=skip_refresh,
grant_type=getattr(request, "grant_type", "unknown"),
)
- return super().save_bearer_token(token, request, *args, **kwargs)
+
+ presented_refresh_token = getattr(request, "refresh_token_instance", None)
+ if not isinstance(presented_refresh_token, OAuthRefreshToken):
+ return super().save_bearer_token(token, request, *args, **kwargs)
+
+ # Take the connection lock before `super()`, which is where DOT opens its transaction and
+ # locks the refresh-token row: acquiring in the other order would deadlock against
+ # `revoke_oauth_session`, which takes this lock and then writes those same rows.
+ with transaction.atomic():
+ lock_oauth_connection(
+ user_id=presented_refresh_token.user_id,
+ application_id=presented_refresh_token.application_id,
+ )
+ # DOT validated this token in autocommit, so a revoke may have deleted the row while
+ # this request waited for the lock. DOT's own re-read is an unguarded `.get()`, which
+ # would surface as a 500; reject the grant instead so the client re-authorizes.
+ if not OAuthRefreshToken.objects.filter(pk=presented_refresh_token.pk).exists():
+ raise InvalidGrantError(
+ description="This application's access was revoked; re-authorize.",
+ request=request,
+ )
+ return super().save_bearer_token(token, request, *args, **kwargs)
def _save_bearer_token(self, token, request, *args, **kwargs):
"""
diff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.py
index f2f0c63c92fd..aadd33fc7c24 100644
--- a/posthog/api/personal_api_key.py
+++ b/posthog/api/personal_api_key.py
@@ -12,6 +12,7 @@ from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.helpers.dev_api_key import get_local_dev_api_key_value
from posthog.models import PersonalAPIKey, User
+from posthog.models.oauth import has_live_third_party_oauth_access
from posthog.models.personal_api_key import LEGACY_HASH_PREFIX
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value
@@ -196,7 +197,7 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
personal_api_key._value = value # type: ignore
# User created their FIRST PAT themselves through a session, so the credential
# review interstitial has nothing partner-issued to surface for them - mark it
- # acknowledged. Three gates, all load-bearing:
+ # acknowledged. Four gates, all load-bearing:
# - count == 0: no pre-existing PATs, so this is the user's first. If they
# already had keys, those might be partner-issued and still awaiting review,
# so don't stamp.
@@ -204,11 +205,15 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
# partner-issued PAT mint another PAT to silently dismiss the victim's
# review screen. Same constraint as credentials_review_complete.
# - credentials_reviewed_at IS NULL: don't clobber a real review timestamp.
+ # - no live third-party OAuth access: a partner-provisioned account has access
+ # to disclose even with no partner-issued PAT, and stamping here would retire
+ # the interstitial before the user was ever shown that connection.
request = self.context["request"]
if (
count == 0
and user.credentials_reviewed_at is None
and isinstance(getattr(request, "successful_authenticator", None), SessionAuthentication)
+ and not has_live_third_party_oauth_access(user)
):
user.credentials_reviewed_at = timezone.now()
user.save(update_fields=["credentials_reviewed_at"])
diff --git a/posthog/api/test/test_leaked_key.py b/posthog/api/test/test_leaked_key.py
index 00fe8371698d..456ac8114d0b 100644
--- a/posthog/api/test/test_leaked_key.py
+++ b/posthog/api/test/test_leaked_key.py
@@ -317,8 +317,7 @@ class TestPublicLeakedKeyReport(APIBaseTest):
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(OAuthRefreshToken.objects.filter(pk=leaked_refresh_token.pk).exists())
self.assertFalse(OAuthAccessToken.objects.filter(id=first_access_token.id).exists())
self.assertFalse(OAuthAccessToken.objects.filter(id=second_access_token.id).exists())
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index f400b1dca16b..60ed4915b952 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -18,9 +18,11 @@ from posthog.constants import AvailableFeature
from posthog.helpers.dev_api_key import get_local_dev_api_key_value
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.organization import Organization
from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKey
from posthog.models.team.team import Team
+from posthog.models.user import User
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value, mask_key_value
from products.product_analytics.backend.models.insight import Insight
@@ -65,6 +67,49 @@ class TestPersonalAPIKeysAPI(APIBaseTest):
}
assert data["value"].startswith("phx_") # Personal API key prefix
+ @parameterized.expand(
+ [
+ ("no_oauth_access", False, True),
+ ("live_third_party_oauth_access", True, False),
+ ]
+ )
+ def test_first_self_created_key_only_acknowledges_review_without_oauth_access(
+ self, _name: str, with_oauth_access: bool, expected_reviewed: bool
+ ):
+ User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
+ if with_oauth_access:
+ app = OAuthApplication.objects.create(
+ name="Provisioning partner",
+ client_id="test_pat_stamp_client_id",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=app,
+ token="test_pat_stamp_access_token",
+ scope="openid",
+ expires=timezone.now() - timedelta(hours=1),
+ )
+ OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=app,
+ token="test_pat_stamp_refresh_token",
+ access_token=access_token,
+ )
+
+ response = self.client.post(
+ "/api/personal_api_keys",
+ {"label": "My own key", "scopes": ["insight:read"], "scoped_organizations": [], "scoped_teams": []},
+ )
+
+ assert response.status_code == 201
+ assert (User.objects.get(pk=self.user.pk).credentials_reviewed_at is not None) is expected_reviewed
+
def test_create_personal_api_key_normalizes_blank_description_to_null(self):
response = self.client.post(
"/api/personal_api_keys",
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 10f66bebf290..af5d2cf963ff 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -362,6 +362,53 @@ class TestUserAPI(APIBaseTest):
assert response.status_code == 200
assert response.json()["requires_credential_review"] is True
+ @parameterized.expand(
+ [
+ ("live_access_token", 1, False, False, True),
+ ("live_refresh_token_only", -1, True, False, True),
+ ("expired_access_token_only", -1, False, False, False),
+ ("live_access_token_first_party", 1, False, True, False),
+ ]
+ )
+ def test_requires_credential_review_for_oauth_access(
+ self,
+ _name: str,
+ expires_hours: int,
+ with_refresh_token: bool,
+ is_first_party: bool,
+ expected: bool,
+ ):
+ User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
+ app = OAuthApplication.objects.create(
+ name="Provisioning partner",
+ client_id="test_credential_review_client_id",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ is_first_party=is_first_party,
+ )
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=app,
+ token="test_credential_review_access_token",
+ scope="openid",
+ expires=timezone.now() + timedelta(hours=expires_hours),
+ )
+ if with_refresh_token:
+ OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=app,
+ token="test_credential_review_refresh_token",
+ access_token=access_token,
+ )
+
+ response = self.client.get("/api/users/@me/")
+ assert response.status_code == 200
+ assert response.json()["requires_credential_review"] is expected
+
def test_credentials_review_complete_endpoint(self):
User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
PersonalAPIKey.objects.create(
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 58ebbf59ab1d..631a35302468 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -99,7 +99,7 @@ from posthog.middleware import (
is_read_only_impersonation,
)
from posthog.models import OrganizationInvite, Team, User, UserScenePersonalisation
-from posthog.models.oauth import OAuthGrant, find_oauth_refresh_token
+from posthog.models.oauth import OAuthGrant, find_oauth_refresh_token, has_live_third_party_oauth_access
from posthog.models.onboarding_delegation import cancel_pending_delegation, clear_delegation_state
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -282,10 +282,10 @@ class UserSerializer(serializers.ModelSerializer):
)
requires_credential_review = serializers.SerializerMethodField(
help_text=(
- "True if the user has at least one Personal API Key or passkey and has not yet "
- "acknowledged their existing credentials. Used to gate a one-shot review screen on "
- "first post-provisioning login. Becomes False once the user POSTs to "
- "`/api/users/@me/credentials_review_complete/`. Read-only."
+ "True if the user has at least one Personal API Key or passkey, or a third-party OAuth "
+ "application that can currently act as them, and has not yet acknowledged that access. "
+ "Used to gate a one-shot review screen on first post-provisioning login. Becomes False "
+ "once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only."
),
)
@@ -459,7 +459,13 @@ class UserSerializer(serializers.ModelSerializer):
return False
if PersonalAPIKey.objects.filter(user=instance).exists():
return True
- return WebauthnCredential.objects.filter(user=instance).exists()
+ if WebauthnCredential.objects.filter(user=instance).exists():
+ return True
+ # A provisioning partner's OAuth token is the access this screen exists to disclose, and it
+ # is the one form of it that leaves no credential on the user's own record. Without this the
+ # interstitial never fires for a partner that provisioned the account without also issuing a
+ # personal API key, which is the default (see `issues_personal_api_key`).
+ return has_live_third_party_oauth_access(instance)
@tracer.start_as_current_span("user_serializer.is_2fa_enabled")
def get_is_2fa_enabled(self, instance: User) -> bool:
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 94021d7f1e71..3305dfe22d2d 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -1,4 +1,5 @@
import enum
+import uuid
from typing import TYPE_CHECKING, cast
from urllib.parse import urlparse
@@ -7,7 +8,7 @@ from django.contrib.auth.signals import user_logged_out
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.core.exceptions import ValidationError
-from django.db import models, transaction
+from django.db import connection, models, transaction
from django.db.models import Q
from django.dispatch import receiver
from django.utils import timezone
@@ -652,6 +653,57 @@ def find_oauth_refresh_token(token: str) -> OAuthRefreshToken | None:
return None
+def live_oauth_access_tokens(user: "User") -> models.QuerySet[OAuthAccessToken]:
+ """Access tokens an application can still present as `user`."""
+ return OAuthAccessToken.objects.filter(user=user, application__isnull=False, expires__gt=timezone.now())
+
+
+def live_oauth_refresh_tokens(user: "User") -> models.QuerySet[OAuthRefreshToken]:
+ """Refresh tokens an application can still exchange for a new access token as `user`.
+
+ Unrevoked is the whole test. DOT's `validate_refresh_token` checks the token value, the
+ `revoked` timestamp, and the client, and never compares `created` against
+ REFRESH_TOKEN_EXPIRE_SECONDS; that setting only drives the `clear_expired` cleanup job. So a
+ refresh token whose access token lapsed hours ago still mints a new one on demand, which
+ means it has to count as standing access anywhere we answer "who can act as this user".
+ """
+ return OAuthRefreshToken.objects.filter(user=user, revoked__isnull=True)
+
+
+def has_live_third_party_oauth_access(user: "User") -> bool:
+ """Whether any non-first-party application can act as `user` right now.
+
+ Refresh tokens have to be counted here, because a provisioning partner holds one for the life
+ of the connection and owns no live access token at all between refreshes. Checking access
+ tokens alone would therefore report no access for a partner that has full standing access.
+
+ First-party applications are excluded because they are PostHog's own surfaces, so a token from
+ one is not the third-party access this answers about.
+ """
+ return OAuthApplication.objects.filter(
+ Q(id__in=live_oauth_access_tokens(user).values("application_id"))
+ | Q(id__in=live_oauth_refresh_tokens(user).values("application_id")),
+ is_first_party=False,
+ ).exists()
+
+
+def lock_oauth_connection(*, user_id: int, application_id: uuid.UUID) -> None:
+ """Serialize token minting against session revocation for one (user, application) pair.
+
+ Revocation cannot rely on row locks alone. DOT validates a refresh token in autocommit and only
+ locks the row later, inside `save_bearer_token`, so a mint can already hold that row lock when a
+ revoke arrives. The revoke's sweep then blocks, and when Postgres releases it the statement
+ re-checks the locked row but does not widen its snapshot, so a refresh token the mint inserted
+ meanwhile stays invisible to the sweep and outlives it.
+
+ Every party takes this lock before any row lock, so the acquisition order is identical on both
+ sides and a revoke waiting on a mint's row lock cannot deadlock against a mint waiting on this
+ one. See `OAuthValidator.save_bearer_token` for the minting side.
+ """
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [user_id, str(application_id)])
+
+
def revoke_oauth_session(
access_token: OAuthAccessToken | None = None, refresh_token: OAuthRefreshToken | None = None
) -> None:
@@ -689,16 +741,22 @@ def revoke_oauth_session(
else:
# 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
+ # instead of missing tokens it mints; refresh tokens deleted before access tokens so a
# mid-way failure can't leave a refresh token live after its access token is gone.
with transaction.atomic():
+ lock_oauth_connection(user_id=user.pk, application_id=application.pk)
+
# 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
- )
+ # Delete, rather than revoke, every refresh token for this user+application. Absence is
+ # what makes the revoke stick: `validate_refresh_token` looks a token up by value and
+ # rejects a miss, whereas a row marked `revoked` keeps validating for
+ # REFRESH_TOKEN_GRACE_PERIOD_SECONDS and then mints a replacement pair, because
+ # `RefreshToken.revoke()` returns silently on an already-revoked row. Deleting covers a
+ # token rotation already revoked too, which a `revoked__isnull=True` filter would skip
+ # while the grace period still accepts it.
+ OAuthRefreshToken.objects.filter(user=user, application=application).delete()
# Delete all access tokens for this user+application
OAuthAccessToken.objects.filter(user=user, application=application).delete()
diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.py
index 6b035e6b40c1..fd7d81cc2003 100644
--- a/posthog/models/test/test_oauth.py
+++ b/posthog/models/test/test_oauth.py
@@ -483,8 +483,7 @@ class TestOAuthModels(TestCase):
self.assertEqual(OAuthAccessToken.objects.filter(user=self.user, application=app).count(), 0)
self.assertEqual(OAuthGrant.objects.filter(user=self.user, application=app).count(), 0)
- refresh_token.refresh_from_db()
- self.assertIsNotNone(refresh_token.revoked)
+ self.assertFalse(OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists())
def test_revoke_oauth_session_with_null_user_still_revokes_specific_token(self):
app = OAuthApplication.objects.create(
@@ -591,8 +590,7 @@ class TestOAuthModels(TestCase):
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)
+ self.assertFalse(OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists())
@freeze_time("2026-01-01 00:00:00")
def test_revoke_application_sessions_revokes_across_all_users_and_leaves_other_apps(self):
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 25a3c9691eeb..32840cbc772a 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -201,7 +201,7 @@ class TestAutoProjectMiddleware(APIBaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- cls.base_app_num_queries = 52
+ cls.base_app_num_queries = 53
# Create another team that the user does have access to
cls.second_team = create_team(organization=cls.organization, name="Second Life")
@@ -355,7 +355,7 @@ class TestAutoProjectMiddleware(APIBaseTest):
with self.assertNumQueries(
FuzzyInt(self.base_app_num_queries, self.base_app_num_queries + 10)
- ): # +1 from activity logging _get_before_update(), +1 from passkey credential review check
+ ): # +1 from activity logging _get_before_update(), +1 from the credential review checks
response_app = self.client.get(f"/feature_flags/{feature_flag.id}")
response_users_api = self.client.get(f"/api/users/@me/")
response_users_api_data = response_users_api.json()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2142a58ad2fe..4efc74218ae1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55304,7 +55304,7 @@ export namespace Schemas {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types: readonly string[];
readonly pending_invites: readonly PendingInvite[];
- /** True if the user has at least one Personal API Key or passkey and has not yet acknowledged their existing credentials. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
+ /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review: boolean;
}
@@ -63749,7 +63749,7 @@ export namespace Schemas {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types?: readonly string[];
readonly pending_invites?: readonly PendingInvite[];
- /** True if the user has at least one Personal API Key or passkey and has not yet acknowledged their existing credentials. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
+ /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review?: boolean;
}