: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
fix(oauth): scope bearer token introspection to the caller (#93807)
Tom Piccirello2908e0dbad00
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.mdindex 030968c1901a..57caaf4d7227 100644--- a/docs/published/handbook/engineering/oauth-development-guide.md+++ b/docs/published/handbook/engineering/oauth-development-guide.md@@ -371,7 +371,7 @@ curl -X POST http://localhost:8010/oauth/introspect/ \- **Client Authentication (HTTP Basic or Credentials)**: No scope required- **Bearer Token Authentication**: Requires `introspection` scope-This means you can introspect any token using your application's client credentials, regardless of what scopes the token being introspected has. However, if you want to use an access token to introspect other tokens, that access token must have been granted the `introspection` scope.+You only see tokens that belong to your own application, whichever method you use. The `introspection` scope lets an access token introspect other tokens from the same application. A token can always introspect itself, with or without the scope.### Response Formatdiff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 4a4a54dc3411..67d414b0fe87 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -3755,6 +3755,38 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(data["token_type"], "refresh_token")self.assertNotIn("scope", data)+ @parameterized.expand(["access_token", "refresh_token"])+ def test_introspection_with_bearer_token_rejects_a_different_applications_token(self, token_type):+ # The `introspection` scope says the caller may introspect, not whose tokens it may+ # read. Any self-registered client can obtain the scope, so without an ownership+ # check the bearer path reads back every other application's tokens.+ caller_token, _ = self._create_access_and_refresh_tokens(scopes="openid introspection")++ other_app = OAuthApplication.objects.create(+ name="Other Bearer App",+ client_id="other_bearer_client_id",+ client_secret="other_bearer_client_secret",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://other.example.com/callback",+ user=self.user,+ hash_client_secret=True,+ algorithm="RS256",+ )+ other_access_token, other_refresh_token = self._create_token_pair_for_app(other_app)+ token = other_access_token if token_type == "access_token" else other_refresh_token++ response = self.post(+ "/oauth/introspect/",+ {"token": token.token},+ headers={"Authorization": f"Bearer {caller_token.token}"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertFalse(data["active"])+ self.assertEqual(len(data), 1)+def test_introspection_with_invalid_token(self):authorization_header = self.get_basic_auth_header("test_confidential_client_id", "test_confidential_client_secret"diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex de439a50ca99..075a104afff6 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -1997,6 +1997,9 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):if a confidential client's client_id and client_secret are provided, the request isauthenticated using client credentials and does not require the `introspection` scope.+ Either way a caller only sees tokens issued to its own application. The scope+ grants the capability; it does not widen which tokens the capability reaches.+Self-introspection: An access token can always introspect itself withoutrequiring the `introspection` scope. This allows MCP clients to discovertheir own token's scopes and permissions during initialization. Refresh@@ -2043,11 +2046,15 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):bearer_token = request.headers.get("Authorization", "")[7:]token_checksum = hashlib.sha256(bearer_token.encode("utf-8")).hexdigest()try:- OAuthAccessToken.objects.get(token_checksum=token_checksum)+ request.oauth_caller_access_token = OAuthAccessToken.objects.get(token_checksum=token_checksum)except OAuthAccessToken.DoesNotExist:return False, requestreturn True, request- return super().verify_request(request)++ valid, oauth_request = super().verify_request(request)+ if valid:+ request.oauth_caller_access_token = getattr(oauth_request, "access_token", None)+ return valid, oauth_requestdef authenticate_client(self, request):"""Authenticate the client and record which application was verified.@@ -2100,14 +2107,24 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):credential_client_id = self._client_credentials_client_id(request)- # The bearer path (self-introspection or the `introspection` scope) is governed by- # scope, not by client identity, and never reaches here. On the client-credentials- # path, treating an unidentifiable caller as exempt from the ownership check below- # would be indistinguishable from disclosing any token to anyone.+ # The bearer path identifies its caller through `oauth_caller_access_token` below and+ # never reaches here. On the client-credentials path, treating an unidentifiable caller+ # as exempt from the ownership check below would be indistinguishable from disclosing+ # any token to anyone.is_client_credentials = not hasattr(request, "resource_owner")if is_client_credentials and credential_client_id is None:return JsonResponse({"active": False}, status=200)+ # The bearer caller is identified by the application its own token belongs to. The+ # `introspection` scope says a caller may introspect, not whose tokens it may read,+ # and `/oauth/register/` hands the scope to anyone, so the scope alone would let one+ # client read back every other client's tokens.+ caller_token = None+ if not is_client_credentials:+ caller_token = getattr(request, "oauth_caller_access_token", None)+ if caller_token is None:+ return JsonResponse({"active": False}, status=200)+# Try access token first (indexed lookup via token_checksum)token_checksum = hashlib.sha256(token_value.encode("utf-8")).hexdigest()try:@@ -2121,6 +2138,17 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):# issues a confidential client_id and secret to anyone who asks.if credential_client_id and getattr(access_token.application, "client_id", None) != credential_client_id:return JsonResponse({"active": False}, status=200)+ # `application_id` is nullable, so the primary-key match is what keeps the+ # self-introspection carve-out in verify_request working for a token that+ # carries no application.+ if caller_token is not None and not (+ access_token.pk == caller_token.pk+ or (+ caller_token.application_id is not None+ and access_token.application_id == caller_token.application_id+ )+ ):+ return JsonResponse({"active": False}, status=200)# RFC 7662 Section 2.2: expired tokens MUST return {"active": false}if not access_token.is_valid():return JsonResponse({"active": False}, status=200)@@ -2153,6 +2181,12 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):if refresh_token:if credential_client_id and getattr(refresh_token.application, "client_id", None) != credential_client_id:return JsonResponse({"active": False}, status=200)+ # A refresh token is never the caller: it cannot be presented as a Bearer+ # credential, so it has no self-introspection case to preserve.+ if caller_token is not None and (+ caller_token.application_id is None or refresh_token.application_id != caller_token.application_id+ ):+ return JsonResponse({"active": False}, status=200)if not refresh_token.user.is_active:return JsonResponse({"active": False}, status=200)# Refresh tokens lack scope and exp fields on AbstractRefreshToken,