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): insert new access token per non-rotating refresh (#58199)

Matt Brookerb4d8f95dec0a
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 8043570d25ff..592b968bdc97 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -3195,6 +3195,302 @@ class TestOAuthAPI(APIBaseTest):
db_refresh_token = OAuthRefreshToken.objects.get(token=original_refresh_token)
self.assertIsNone(db_refresh_token.revoked)
+ @freeze_time("2025-01-01 00:00:00")
+ def test_dcr_refresh_does_not_invalidate_previously_issued_access_tokens(self):
+ # Each refresh on a non-rotating client must issue a NEW OAuthAccessToken row, not
+ # overwrite the existing one. Overwriting causes a body/DB token mismatch under
+ # concurrent refreshes: the upstream post-grant lookup at oauth2_provider/views/base.py:309
+ # does objects.get(token_checksum=sha256(body_access_token)) and any concurrent writer's
+ # body now contains a value that the row no longer has — DoesNotExist propagates as a 500.
+ self.public_application.is_dcr_client = True
+ self.public_application.save()
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "response_type": "code",
+ "code_challenge": self.code_challenge,
+ "code_challenge_method": "S256",
+ "allow": True,
+ "access_level": OAuthApplicationAccessLevel.ALL.value,
+ "scoped_organizations": [],
+ "scoped_teams": [],
+ "scope": "openid",
+ },
+ )
+ code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
+
+ token_response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "code": code,
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "code_verifier": self.code_verifier,
+ },
+ )
+ refresh_token = token_response.json()["refresh_token"]
+ access_token_after_grant = token_response.json()["access_token"]
+
+ first_refresh = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": self.public_application.client_id,
+ },
+ )
+ self.assertEqual(first_refresh.status_code, status.HTTP_200_OK)
+ access_token_after_first_refresh = first_refresh.json()["access_token"]
+ self.assertNotEqual(access_token_after_first_refresh, access_token_after_grant)
+
+ second_refresh = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": self.public_application.client_id,
+ },
+ )
+ self.assertEqual(second_refresh.status_code, status.HTTP_200_OK)
+ access_token_after_second_refresh = second_refresh.json()["access_token"]
+
+ # Each refresh must return a distinct access_token; otherwise both existence
+ # checks below would still pass against a single shared row.
+ self.assertNotEqual(access_token_after_first_refresh, access_token_after_second_refresh)
+
+ # Each access_token returned in a /oauth/token response must remain resolvable
+ # in the database afterwards. Upstream's non-rotating UPDATE branch overwrites the
+ # one row, so the first refresh's token disappears as soon as the second refresh runs.
+ self.assertTrue(
+ OAuthAccessToken.objects.filter(token=access_token_after_first_refresh).exists(),
+ "access_token returned by the first refresh must still exist in the database "
+ "after a subsequent refresh on the same non-rotating refresh_token",
+ )
+ self.assertTrue(
+ OAuthAccessToken.objects.filter(token=access_token_after_second_refresh).exists(),
+ )
+
+ # The token_checksum lookup at oauth2_provider/views/base.py:309 must succeed for
+ # every previously-issued token. Replicate that lookup to assert the bug is gone.
+ first_checksum = hashlib.sha256(access_token_after_first_refresh.encode("utf-8")).hexdigest()
+ self.assertTrue(
+ OAuthAccessToken.objects.filter(token_checksum=first_checksum).exists(),
+ "token_checksum for a previously-issued access_token must still resolve — "
+ "the post-grant lookup at oauth2_provider/views/base.py:309 depends on it",
+ )
+
+ @parameterized.expand(
+ [
+ # RFC 7009 §4.1.2 makes token_type_hint optional; the sweep must fire in all three cases.
+ ("with_refresh_token_hint", "refresh_token"),
+ ("with_no_hint", None),
+ ("with_wrong_access_token_hint", "access_token"),
+ ]
+ )
+ @freeze_time("2025-01-01 00:00:00")
+ def test_dcr_refresh_token_revoke_sweeps_all_refresh_issued_access_tokens(self, _name, hint):
+ # Revoking a non-rotating refresh token via /oauth/revoke/ must invalidate every
+ # access_token issued from it, not just the original authorization_code-issued
+ # row. Refresh-issued rows carry source_refresh_token=None, so the upstream
+ # RefreshToken.revoke() path (which follows the OneToOne back-reference) would
+ # leave them valid until expiry — up to 7 days for DCR/CIMD clients.
+ self.public_application.is_dcr_client = True
+ self.public_application.save()
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "response_type": "code",
+ "code_challenge": self.code_challenge,
+ "code_challenge_method": "S256",
+ "allow": True,
+ "access_level": OAuthApplicationAccessLevel.ALL.value,
+ "scoped_organizations": [],
+ "scoped_teams": [],
+ "scope": "openid",
+ },
+ )
+ code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
+
+ token_response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "code": code,
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "code_verifier": self.code_verifier,
+ },
+ )
+ refresh_token = token_response.json()["refresh_token"]
+ original_access_token = token_response.json()["access_token"]
+
+ refresh_response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": self.public_application.client_id,
+ },
+ )
+ refresh_issued_access_token = refresh_response.json()["access_token"]
+
+ # Sanity check: both tokens exist before revoke, and they are distinct rows.
+ self.assertTrue(OAuthAccessToken.objects.filter(token=original_access_token).exists())
+ self.assertTrue(OAuthAccessToken.objects.filter(token=refresh_issued_access_token).exists())
+ self.assertNotEqual(original_access_token, refresh_issued_access_token)
+
+ revoke_body = {
+ "token": refresh_token,
+ "client_id": self.public_application.client_id,
+ }
+ if hint is not None:
+ revoke_body["token_type_hint"] = hint
+ revoke_response = self.post("/oauth/revoke/", revoke_body)
+ self.assertEqual(revoke_response.status_code, status.HTTP_200_OK)
+
+ self.assertFalse(OAuthAccessToken.objects.filter(token=original_access_token).exists())
+ self.assertFalse(
+ OAuthAccessToken.objects.filter(token=refresh_issued_access_token).exists(),
+ "refresh-issued access tokens with source_refresh_token=None must also be "
+ "swept when their refresh token is revoked",
+ )
+
+ @freeze_time("2025-01-01 00:00:00")
+ def test_dcr_refresh_token_revoke_from_other_client_does_not_sweep_session(self):
+ # RFC 7009 §2.1: the server verifies the token was issued to the requesting
+ # client. A different dynamic client presenting app A's refresh token must not
+ # trigger the (user, application) session sweep for app A.
+ self.public_application.is_dcr_client = True
+ self.public_application.save()
+
+ other_dynamic_application = OAuthApplication.objects.create(
+ name="Other Dynamic App",
+ client_id="other_dynamic_client_id",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ user=self.user,
+ hash_client_secret=True,
+ algorithm="RS256",
+ is_dcr_client=True,
+ )
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "response_type": "code",
+ "code_challenge": self.code_challenge,
+ "code_challenge_method": "S256",
+ "allow": True,
+ "access_level": OAuthApplicationAccessLevel.ALL.value,
+ "scoped_organizations": [],
+ "scoped_teams": [],
+ "scope": "openid",
+ },
+ )
+ code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
+
+ token_response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "code": code,
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "code_verifier": self.code_verifier,
+ },
+ )
+ refresh_token = token_response.json()["refresh_token"]
+
+ refresh_response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": self.public_application.client_id,
+ },
+ )
+ refresh_issued_access_token = refresh_response.json()["access_token"]
+ self.assertTrue(OAuthAccessToken.objects.filter(token=refresh_issued_access_token).exists())
+
+ revoke_response = self.post(
+ "/oauth/revoke/",
+ {
+ "token": refresh_token,
+ "client_id": other_dynamic_application.client_id,
+ },
+ )
+ self.assertEqual(revoke_response.status_code, status.HTTP_200_OK)
+
+ self.assertTrue(
+ OAuthAccessToken.objects.filter(token=refresh_issued_access_token).exists(),
+ "a dynamic client presenting another app's refresh token must not sweep "
+ "that app's (user, application) access-token family",
+ )
+
+ @freeze_time("2026-01-01 00:00:00")
+ def test_dcr_non_rotating_refresh_racing_app_revoke_is_rejected(self):
+ # The non-rotating (DCR) refresh path passes the presented token via
+ # scope_source_refresh_token with source_refresh_token=None, so the mint-time revoke
+ # guard must check that param too. Otherwise a non-rotating refresh that races
+ # revoke_application_sessions slips past _reject_refresh_racing_revoke and mints a token
+ # the bulk sweep already missed.
+ self.public_application.is_dcr_client = True
+ self.public_application.save()
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "response_type": "code",
+ "code_challenge": self.code_challenge,
+ "code_challenge_method": "S256",
+ "allow": True,
+ "access_level": OAuthApplicationAccessLevel.ALL.value,
+ "scoped_organizations": [],
+ "scoped_teams": [],
+ "scope": "openid",
+ },
+ )
+ code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
+ refresh_token = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "code": code,
+ "client_id": self.public_application.client_id,
+ "redirect_uri": "https://example.com/callback",
+ "code_verifier": self.code_verifier,
+ },
+ ).json()["refresh_token"]
+
+ with freeze_time("2026-01-01 00:00:05"):
+ revoke_application_sessions(self.public_application)
+ refresh_response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": self.public_application.client_id,
+ },
+ )
+
+ self.assertEqual(refresh_response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(refresh_response.json()["error"], "invalid_grant")
+ self.assertFalse(
+ OAuthRefreshToken.objects.filter(application=self.public_application, revoked__isnull=True).exists()
+ )
+
@freeze_time("2025-01-01 00:00:00")
def test_non_dcr_client_refresh_token_is_rotated(self):
self.public_application.is_dcr_client = False
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index d36877fb2baa..9ba2c1c604e9 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -17,7 +17,7 @@ from django.views.decorators.csrf import csrf_exempt
import structlog
import posthoganalytics
from oauth2_provider.compat import login_not_required
-from oauth2_provider.exceptions import OAuthToolkitError
+from oauth2_provider.exceptions import FatalClientError, OAuthToolkitError
from oauth2_provider.http import OAuth2ResponseRedirect
from oauth2_provider.oauth2_validators import OAuth2Validator
from oauth2_provider.settings import oauth2_settings
@@ -48,7 +48,7 @@ from posthog.api.oauth.cimd import (
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
from posthog.middleware import is_read_only_impersonation
from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User
-from posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken
+from posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken, revoke_oauth_session
from posthog.scopes import (
ALWAYS_ALLOWED_SCOPES,
downgrade_scopes_to_read_only,
@@ -508,6 +508,87 @@ class OAuthValidator(OAuth2Validator):
)
return super().save_bearer_token(token, request, *args, **kwargs)
+ def _save_bearer_token(self, token, request, *args, **kwargs):
+ """
+ Insert a new access_token row per non-rotating refresh instead of
+ overwriting the previous one. Upstream's non-rotating branch
+ SELECT FOR UPDATEs and writes over a single AccessToken row, so
+ concurrent refreshes for the same RT corrupt each others' response
+ bodies (the losing writers return a token whose DB row was just
+ overwritten by the winner, then upstream's post-grant
+ ``objects.get(token_checksum=...)`` misses and 500s).
+
+ ``OAuthAccessToken.source_refresh_token`` is OneToOne, so only the
+ original ``authorization_code``-issued AT keeps the back-reference;
+ refresh-issued rows pass ``source_refresh_token=None`` and stay
+ addressable by token / token_checksum.
+ """
+ refresh_token_code = token.get("refresh_token")
+ refresh_token_instance = getattr(request, "refresh_token_instance", None)
+
+ is_non_rotating_refresh = (
+ refresh_token_code
+ and not self.rotate_refresh_token(request)
+ and isinstance(refresh_token_instance, OAuthRefreshToken)
+ )
+ if not is_non_rotating_refresh:
+ return super()._save_bearer_token(token, request, *args, **kwargs)
+
+ assert isinstance(refresh_token_instance, OAuthRefreshToken)
+
+ if "scope" not in token:
+ raise FatalClientError("Failed to renew access token: missing scope")
+
+ expires = timezone.now() + timedelta(
+ seconds=token.get("expires_in", oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS),
+ )
+
+ self._create_access_token(
+ expires,
+ request,
+ token,
+ source_refresh_token=None,
+ scope_source_refresh_token=refresh_token_instance,
+ )
+ logger.info(
+ "oauth_non_rotating_refresh_inserted",
+ client_id_prefix=str(getattr(request.client, "client_id", "")[:8]),
+ refresh_token_id=str(refresh_token_instance.pk),
+ )
+
+ def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
+ """
+ Sweep the full ``(user, application)`` access-token family when a
+ non-rotating refresh token is revoked via RFC 7009.
+
+ Upstream's ``RefreshToken.revoke()`` only deletes the AT linked via the
+ OneToOne ``RefreshToken.access_token`` FK. Refresh-issued rows from our
+ non-rotating ``_save_bearer_token`` branch carry
+ ``source_refresh_token=None`` so they would survive that path and stay
+ valid until expiry. ``revoke_oauth_session`` deletes by
+ ``(user, application)``, which is the same semantics the UI revoke flow
+ in ``connected_apps`` uses.
+
+ ``token_type_hint`` is OPTIONAL per RFC 7009 §2.1 and the server MUST
+ fall back to searching all token types when the hint doesn't locate the
+ token. We always probe the refresh-token table so the sweep fires for
+ omitted, ``refresh_token``, and (incorrect) ``access_token`` hints
+ alike; a single indexed lookup is cheap and the cost of getting this
+ wrong is leaving compromised tokens valid.
+
+ The sweep only fires when the presented token belongs to the
+ authenticated client (RFC 7009 §2.1: the server verifies the token was
+ issued to the requesting client). Without that binding, any dynamic
+ client that learned another app's refresh token could revoke that
+ app's entire ``(user, application)`` session instead of just the one
+ token upstream would revoke.
+ """
+ rt = OAuthRefreshToken.objects.filter(token=token, revoked__isnull=True).first()
+ if rt and self._is_dynamic_client(request) and rt.application_id == getattr(request.client, "pk", None):
+ revoke_oauth_session(refresh_token=rt)
+ return
+ return super().revoke_token(token, token_type_hint, request, *args, **kwargs)
+
def get_additional_claims(self, request):
return {
"given_name": request.user.first_name,
@@ -566,17 +647,35 @@ class OAuthValidator(OAuth2Validator):
request=request,
)
- def _create_access_token(self, expires, request, token, source_refresh_token=None):
- if source_refresh_token is not None:
- self._reject_refresh_racing_revoke(request, source_refresh_token)
+ def _create_access_token(
+ self,
+ expires,
+ request,
+ token,
+ source_refresh_token=None,
+ scope_source_refresh_token=None,
+ ):
+ # A refresh reaches here with the presented token in either ``source_refresh_token``
+ # (rotating) or ``scope_source_refresh_token`` (non-rotating, where the OneToOne FK is
+ # left null so sibling rows stay addressable) — both must be checked against an app-wide
+ # revoke, or a non-rotating refresh could race the revoke and mint a surviving token.
+ # Only a true authorization-code exchange reaches here with neither.
+ refresh_token = source_refresh_token or scope_source_refresh_token
+ if refresh_token is not None:
+ self._reject_refresh_racing_revoke(request, refresh_token)
else:
self._reject_code_exchange_racing_revoke(request)
id_token = token.get("id_token", None)
if id_token:
id_token = self._load_id_token(id_token)
+ # ``scope_source_refresh_token`` lets the caller inherit scopes from a
+ # refresh_token without taking the OneToOne ``source_refresh_token`` FK
+ # (needed by the non-rotating refresh path, where multiple rows share
+ # one RT but only the original can hold the back-reference).
+ scope_refresh_token = scope_source_refresh_token or source_refresh_token
scoped_teams, scoped_organizations = self._get_scoped_teams_and_organizations(
- request, access_token=None, grant=None, refresh_token=source_refresh_token
+ request, access_token=None, grant=None, refresh_token=scope_refresh_token
)
return OAuthAccessToken.objects.create(