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): revoke refresh token families in constant queries on reuse detection (#83929)

Paul D'Ambra494678060d90
diff --git a/posthog/api/oauth/test_oauth_validator_fork.py b/posthog/api/oauth/test_oauth_validator_fork.py
new file mode 100644
index 000000000000..6d3e0d18358e
--- /dev/null
+++ b/posthog/api/oauth/test_oauth_validator_fork.py
@@ -0,0 +1,60 @@
+import hashlib
+import inspect
+from collections.abc import Callable
+
+from django.test import SimpleTestCase
+
+from oauth2_provider import __version__ as installed_dot_version
+from oauth2_provider.models import AbstractRefreshToken
+from oauth2_provider.oauth2_validators import OAuth2Validator
+from parameterized import parameterized
+
+# OAuthValidator.validate_refresh_token (posthog/api/oauth/views.py) is a line-for-line fork
+# of the upstream method with the reuse-protection family sweep replaced by
+# revoke_oauth_token_family (posthog/models/oauth.py). That helper reproduces the effects of
+# AbstractRefreshToken.revoke in bulk, and the sweep's correctness rests on how
+# _create_refresh_token assigns token_family. Pinning the upstream sources makes a
+# django-oauth-toolkit upgrade that touches any of them fail CI until the fork is
+# re-reviewed, instead of shipping with silently stale semantics.
+#
+# Known hazards when moving to django-oauth-toolkit 3.4+:
+# - validate_refresh_token looks tokens up by SHA-256 token_checksum; the token column
+# loses its unique index and is blank under hashed-at-rest storage, so the fork's
+# `token=` filter would lose its index or match nothing.
+# - request.refresh_token is assigned the raw presented token, not rt.token.
+# - RefreshToken.token becomes a TextField and the unique constraint moves to
+# (token_checksum, revoked); swapped models need a checksum backfill migration.
+PINNED_UPSTREAM_SOURCES: list[tuple[str, Callable[..., object], str]] = [
+ (
+ "OAuth2Validator.validate_refresh_token",
+ OAuth2Validator.validate_refresh_token,
+ "2e4789d15b0f661fe79734d20e7b04e15b0eb9dc6446f4dbe14538a2deb8c66f",
+ ),
+ (
+ "OAuth2Validator._create_refresh_token",
+ OAuth2Validator._create_refresh_token,
+ "f2d62a61db7fb44ce32a359311e18517e3936063a7615675543bec5f61b53991",
+ ),
+ (
+ "AbstractRefreshToken.revoke",
+ AbstractRefreshToken.revoke,
+ "cee9cbb06e002042f3341e35ccb8dc39ffc72e2c7d2959d464362a6fbc999349",
+ ),
+]
+
+
+class TestOAuthValidatorForkUpstreamPin(SimpleTestCase):
+ @parameterized.expand(PINNED_UPSTREAM_SOURCES)
+ def test_forked_upstream_source_is_unchanged(
+ self, name: str, method: Callable[..., object], pinned_sha256: str
+ ) -> None:
+ actual_sha256 = hashlib.sha256(inspect.getsource(method).encode()).hexdigest()
+ self.assertEqual(
+ actual_sha256,
+ pinned_sha256,
+ f"django-oauth-toolkit {installed_dot_version} changed {name}, which "
+ "OAuthValidator.validate_refresh_token (posthog/api/oauth/views.py) forks and "
+ "revoke_oauth_token_family (posthog/models/oauth.py) reproduces in bulk. Diff "
+ "the upstream method against the fork, port any behavior change (this file's "
+ "header lists the known 3.4+ hazards), then update the pinned hash here.",
+ )
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index b5dec387550b..a404db59e37a 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -10,7 +10,7 @@ from urllib.parse import parse_qs, quote, urlencode, urlparse, urlunparse
import pytest
from freezegun import freeze_time
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, FuzzyInt
from unittest.mock import patch
from django.conf import settings
@@ -2915,6 +2915,49 @@ class TestOAuthAPI(APIBaseTest):
# Some implementations may immediately revoke all tokens in the family,
# while others may only mark them as suspicious for future use
+ @freeze_time("2025-01-01 00:00:00")
+ def test_refresh_token_reuse_detection_query_count_is_constant_in_family_size(self):
+ # A rotating client grows its token family by one row per refresh, so a long-lived
+ # session can sit on a family of hundreds. Detecting reuse of a stale token must
+ # revoke the family in a constant number of queries, not one loop per member.
+ refresh_data = {
+ "grant_type": "refresh_token",
+ "client_id": self.confidential_application.client_id,
+ "client_secret": "test_confidential_client_secret",
+ }
+
+ for historical_members in (0, 5, 15):
+ response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
+ code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
+ token_response = self.post("/oauth/token/", {**self.base_token_body, "code": code})
+ stale_refresh_token = token_response.json()["refresh_token"]
+
+ first_refresh_response = self.post("/oauth/token/", {**refresh_data, "refresh_token": stale_refresh_token})
+ self.assertEqual(first_refresh_response.status_code, status.HTTP_200_OK)
+ live_refresh_token = first_refresh_response.json()["refresh_token"]
+ live_access_token = first_refresh_response.json()["access_token"]
+
+ family = OAuthRefreshToken.objects.get(token=live_refresh_token).token_family
+ for i in range(historical_members):
+ OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=self.confidential_application,
+ token=f"historical_rt_{family}_{i}",
+ token_family=family,
+ revoked=timezone.now(),
+ )
+
+ # Present the stale token after the grace period: reuse detection fires and
+ # the whole family is revoked. The query count must not scale with family size.
+ with freeze_time("2025-01-01 00:10:00"):
+ with self.assertNumQueries(FuzzyInt(12, 16)):
+ reuse_response = self.post("/oauth/token/", {**refresh_data, "refresh_token": stale_refresh_token})
+ self.assertEqual(reuse_response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(reuse_response.json()["error"], "invalid_grant")
+
+ self.assertEqual(OAuthRefreshToken.objects.filter(token_family=family, revoked__isnull=True).count(), 0)
+ self.assertFalse(OAuthAccessToken.objects.filter(token=live_access_token).exists())
+
@freeze_time("2025-01-01 00:00:00")
def test_multiple_refresh_token_rotations_preserve_token_family(self):
# Get initial tokens
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 68fc3bb3f503..0ee46b53f054 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -69,6 +69,7 @@ from posthog.models.oauth import (
TokenEndpointAuthMethod,
lock_oauth_connection,
revoke_oauth_session,
+ revoke_oauth_token_family,
)
from posthog.scopes import (
ALWAYS_ALLOWED_SCOPES,
@@ -849,6 +850,53 @@ class OAuthValidator(OAuth2Validator):
refresh_token_id=str(refresh_token_instance.pk),
)
+ def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):
+ """Fork of django-oauth-toolkit 3.2.x ``OAuth2Validator.validate_refresh_token``
+ with the reuse-protection family sweep made set-based.
+
+ Upstream revokes the compromised family one row at a time (``related_rt.revoke()``
+ per member). Each row costs a ``SELECT ... FOR UPDATE`` plus access-token cleanup,
+ even when already revoked, and a rotating session grows its family by one row per
+ refresh, so a long-lived client that keeps re-presenting a stale token turns every
+ ``/oauth/token`` request into hundreds of serial row-locking queries.
+
+ Everything here is upstream line for line except the two blocks marked
+ "PostHog:" below. ``test_oauth_validator_fork.py`` pins the upstream sources this
+ fork was taken from, so a django-oauth-toolkit upgrade that touches any of them
+ fails CI until this method is re-reviewed against the new upstream. Known hazards
+ when moving to 3.4+: refresh tokens are looked up by SHA-256 ``token_checksum``
+ there (the ``token`` column loses its unique index and is blank under
+ hashed-at-rest storage, so the ``token=`` filter below would lose its index or
+ match nothing), and ``request.refresh_token`` must become the raw presented token
+ rather than ``rt.token``.
+ """
+ # Upstream verbatim from here to the sweep, with RefreshToken resolved to our
+ # swapped OAuthRefreshToken model.
+ rt = OAuthRefreshToken.objects.filter(token=refresh_token).select_related("access_token").first()
+
+ if not rt:
+ return False
+
+ if rt.revoked is not None and rt.revoked <= timezone.now() - timedelta(
+ seconds=oauth2_settings.REFRESH_TOKEN_GRACE_PERIOD_SECONDS
+ ):
+ if oauth2_settings.REFRESH_TOKEN_REUSE_PROTECTION and rt.token_family:
+ # PostHog: upstream loops `related_rt.revoke()` over the whole family
+ # here. This batched sweep is the reason the method is forked.
+ revoke_oauth_token_family(rt)
+ return False
+
+ # Upstream verbatim: attach the validated token for get_original_scopes and
+ # save_bearer_token, which read request.refresh_token_instance.
+ request.user = rt.user
+ request.refresh_token = rt.token
+ request.refresh_token_instance = rt
+
+ # PostHog: upstream returns `rt.application == client`. Django model equality is
+ # pk-based and False against None, so this is equivalent while avoiding a lazy
+ # load of the Application row.
+ return client is not None and rt.application_id == client.pk
+
def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
"""
Sweep the full ``(user, application)`` access-token family when a
diff --git a/posthog/migrations/1312_oauthrefreshtoken_oauthrefreshtoken_family_idx.py b/posthog/migrations/1312_oauthrefreshtoken_oauthrefreshtoken_family_idx.py
new file mode 100644
index 000000000000..d09273d6d9e7
--- /dev/null
+++ b/posthog/migrations/1312_oauthrefreshtoken_oauthrefreshtoken_family_idx.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.17 on 2026-08-17 22:31
+
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ """
+ Index for revoke_oauth_token_family's sweep on the /oauth/token path. Without it
+ the sweep scans the whole refresh token table. Built concurrently (SHARE UPDATE
+ EXCLUSIVE) so the build doesn't block reads or writes on the token endpoint.
+ """
+
+ atomic = False
+
+ dependencies = [("posthog", "1311_alter_oauthapplication_client_id")]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="oauthrefreshtoken",
+ index=models.Index(fields=["token_family"], name="oauthrefreshtoken_family_idx"),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 2de2841afe78..26fd9a5d3ad5 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1311_alter_oauthapplication_client_id
+1312_oauthrefreshtoken_oauthrefreshtoken_family_idx
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 2a966ed1d64a..6aed21731f9d 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -593,6 +593,11 @@ class OAuthRefreshToken(AbstractRefreshToken):
verbose_name = "OAuth Refresh Token"
verbose_name_plural = "OAuth Refresh Tokens"
swappable = "OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL"
+ indexes = [
+ # revoke_oauth_token_family sweeps by token_family on the /oauth/token path;
+ # without this index the sweep scans the whole refresh token table.
+ models.Index(fields=["token_family"], name="oauthrefreshtoken_family_idx"),
+ ]
id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)
@@ -784,6 +789,35 @@ def revoke_oauth_session(
OAuthAccessToken.objects.filter(user=user, application=application).delete()
+def revoke_oauth_token_family(refresh_token: OAuthRefreshToken) -> None:
+ """Revoke every live member of a refresh token's family in a constant number of
+ queries, and delete the access tokens still linked to them.
+
+ Use this when refresh-token reuse protection fires and the whole family is suspect:
+ DOT's per-row `RefreshToken.revoke()` loop costs a `SELECT ... FOR UPDATE` per family
+ member, even already-revoked ones.
+
+ This reproduces the effects of upstream's `AbstractRefreshToken.revoke` (stamp
+ `revoked`, delete the linked access token) in bulk, so any new effect upstream adds to
+ `revoke()` must be mirrored here. `posthog/api/oauth/test_oauth_validator_fork.py`
+ pins that upstream source and fails when it changes."""
+ # Rows without a family (pre-rotation-refresh tokens, non-rotating clients) are their
+ # own lineage: sweeping them by token_family=None would revoke unrelated tokens.
+ if refresh_token.token_family is None:
+ return
+ now = timezone.now()
+ with transaction.atomic():
+ # Revoke refresh tokens before deleting access tokens, in one transaction, so a
+ # mid-way failure can't leave one of them live after its access token is gone
+ # (same ordering as revoke_oauth_session above). The delete joins through the
+ # subquery instead of listing ids in Python: reuse protection fires rarely, but
+ # a compromised family can hold tens of thousands of historical rows.
+ OAuthRefreshToken.objects.filter(token_family=refresh_token.token_family, revoked__isnull=True).update(
+ revoked=now
+ )
+ OAuthAccessToken.objects.filter(refresh_token__token_family=refresh_token.token_family).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,
diff --git a/posthog/test/test_migration_1310.py b/posthog/test/test_migration_1310.py
index 4bad2e0ef082..5f8db3ff9e62 100644
--- a/posthog/test/test_migration_1310.py
+++ b/posthog/test/test_migration_1310.py
@@ -1,9 +1,10 @@
from typing import Any
-from posthog.test.base import TestMigrations
+from posthog.test.base import NonAtomicTestMigrations
-class ProvisioningRateLimitOverridesMigrationTest(TestMigrations):
+# Non-atomic so a later posthog migration with a CONCURRENTLY index doesn't break the rewind.
+class ProvisioningRateLimitOverridesMigrationTest(NonAtomicTestMigrations):
migrate_from = "1309_integration_kind_ext_idx"
migrate_to = "1310_provisioning_rate_limit_overrides"