: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(oauth): app-wide session revoke + refresh narrowing tests (#61711)
Matt Brookerbc62bc0c3e6e
diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex 88adf5656130..c6487c2e44fc 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -1,6 +1,6 @@import jsonimport time-from datetime import timedelta+from datetime import datetime, timedeltafrom urllib.parse import parse_qs, urlparsefrom unittest.mock import patch@@ -66,6 +66,17 @@ class TestAccountRequests(ProvisioningTestBase):assert user.organization is not Noneassert user.team is not None+ def test_new_user_auth_code_cached_with_issued_at(self):+ payload = self._account_request_payload()+ res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)+ code = res.json()["oauth"]["code"]+ code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")+ assert code_data is not None+ # Without issued_at the code exchange fails closed once the app is ever session-revoked,+ # which would block every new user. See _exchange_authorization_code's revoke guard.+ assert "issued_at" in code_data+ datetime.fromisoformat(code_data["issued_at"])+def test_existing_user_returns_oauth_type_with_code(self):User.objects.create_and_join(organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.pyindex 083115cc0ef7..75e62c9dec76 100644--- a/ee/api/agentic_provisioning/test/test_oauth_token.py+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py@@ -1,8 +1,10 @@import time+from datetime import timedeltafrom urllib.parse import urlencodefrom django.core.cache import cachefrom django.test import override_settings+from django.utils import timezonefrom parameterized import parameterized@@ -202,6 +204,59 @@ class TestOAuthTokenExchange(ProvisioningTestBase):assert res.status_code == 400assert res.json()["error"] == "invalid_grant"+ def _stamp_session_revoke(self, when=None) -> None:+ OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).update(+ sessions_revoked_at=when or timezone.now()+ )++ def test_refresh_rejected_when_token_predates_session_revoke(self):+ # Stamp without sweeping, simulating a refresh token the bulk revoke missed.+ self._store_auth_code("revoke_refresh", issued_at=timezone.now().isoformat())+ first = self._post_token(self._token_request_body(code="revoke_refresh"))+ refresh_token = first.json()["refresh_token"]++ self._stamp_session_revoke()++ tokens_before = OAuthAccessToken.objects.count()+ refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()+ res = self._post_token(refresh_body)+ assert res.status_code == 400+ body = res.json()+ assert body["error"] == "invalid_grant"+ assert "revoked" in body["error_description"]+ assert OAuthAccessToken.objects.count() == tokens_before++ def test_refresh_allowed_when_token_postdates_session_revoke(self):+ self._stamp_session_revoke(timezone.now() - timedelta(hours=1))+ self._store_auth_code("post_revoke", issued_at=timezone.now().isoformat())+ first = self._post_token(self._token_request_body(code="post_revoke"))+ assert first.status_code == 200++ refresh_body = urlencode(+ {"grant_type": "refresh_token", "refresh_token": first.json()["refresh_token"]}+ ).encode()+ res = self._post_token(refresh_body)+ assert res.status_code == 200++ @parameterized.expand(+ [+ ("issued_before_revoke", -120, 400),+ ("missing_issued_at", None, 400),+ ("issued_after_revoke", 120, 200),+ ]+ )+ def test_code_exchange_against_session_revoke_stamp(self, _name, issued_offset_seconds, expected_status):+ overrides = {}+ if issued_offset_seconds is not None:+ overrides["issued_at"] = (timezone.now() + timedelta(seconds=issued_offset_seconds)).isoformat()+ self._store_auth_code("revoke_code", **overrides)+ self._stamp_session_revoke()++ res = self._post_token(self._token_request_body(code="revoke_code"))+ assert res.status_code == expected_status+ if expected_status == 400:+ assert res.json()["error"] == "invalid_grant"+class TestLegacyStripeOAuthApp(ProvisioningTestBase):def _stripe_app(self) -> OAuthApplication:diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex fbc5c2414e07..8c625ca8d3bd 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -7,7 +7,7 @@ import base64import hashlibimport secretsimport unicodedata-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Any, castfrom urllib.parse import urlencode@@ -34,13 +34,7 @@ from rest_framework.response import Responsefrom posthog.api.authentication import password_reset_token_generatorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import StripeIntegration-from posthog.models.oauth import (- OAuthAccessToken,- OAuthApplication,- OAuthRefreshToken,- find_oauth_access_token,- find_oauth_refresh_token,-)+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, find_oauth_access_tokenfrom posthog.models.personal_api_key import PersonalAPIKey, hash_key_valuefrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -579,6 +573,7 @@ def _handle_existing_user(cache.set(f"{AUTH_CODE_CACHE_PREFIX}{code}",{+ "issued_at": timezone.now().isoformat(),"user_id": user.id,"org_id": str(team.organization_id),"team_id": team.id,@@ -752,6 +747,7 @@ def _handle_new_user(cache.set(cache_key,{+ "issued_at": timezone.now().isoformat(),"user_id": user.id,"org_id": str(organization.id),"team_id": team.id,@@ -844,6 +840,7 @@ def agentic_authorize(request: Any) -> HttpResponseBase:cache.set(f"{AUTH_CODE_CACHE_PREFIX}{code}",{+ "issued_at": timezone.now().isoformat(),"user_id": user.id,"org_id": str(organization.id),"team_id": team.id,@@ -951,6 +948,7 @@ def agentic_authorize_confirm(request: Request) -> Response:cache.set(f"{AUTH_CODE_CACHE_PREFIX}{code}",{+ "issued_at": timezone.now().isoformat(),"user_id": user.id,"org_id": str(team.organization_id),"team_id": team.id,@@ -999,6 +997,18 @@ def oauth_token(request: Request) -> Response:)+def _lock_application(application_id: int) -> OAuthApplication | None:+ """Row-lock the OAuthApplication so direct-mint serializes with revoke_application_sessions.++ The revoke updates this row first and holds the lock for its whole transaction before+ sweeping tokens, so a mint that takes the same lock is forced into one of two safe orders:+ it holds the lock and its new tokens land before the revoke's sweep (which then catches+ them), or the revoke committed first and the caller reads the now-visible+ `sessions_revoked_at` and rejects. Must be called inside `transaction.atomic()`.+ """+ return OAuthApplication.objects.select_for_update().filter(pk=application_id).first()++def _exchange_authorization_code(request: Request) -> Response:code = request.data.get("code", "")if not code:@@ -1075,43 +1085,64 @@ def _exchange_authorization_code(request: Request) -> Response:{"error": "server_error", "error_description": "OAuth application is not configured"}, status=500)- # Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope- # ceiling has to be enforced here before the token is created by hand.- requested_scopes = scopes if scopes else StripeIntegration.SCOPES.split()- app_scopes = oauth_app.scopes if oauth_app else []- if not scopes_within_ceiling(requested_scopes, app_scopes):- _capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="authorization_code")- return Response(- {- "error": "invalid_scope",- "error_description": "Requested scopes exceed the application's allowed scopes",- },- status=400,- )- scope_str = " ".join(requested_scopes)+ # Lock the app row before reading the revoke stamp and minting, so this serializes+ # with revoke_application_sessions (see _lock_application). Provisioning auth codes+ # live in the cache, not OAuthGrant, so the revoke's sweep can't reach them — the+ # `issued_at` carried on the code is what a revoke is checked against. Codes minted+ # before `issued_at` shipped lack the field; fail closed (they expire in+ # AUTH_CODE_TTL_SECONDS and the client can re-run the flow).+ with transaction.atomic():+ locked_app = _lock_application(oauth_app.pk) if oauth_app else None+ sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None+ if sessions_revoked_at is not None:+ issued_at_raw = code_data.get("issued_at")+ issued_at = datetime.fromisoformat(issued_at_raw) if issued_at_raw else None+ if issued_at is None or issued_at < sessions_revoked_at:+ _capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="authorization_code")+ return Response(+ {"error": "invalid_grant", "error_description": "Application sessions were revoked; re-authorize."},+ status=400,+ )++ # Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope+ # ceiling has to be enforced here before the token is created by hand.+ requested_scopes = scopes if scopes else StripeIntegration.SCOPES.split()+ app_scopes = locked_app.scopes if locked_app else []+ if not scopes_within_ceiling(requested_scopes, app_scopes):+ _capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="authorization_code")+ return Response(+ {+ "error": "invalid_scope",+ "error_description": "Requested scopes exceed the application's allowed scopes",+ },+ status=400,+ )+ scope_str = " ".join(requested_scopes)- token_expiry = (- PARTNER_TOKEN_EXPIRY_SECONDS if oauth_app and oauth_app.is_provisioning_partner else ACCESS_TOKEN_EXPIRY_SECONDS- )+ token_expiry = (+ PARTNER_TOKEN_EXPIRY_SECONDS+ if oauth_app and oauth_app.is_provisioning_partner+ else ACCESS_TOKEN_EXPIRY_SECONDS+ )- access_token_value = generate_random_oauth_access_token(None)- access_token = OAuthAccessToken.objects.create(- application=oauth_app,- token=access_token_value,- user=user,- expires=timezone.now() + timedelta(seconds=token_expiry),- scope=scope_str,- scoped_teams=[team_id],- )+ access_token_value = generate_random_oauth_access_token(None)+ access_token = OAuthAccessToken.objects.create(+ application=oauth_app,+ token=access_token_value,+ user=user,+ expires=timezone.now() + timedelta(seconds=token_expiry),+ scope=scope_str,+ scoped_teams=[team_id],+ )- refresh_token_value = generate_random_oauth_refresh_token(None)- OAuthRefreshToken.objects.create(- application=oauth_app,- token=refresh_token_value,- user=user,- access_token=access_token,- scoped_teams=[team_id],- )+ refresh_token_value = generate_random_oauth_refresh_token(None)+ OAuthRefreshToken.objects.create(+ application=oauth_app,+ token=refresh_token_value,+ user=user,+ access_token=access_token,+ scoped_teams=[team_id],+ )account_id = str(code_data.get("org_id", ""))@@ -1140,70 +1171,99 @@ def _exchange_refresh_token(request: Request) -> Response:_capture_provisioning_event("token_exchange", "missing_refresh_token", grant_type="refresh_token")return Response({"error": "invalid_request", "error_description": "refresh_token is required"}, status=400)- old_refresh = find_oauth_refresh_token(refresh_token_value)- if old_refresh is None:- _capture_provisioning_event("token_exchange", "invalid_refresh_token", grant_type="refresh_token")- return Response({"error": "invalid_grant", "error_description": "Invalid or revoked refresh token"}, status=400)-- oauth_app = old_refresh.application- user = old_refresh.user- scoped_teams = old_refresh.scoped_teams- old_scope = old_refresh.access_token.scope if old_refresh.access_token else StripeIntegration.SCOPES-- # Cap the refreshed scope at the app's current ceiling before touching any- # token rows — a since-tightened ceiling must drop the removed scopes, and a- # token now fully outside the ceiling has to re-authorize rather than refresh.- # Done up front so a rejected refresh never revokes the caller's only token.- app_scopes = oauth_app.scopes if oauth_app else []- narrowed_scopes = narrow_scopes_to_ceiling(old_scope.split(), app_scopes)- if narrowed_scopes is None:- _capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="refresh_token")- return Response(- {- "error": "invalid_grant",- "error_description": "Token scopes are no longer within the application's allowed scopes; re-authorize.",- },- status=400,+ # Lock the app row first (revoke_application_sessions locks it before sweeping tokens),+ # then re-read the refresh token under that lock, so the rotate-and-mint serializes with+ # the revoke: either we hold the lock and our new tokens land before its sweep, or it+ # committed first and we see the token already revoked (or the stamp) and reject. Looking+ # the app up by id first (without locking the token row) keeps the lock order app→token,+ # matching the revoke, so the two can't deadlock.+ with transaction.atomic():+ application_id = (+ OAuthRefreshToken.objects.filter(token=refresh_token_value, revoked__isnull=True)+ .values_list("application_id", flat=True)+ .first()+ )+ locked_app = _lock_application(application_id) if application_id else None+ old_refresh = (+ OAuthRefreshToken.objects.select_related("user", "access_token")+ .filter(token=refresh_token_value, revoked__isnull=True)+ .first())- new_scope = " ".join(narrowed_scopes)+ if old_refresh is None:+ _capture_provisioning_event("token_exchange", "invalid_refresh_token", grant_type="refresh_token")+ return Response(+ {"error": "invalid_grant", "error_description": "Invalid or revoked refresh token"}, status=400+ )- # provisioning_partner_type is a stable marker set at partner registration;- # checking it instead of is_provisioning_partner prevents a bypass when an admin- # clears provisioning_auth_method to disable a partner without revoking tokens.- if oauth_app and oauth_app.provisioning_partner_type:- if error := _enforce_partner_rate_limit(oauth_app, "token_exchanges"):- return error+ oauth_app = locked_app+ user = old_refresh.user+ scoped_teams = old_refresh.scoped_teams+ old_scope = old_refresh.access_token.scope if old_refresh.access_token else StripeIntegration.SCOPES- old_access = old_refresh.access_token- old_refresh.access_token = None- old_refresh.revoked = timezone.now()- old_refresh.save(update_fields=["access_token", "revoked"])+ sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None+ if sessions_revoked_at is not None and old_refresh.created < sessions_revoked_at:+ _capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="refresh_token")+ return Response(+ {"error": "invalid_grant", "error_description": "Application sessions were revoked; re-authorize."},+ status=400,+ )- if old_access:- old_access.delete()+ # Cap the refreshed scope at the app's current ceiling before touching any+ # token rows — a since-tightened ceiling must drop the removed scopes, and a+ # token now fully outside the ceiling has to re-authorize rather than refresh.+ # Done up front so a rejected refresh never revokes the caller's only token.+ app_scopes = oauth_app.scopes if oauth_app else []+ narrowed_scopes = narrow_scopes_to_ceiling(old_scope.split(), app_scopes)+ if narrowed_scopes is None:+ _capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="refresh_token")+ return Response(+ {+ "error": "invalid_grant",+ "error_description": "Token scopes are no longer within the application's allowed scopes; re-authorize.",+ },+ status=400,+ )+ new_scope = " ".join(narrowed_scopes)- token_expiry = (- PARTNER_TOKEN_EXPIRY_SECONDS if oauth_app and oauth_app.is_provisioning_partner else ACCESS_TOKEN_EXPIRY_SECONDS- )+ # provisioning_partner_type is a stable marker set at partner registration;+ # checking it instead of is_provisioning_partner prevents a bypass when an admin+ # clears provisioning_auth_method to disable a partner without revoking tokens.+ if oauth_app and oauth_app.provisioning_partner_type:+ if error := _enforce_partner_rate_limit(oauth_app, "token_exchanges"):+ return error- new_access_value = generate_random_oauth_access_token(None)- new_access = OAuthAccessToken.objects.create(- application=oauth_app,- token=new_access_value,- user=user,- expires=timezone.now() + timedelta(seconds=token_expiry),- scope=new_scope,- scoped_teams=scoped_teams,- )+ old_access = old_refresh.access_token+ old_refresh.access_token = None+ old_refresh.revoked = timezone.now()+ old_refresh.save(update_fields=["access_token", "revoked"])- new_refresh_value = generate_random_oauth_refresh_token(None)- OAuthRefreshToken.objects.create(- application=oauth_app,- token=new_refresh_value,- user=user,- access_token=new_access,- scoped_teams=scoped_teams,- )+ if old_access:+ old_access.delete()++ token_expiry = (+ PARTNER_TOKEN_EXPIRY_SECONDS+ if oauth_app and oauth_app.is_provisioning_partner+ else ACCESS_TOKEN_EXPIRY_SECONDS+ )++ new_access_value = generate_random_oauth_access_token(None)+ new_access = OAuthAccessToken.objects.create(+ application=oauth_app,+ token=new_access_value,+ user=user,+ expires=timezone.now() + timedelta(seconds=token_expiry),+ scope=new_scope,+ scoped_teams=scoped_teams,+ )++ new_refresh_value = generate_random_oauth_refresh_token(None)+ OAuthRefreshToken.objects.create(+ application=oauth_app,+ token=new_refresh_value,+ user=user,+ access_token=new_access,+ scoped_teams=scoped_teams,+ )_capture_provisioning_event("token_exchange", "success", partner=oauth_app, grant_type="refresh_token")diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex b124a697811c..2d377181086c 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -6,13 +6,15 @@ from urllib.parse import urlencodefrom django import formsfrom django.contrib import admin+from django.contrib.admin import helpers+from django.template.response import TemplateResponsefrom django.urls import reversefrom django.utils.html import format_htmlfrom oauth2_provider.generators import generate_client_id, generate_client_secretfrom oauth2_provider.models import AbstractApplication-from posthog.models.oauth import OAuthApplication+from posthog.models.oauth import OAuthApplication, revoke_application_sessionsclass OAuthApplicationForm(forms.ModelForm):@@ -90,6 +92,26 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-nesearch_fields = ("name", "client_id", "user__email", "organization__name")autocomplete_fields = ("user", "organization")ordering = ("name",)+ actions = ("revoke_all_sessions",)++ @admin.action(description="Revoke all sessions (force re-auth under current scopes)")+ def revoke_all_sessions(self, request, queryset):+ # Irreversible and app-wide (signs out every user/connection), so gate it behind an+ # interstitial confirmation instead of firing on the first click.+ if request.POST.get("confirm"):+ count = queryset.count()+ for application in queryset:+ revoke_application_sessions(application)+ self.message_user(request, f"Revoked all sessions for {count} application(s).")+ return None+ context = {+ **self.admin_site.each_context(request),+ "title": "Revoke all sessions",+ "queryset": queryset,+ "opts": self.model._meta,+ "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,+ }+ return TemplateResponse(request, "admin/posthog/oauthapplication/revoke_all_sessions_confirm.html", context)def view_on_site(self, obj: OAuthApplication):code_verifier = "test"diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.pyindex 18a910fab10a..76af26fe21b4 100644--- a/posthog/admin/test_oauth_admin.py+++ b/posthog/admin/test_oauth_admin.py@@ -1,11 +1,17 @@+from datetime import timedelta++from freezegun import freeze_timefrom posthog.test.base import BaseTest+from unittest.mock import patchfrom django.contrib.admin import AdminSite+from django.test import RequestFactory+from django.utils import timezonefrom parameterized import parameterizedfrom posthog.admin.admins.oauth_admin import OAuthApplicationAdmin, OAuthApplicationForm-from posthog.models.oauth import OAuthApplication+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenclass TestOAuthApplicationAdmin(BaseTest):@@ -38,6 +44,59 @@ class TestOAuthApplicationAdmin(BaseTest):assert "Only used for HMAC provisioning partners" in form.fields["provisioning_signing_secret"].help_text+ @freeze_time("2026-01-01 00:00:00")+ def test_revoke_all_sessions_action_force_invalidates_tokens(self):+ app = OAuthApplication.objects.create(+ name="Revoke Action App",+ client_id="revoke_action_client_id",+ client_secret="revoke_action_client_secret",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ algorithm="RS256",+ )+ access_token = OAuthAccessToken.objects.create(+ application=app, user=self.user, token="at_revoke_action", expires=timezone.now() + timedelta(minutes=5)+ )+ OAuthRefreshToken.objects.create(+ application=app, user=self.user, token="rt_revoke_action", access_token=access_token+ )++ request = RequestFactory().post("/", {"confirm": "yes"})+ with patch.object(self.admin, "message_user") as message_user:+ self.admin.revoke_all_sessions(request=request, queryset=OAuthApplication.objects.filter(id=app.id))++ self.assertEqual(OAuthAccessToken.objects.filter(application=app).count(), 0)+ self.assertEqual(OAuthRefreshToken.objects.filter(application=app, revoked__isnull=True).count(), 0)+ message_user.assert_called_once()++ @freeze_time("2026-01-01 00:00:00")+ def test_revoke_all_sessions_without_confirm_renders_page_and_keeps_tokens(self):+ app = OAuthApplication.objects.create(+ name="Revoke Confirm App",+ client_id="revoke_confirm_client_id",+ client_secret="revoke_confirm_client_secret",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ algorithm="RS256",+ )+ OAuthAccessToken.objects.create(+ application=app, user=self.user, token="at_revoke_confirm", expires=timezone.now() + timedelta(minutes=5)+ )++ self.user.is_staff = True+ request = RequestFactory().post("/")+ request.user = self.user+ response = self.admin.revoke_all_sessions(request=request, queryset=OAuthApplication.objects.filter(id=app.id))++ self.assertEqual(response.status_code, 200)+ self.assertIn("revoke_all_sessions_confirm.html", response.template_name)+ # Nothing revoked until the operator confirms.+ self.assertEqual(OAuthAccessToken.objects.filter(application=app).count(), 1)+@parameterized.expand([("cimd_app", True, True),diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex ed30bf2a8ae9..a75dda33eab4 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -32,6 +32,7 @@ from posthog.models.oauth import (OAuthApplicationAccessLevel,OAuthGrant,OAuthRefreshToken,+ revoke_application_sessions,)from posthog.models.team.team import Team@@ -1280,18 +1281,21 @@ class TestOAuthAPI(APIBaseTest):scoped_organizations=None,)- def _refresh_and_get_scopes(self, refresh_token: OAuthRefreshToken) -> set[str]:+ def _refresh(self, refresh_token: str) -> dict:response = self.post("/oauth/token/",{"grant_type": "refresh_token",- "refresh_token": refresh_token.token,+ "refresh_token": refresh_token,"client_id": self.confidential_application.client_id,"client_secret": "test_confidential_client_secret",},)self.assertEqual(response.status_code, status.HTTP_200_OK)- new_access_token = OAuthAccessToken.objects.get(token=response.json()["access_token"])+ return response.json()++ def _refresh_and_get_scopes(self, refresh_token: OAuthRefreshToken) -> set[str]:+ new_access_token = OAuthAccessToken.objects.get(token=self._refresh(refresh_token.token)["access_token"])return set((new_access_token.scope or "").split())@parameterized.expand(@@ -1338,14 +1342,214 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["error"], "invalid_grant")- def test_refresh_leaves_wildcard_token_untouched(self):+ @freeze_time("2026-01-01 00:00:00")+ def test_refresh_racing_app_revoke_is_rejected(self):+ # A refresh validates its token in autocommit, before save_bearer_token takes the row+ # lock, so revoke_application_sessions can commit in between and the refresh would mint+ # tokens that escape the bulk revoke. The mint-time sessions_revoked_at check closes it,+ # including within the 120s refresh-token grace period that keeps a just-revoked token+ # valid through validate_refresh_token.+ refresh_token = self._create_refreshable_token_pair("openid")++ with freeze_time("2026-01-01 00:00:05"):+ revoke_application_sessions(self.confidential_application)++ 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.assertEqual(response["Content-Type"], "application/json")+ self.assertFalse(+ OAuthRefreshToken.objects.filter(application=self.confidential_application, revoked__isnull=True).exists()+ )++ @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.+ self.confidential_application.sessions_revoked_at = timezone.now()+ self.confidential_application.save()++ with freeze_time("2026-01-01 00:00:05"):+ refresh_token = self._create_refreshable_token_pair("openid")+ data = self._refresh(refresh_token.token)++ self.assertIn("access_token", data)++ def _authorize_and_get_code(self) -> str:+ response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return response.json()["redirect_to"].split("code=")[1].split("&")[0]++ def _exchange_code(self, code: str):+ return self.post("/oauth/token/", {**self.base_token_body, "code": code})++ def _assert_no_live_tokens(self) -> None:+ self.assertFalse(OAuthAccessToken.objects.filter(application=self.confidential_application).exists())+ self.assertFalse(+ OAuthRefreshToken.objects.filter(application=self.confidential_application, revoked__isnull=True).exists()+ )++ @freeze_time("2026-01-01 00:00:00")+ def test_code_exchange_racing_app_revoke_is_rejected(self):+ # The race leaves this committed state at mint time: sessions_revoked_at stamped, grant+ # predating it. Stamping without the full revoke (which also deletes the grant — covered+ # by the validate-then-revoke test below) exercises the timestamp branch.+ code = self._authorize_and_get_code()++ with freeze_time("2026-01-01 00:00:05"):+ self.confidential_application.sessions_revoked_at = timezone.now()+ self.confidential_application.save()++ response = self._exchange_code(code)++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "invalid_grant")+ self.assertEqual(response["Content-Type"], "application/json")+ self._assert_no_live_tokens()++ @freeze_time("2026-01-01 00:00:00")+ def test_code_exchange_validated_before_app_revoke_is_rejected(self):+ # oauthlib validates the grant in autocommit, before save_bearer_token's transaction, so+ # revoke_application_sessions can commit (deleting the grant and stamping) after+ # validation but before the mint. Inject the revoke right before save_bearer_token to+ # reproduce that interleaving deterministically; the mint-time check then sees the grant+ # missing with the stamp set.+ code = self._authorize_and_get_code()+ real_save_bearer_token = OAuthValidator.save_bearer_token++ def revoke_then_save(validator, token, oauth_request, *args, **kwargs):+ revoke_application_sessions(self.confidential_application)+ return real_save_bearer_token(validator, token, oauth_request, *args, **kwargs)++ with (+ freeze_time("2026-01-01 00:00:05"),+ patch.object(OAuthValidator, "save_bearer_token", revoke_then_save),+ ):+ response = self._exchange_code(code)++ 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_code_exchange_succeeds_for_grant_issued_after_revoke(self):+ # A grant created after the revoke stamp (i.e. the user re-authorized) exchanges normally.+ self.confidential_application.sessions_revoked_at = timezone.now()+ self.confidential_application.save()++ with freeze_time("2026-01-01 00:00:05"):+ code = self._authorize_and_get_code()+ response = self._exchange_code(code)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIn("access_token", response.json())++ @parameterized.expand(+ [+ ("tightened_ceiling", ["experiment:read"], "*", {"*"}),+ ("empty_ceiling", [], "*", {"*"}),+ ("wildcard_with_oidc", ["experiment:read"], "* openid", {"*", "openid"}),+ ]+ )+ def test_refresh_leaves_wildcard_token_untouched(self, _name, ceiling, token_scope, expected):+ # Wildcard narrowing is deferred to #60342: a `*` token must refresh into the+ # exact same scope set, never narrowed down (an empty scope is rejected by+ # APIScopePermission and would break the long-lived `*` CLI/MCP sessions).+ self.confidential_application.scopes = ceiling+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair(token_scope)++ self.assertEqual(self._refresh_and_get_scopes(refresh_token), expected)++ @parameterized.expand(+ [+ ("oidc_only_survives_nonoverlapping_ceiling", "openid", ["experiment:read"], {"openid"}),+ ("oidc_survives_while_resource_scope_drops", "openid insight:read", ["experiment:read"], {"openid"}),+ ]+ )+ def test_refresh_always_allowed_scopes_bypass_ceiling(self, _name, token_scope, ceiling, expected):+ # OIDC/introspection scopes are identity/token-management, not resource+ # permissions: they survive refresh even against a ceiling they don't overlap,+ # and they keep a token alive when every resource scope is narrowed away.+ self.confidential_application.scopes = ceiling+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair(token_scope)++ self.assertEqual(self._refresh_and_get_scopes(refresh_token), expected)++ def test_get_original_scopes_resolves_ceiling_from_token_when_client_missing(self):+ # oauthlib doesn't always populate `request.client` during the refresh grant,+ # so the override falls back to resolving the application (and its ceiling)+ # from the refresh-token row. Exercise that branch directly.self.confidential_application.scopes = ["experiment:read"]self.confidential_application.save()+ refresh_token = self._create_refreshable_token_pair("openid experiment:read insight:read")++ validator = OAuthValidator()+ request = SimpleNamespace(client=None)+ with patch(+ "oauth2_provider.oauth2_validators.OAuth2Validator.get_original_scopes",+ return_value="openid experiment:read insight:read",+ ):+ result = validator.get_original_scopes(refresh_token.token, request)- refresh_token = self._create_refreshable_token_pair("*")+ self.assertEqual(set(result), {"openid", "experiment:read"})- # Wildcard narrowing is deferred to #60342; the token must keep working.- self.assertIn("*", self._refresh_and_get_scopes(refresh_token))+ @freeze_time("2026-01-01 00:00:00")+ def test_narrowed_scopes_persist_across_multiple_refreshes(self):+ # After a narrowed refresh, the rotated token already carries the narrowed+ # set, so a second refresh must hold steady rather than re-broaden.+ self.confidential_application.scopes = ["experiment:read"]+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair("openid experiment:read insight:read")++ first = self._refresh(refresh_token.token)+ first_scopes = set(OAuthAccessToken.objects.get(token=first["access_token"]).scope.split())+ self.assertEqual(first_scopes, {"openid", "experiment:read"})++ second = self._refresh(first["refresh_token"])+ second_scopes = set(OAuthAccessToken.objects.get(token=second["access_token"]).scope.split())+ self.assertEqual(second_scopes, {"openid", "experiment:read"})++ @freeze_time("2026-01-01 00:00:00")+ def test_refresh_rejected_outside_ceiling_does_not_revoke_token(self):+ # The zero-overlap rejection bounces the single request without revoking the+ # token: re-widening the ceiling lets the very same refresh token work again.+ self.confidential_application.scopes = ["experiment:read"]+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair("insight:read")+ refresh_data = {+ "grant_type": "refresh_token",+ "refresh_token": refresh_token.token,+ "client_id": self.confidential_application.client_id,+ "client_secret": "test_confidential_client_secret",+ }++ rejected = self.post("/oauth/token/", refresh_data)+ self.assertEqual(rejected.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(rejected.json()["error"], "invalid_grant")++ refresh_token.refresh_from_db()+ self.assertIsNone(refresh_token.revoked)++ self.confidential_application.scopes = ["experiment:read", "insight:read"]+ self.confidential_application.save()+ retry = self.post("/oauth/token/", refresh_data)+ self.assertEqual(retry.status_code, status.HTTP_200_OK)+ retry_scopes = set(OAuthAccessToken.objects.get(token=retry.json()["access_token"]).scope.split())+ self.assertEqual(retry_scopes, {"insight:read"})def test_refresh_with_injected_code_does_not_escalate_scopes(self):"""A refresh request that includes a `code` parameter from a broader-scopediff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex f69c874c0a7d..b653247071f2 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -2,7 +2,7 @@ import jsonimport uuidimport hashlibimport calendar-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import TypedDict, castfrom urllib.parse import urlparse@@ -517,7 +517,60 @@ class OAuthValidator(OAuth2Validator):"sub": str(request.user.uuid),}+ def _sessions_revoked_at(self, application_id: int) -> datetime | None:+ return OAuthApplication.objects.filter(pk=application_id).values_list("sessions_revoked_at", flat=True).first()++ def _reject_refresh_racing_revoke(self, request, source_refresh_token):+ """Reject a refresh that races an app-wide session revoke.++ DOT validates the refresh token in autocommit, before `save_bearer_token` opens the+ transaction that locks the row, so a refresh that already passed validation can reach+ here after `revoke_application_sessions` committed. This runs inside that transaction,+ so re-reading `sessions_revoked_at` sees the committed revoke: if the presented refresh+ token predates it, the bulk revoke missed the tokens we're about to mint, so reject and+ force re-authorization. The token's own `revoked` flag can't be used here — DOT sets it+ on every rotation, so it doesn't distinguish an admin revoke from a normal refresh.+ """+ revoked_at = self._sessions_revoked_at(source_refresh_token.application_id)+ if revoked_at is not None and source_refresh_token.created < revoked_at:+ raise InvalidGrantError(+ description="Application sessions were revoked; re-authorize.",+ request=request,+ )++ def _reject_code_exchange_racing_revoke(self, request):+ """Reject an authorization-code exchange that races an app-wide session revoke.++ Same race as `_reject_refresh_racing_revoke`, on the code path: oauthlib validates the+ grant in autocommit before `save_bearer_token` opens its transaction, so the revoke can+ commit in between and the exchange would mint tokens that postdate `sessions_revoked_at`+ and survive every later refresh. Unlike the refresh path, where DOT's `select_for_update`+ on the refresh-token row serializes the mint against the revoke's bulk update, nothing+ locks the grant — so take the row lock here. If the revoke committed first, the grant is+ gone (`revoke_application_sessions` deletes grants before sweeping tokens) or predates+ the stamp; if the mint wins the lock, the revoke blocks on its grant delete and its token+ sweep re-snapshots after our commit, catching the tokens minted here.+ """+ if getattr(request, "grant_type", None) != "authorization_code":+ return+ grant_created = (+ OAuthGrant.objects.select_for_update()+ .filter(code=request.code, application=request.client)+ .values_list("created", flat=True)+ .first()+ )+ revoked_at = self._sessions_revoked_at(request.client.pk)+ if revoked_at is not None and (grant_created is None or grant_created < revoked_at):+ raise InvalidGrantError(+ description="Application sessions were revoked; re-authorize.",+ 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)+ 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)@@ -1076,6 +1129,19 @@ class OAuthTokenView(TokenView):except (json.JSONDecodeError, OAuthAccessToken.DoesNotExist) as e:logger.warning(f"Error adding scoped fields to token response: {e}")+ # An OAuth2Error raised from save_bearer_token (e.g. the mint-time app-revoke check)+ # escapes oauthlib's validate_token_request try/except and is serialized by DOT's+ # backend handler instead, which ships oauthlib's empty header dict — so the JSON+ # error body lands with Django's default text/html. Restore the RFC 6749 §5.2+ # application/json header so clients (and DRF's test client) can parse the error.+ if response.status_code != 200 and response.get("Content-Type", "").startswith("text/html"):+ try:+ json.loads(response.content)+ except (json.JSONDecodeError, ValueError):+ pass+ else:+ response["Content-Type"] = "application/json"+return responsediff --git a/posthog/migrations/1214_oauthapplication_sessions_revoked_at.py b/posthog/migrations/1214_oauthapplication_sessions_revoked_at.pynew file mode 100644index 000000000000..42a0997f52b0--- /dev/null+++ b/posthog/migrations/1214_oauthapplication_sessions_revoked_at.py@@ -0,0 +1,19 @@+# Generated by Django 5.2.14 on 2026-06-04 21:03++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1213_filesystemfolderinstructions")]++ operations = [+ migrations.AddField(+ model_name="oauthapplication",+ name="sessions_revoked_at",+ field=models.DateTimeField(+ blank=True,+ help_text="When an admin last force-revoked every session for this app. Tokens issued before this are rejected on refresh, forcing re-authorization.",+ null=True,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 16c06e1d6515..d49047e386f3 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1213_filesystemfolderinstructions+1214_oauthapplication_sessions_revoked_atdiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex a8456e6e779c..86ac329b1131 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -6,7 +6,7 @@ from django.conf import settingsfrom django.contrib.auth.signals import user_logged_outfrom django.contrib.postgres.fields import ArrayFieldfrom django.core.exceptions import ValidationError-from django.db import models+from django.db import models, transactionfrom django.dispatch import receiverfrom django.utils import timezone@@ -109,6 +109,18 @@ class OAuthApplication(AbstractApplication):help_text=("Scope ceiling — strings tokens issued for this app may carry. Empty list means no per-app cap."),)+ # Generation marker for app-wide session revocation. A refresh presenting a token issued+ # before this timestamp is rejected at mint time, so a refresh racing revoke_application_sessions+ # can't slip new tokens past the one-shot bulk revoke.+ sessions_revoked_at: models.DateTimeField = models.DateTimeField(+ null=True,+ blank=True,+ help_text=(+ "When an admin last force-revoked every session for this app. Tokens issued before this "+ "are rejected on refresh, forcing re-authorization."+ ),+ )+# CIMD (Client ID Metadata Document) fields — draft-ietf-oauth-client-id-metadata-document-00is_cimd_client: models.BooleanField = models.BooleanField(default=False,@@ -480,6 +492,34 @@ def revoke_oauth_session(OAuthGrant.objects.filter(user=user, application=application).delete()+def revoke_application_sessions(application: "OAuthApplication") -> None:+ """Force-invalidate every outstanding token and grant for an application, across all users.++ Lets a scope-ceiling narrowing take effect immediately by forcing every connection to+ re-authorize under the new ceiling, instead of waiting for each token to hit its next+ refresh (where `get_original_scopes` caps it).++ Revokes refresh tokens before deleting access tokens, all in one transaction, so a+ concurrent refresh can't mint a fresh access token in the gap and a mid-way failure+ can't leave refresh tokens live after their access tokens are already gone.++ Stamps `sessions_revoked_at` so a refresh that validated its (now-revoked) token before+ this transaction committed is rejected when it tries to mint — DOT validates the refresh+ token in autocommit, before its own transaction takes the row lock, so the bulk update+ here would otherwise miss the tokens that racing refresh is about to create.++ Grants are deleted before the token sweep: a racing code exchange locks its grant row at+ mint (`_reject_code_exchange_racing_revoke`), so deleting grants first makes this+ transaction block on that lock and re-snapshot the token sweep after the mint commits.+ Sweeping tokens first would let the racing mint's tokens escape the sweep."""+ now = timezone.now()+ with transaction.atomic():+ OAuthApplication.objects.filter(pk=application.pk).update(sessions_revoked_at=now)+ OAuthGrant.objects.filter(application=application).delete()+ OAuthRefreshToken.objects.filter(application=application, revoked__isnull=True).update(revoked=now)+ OAuthAccessToken.objects.filter(application=application).delete()++def generate_random_token_cimd_verification() -> str:return "phvt_" + generate_random_token()diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.pyindex 44a016f592cb..092c8a15b432 100644--- a/posthog/models/test/test_oauth.py+++ b/posthog/models/test/test_oauth.py@@ -18,6 +18,7 @@ from posthog.models.oauth import (OAuthGrant,OAuthIDToken,OAuthRefreshToken,+ revoke_application_sessions,revoke_oauth_session,)@@ -639,3 +640,48 @@ class TestOAuthModels(TestCase):revoke_oauth_session(access_token=access_token)self.assertFalse(OAuthAccessToken.objects.filter(id=token_id).exists())++ @freeze_time("2026-01-01 00:00:00")+ def test_revoke_application_sessions_revokes_across_all_users_and_leaves_other_apps(self):+ app = self._make_app("Narrowed App", "narrowed_client_id")+ other_app = self._make_app("Other App", "other_client_id")+ other_user = User.objects.create(email="[email protected]")++ for owner, suffix in [(self.user, "a"), (other_user, "b")]:+ access_token = OAuthAccessToken.objects.create(+ application=app, user=owner, token=f"at_{suffix}", expires=timezone.now() + timedelta(minutes=5)+ )+ OAuthRefreshToken.objects.create(+ application=app, user=owner, token=f"rt_{suffix}", access_token=access_token+ )+ OAuthGrant.objects.create(+ application=app,+ user=owner,+ code=f"grant_{suffix}",+ code_challenge="challenge",+ code_challenge_method="S256",+ expires=timezone.now() + timedelta(minutes=5),+ )++ survivor = OAuthAccessToken.objects.create(+ application=other_app, user=self.user, token="at_survivor", expires=timezone.now() + timedelta(minutes=5)+ )++ revoke_application_sessions(app)++ self.assertEqual(OAuthAccessToken.objects.filter(application=app).count(), 0)+ self.assertEqual(OAuthGrant.objects.filter(application=app).count(), 0)+ self.assertEqual(OAuthRefreshToken.objects.filter(application=app, revoked__isnull=True).count(), 0)+ self.assertTrue(OAuthAccessToken.objects.filter(id=survivor.id).exists())++ @freeze_time("2026-01-01 00:00:00")+ def test_revoke_application_sessions_stamps_sessions_revoked_at(self):+ app = self._make_app("Stamped App", "stamped_client_id")+ other_app = self._make_app("Untouched App", "untouched_client_id")++ revoke_application_sessions(app)++ app.refresh_from_db()+ other_app.refresh_from_db()+ self.assertEqual(app.sessions_revoked_at, timezone.now())+ self.assertIsNone(other_app.sessions_revoked_at)diff --git a/posthog/templates/admin/posthog/oauthapplication/revoke_all_sessions_confirm.html b/posthog/templates/admin/posthog/oauthapplication/revoke_all_sessions_confirm.htmlnew file mode 100644index 000000000000..f560facb7a9b--- /dev/null+++ b/posthog/templates/admin/posthog/oauthapplication/revoke_all_sessions_confirm.html@@ -0,0 +1,31 @@+{% extends "admin/base_site.html" %}+{% load i18n l10n admin_urls %}++{% block breadcrumbs %}+<div class="breadcrumbs">+ <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a>+ › <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>+ › <a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>+ › {% translate 'Revoke all sessions' %}+</div>+{% endblock %}++{% block content %}+<p>Revoking all sessions immediately signs out <strong>every connection across all users</strong> (CLI, MCP, and partner integrations) for the selected applications and forces each one to re-authorize under the current scope ceiling. This cannot be undone.</p>++<p>Are you sure you want to revoke all sessions for the following {{ queryset|length }} application(s)?</p>++<ul>+ {% for obj in queryset %}<li>{{ obj }}</li>{% endfor %}+</ul>++<form method="post">{% csrf_token %}+ {% for obj in queryset %}+ <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}">+ {% endfor %}+ <input type="hidden" name="action" value="revoke_all_sessions">+ <input type="hidden" name="confirm" value="yes">+ <input type="submit" value="Yes, revoke all sessions" class="default">+ <a href="{% url opts|admin_urlname:'changelist' %}" class="button cancel-link">Cancel</a>+</form>+{% endblock %}