: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 client-credentials token introspection to the caller (#82258)
Matt Brooker51cf3cbb9f09
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex eb8010df3230..db6b37a422e3 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -3603,6 +3603,130 @@ class TestOAuthAPI(APIBaseTest):self.assertFalse(data["active"])self.assertEqual(len(data), 1)+ @parameterized.expand(["access_token", "refresh_token"])+ @override_settings(SITE_URL="https://us.posthog.com")+ def test_introspection_ignores_a_spoofed_basic_auth_header(self, token_type):+ # Assertion auth short-circuits before the Basic header is ever validated, so a caller+ # can authenticate as itself with a signed assertion while stapling a Basic header+ # naming another client. The ownership check must bind to the verified assertion+ # identity, not the unverified header, or the caller reads that other client's token.+ access_token, refresh_token = self._create_access_and_refresh_tokens()+ token = access_token if token_type == "access_token" else refresh_token++ app, _grant, private_key = self._create_private_key_jwt_app_and_grant()+ assertion, jwks = self._signed_assertion_and_jwks(app, private_key)++ with (+ patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document",+ return_value=(jwks, None),+ ),+ patch("posthog.api.oauth.views.enqueue_cimd_refresh_if_stale"),+ ):+ response = self.post(+ "/oauth/introspect/",+ {+ "token": token.token,+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ "client_assertion": assertion,+ },+ headers={"Authorization": self.get_basic_auth_header("test_confidential_client_id", "anything")},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertFalse(data["active"])+ self.assertEqual(len(data), 1)++ def _create_token_pair_for_app(+ self, app: OAuthApplication, *, scope: str = "openid"+ ) -> tuple[OAuthAccessToken, OAuthRefreshToken]:+ access_token = OAuthAccessToken.objects.create(+ application=app,+ user=self.user,+ token=f"at_{app.id}",+ expires=timezone.now() + timedelta(hours=1),+ scope=scope,+ scoped_teams=[],+ scoped_organizations=[str(self.organization.id)],+ )+ refresh_token = OAuthRefreshToken.objects.create(+ application=app,+ user=self.user,+ token=f"rt_{app.id}",+ access_token=access_token,+ scoped_teams=[],+ scoped_organizations=[str(self.organization.id)],+ )+ return access_token, refresh_token++ @parameterized.expand(["access_token", "refresh_token"])+ @override_settings(SITE_URL="https://us.posthog.com")+ def test_introspection_with_client_assertion_rejects_a_different_clients_token(self, token_type):+ # A private_key_jwt CIMD client carries its identity in the assertion's `sub`, not in+ # HTTP Basic auth or a `client_id` form field. The ownership check must still bind to+ # that identity, or an assertion-authenticated caller can introspect any client's token.+ access_token, refresh_token = self._create_access_and_refresh_tokens()+ token = access_token if token_type == "access_token" else refresh_token++ app, _grant, private_key = self._create_private_key_jwt_app_and_grant()+ assertion, jwks = self._signed_assertion_and_jwks(app, private_key)++ with (+ patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document",+ return_value=(jwks, None),+ ),+ patch("posthog.api.oauth.views.enqueue_cimd_refresh_if_stale"),+ ):+ response = self.post(+ "/oauth/introspect/",+ {+ "token": token.token,+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ "client_assertion": assertion,+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertFalse(data["active"])+ self.assertEqual(len(data), 1)++ @parameterized.expand(["access_token", "refresh_token"])+ @override_settings(SITE_URL="https://us.posthog.com")+ def test_introspection_with_client_assertion_allows_own_token(self, token_type):+ # A CIMD client's wire identity is its cimd_metadata_url (effective_client_id), not+ # the opaque client_id PostHog assigns at registration. Comparing against the opaque+ # value would reject a CIMD client introspecting even its own token.+ app, _grant, private_key = self._create_private_key_jwt_app_and_grant()+ access_token, refresh_token = self._create_token_pair_for_app(app)+ token = access_token if token_type == "access_token" else refresh_token++ assertion, jwks = self._signed_assertion_and_jwks(app, private_key)++ with (+ patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document",+ return_value=(jwks, None),+ ),+ patch("posthog.api.oauth.views.enqueue_cimd_refresh_if_stale"),+ ):+ response = self.post(+ "/oauth/introspect/",+ {+ "token": token.token,+ "client_id": app.cimd_metadata_url,+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ "client_assertion": assertion,+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertTrue(data["active"])+ self.assertEqual(data["client_id"], app.client_id)+def test_introspection_with_bearer_token_requires_introspection_scope(self):access_token, _ = self._create_access_and_refresh_tokens(scopes="openid")token_to_introspect, _ = self._create_access_and_refresh_tokens()diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 437fe4516e83..9e9a6d1b4e13 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -32,6 +32,7 @@ from oauth2_provider.views import (UserInfoView,)from oauth2_provider.views.mixins import OAuthLibMixin+from oauthlib.common import Request as OauthlibRequestfrom oauthlib.oauth2 import InvalidGrantErrorfrom redis.exceptions import RedisErrorfrom rest_framework import serializers, status@@ -57,7 +58,7 @@ from posthog.api.oauth.client_assertion import (resolve_client_assertion,verify_client_assertion,)-from posthog.api.oauth.client_auth import client_credentials_from_basic_auth, verify_client_secret+from posthog.api.oauth.client_auth import verify_client_secretfrom posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_contextfrom posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_sessionfrom posthog.middleware import is_read_only_impersonation@@ -2061,23 +2062,39 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):return True, requestreturn super().verify_request(request)+ def authenticate_client(self, request):+ """Authenticate the client and record which application was verified.++ The base mixin returns only a bool and discards the oauthlib request that holds the+ verified ``client``, so the ownership check would otherwise have to re-derive the+ caller's identity from request fields. Those fields lie: an ``Authorization: Basic``+ header or a ``client_id`` body param can name any client without proving anything,+ while authentication may have succeeded through an entirely different credential. The+ only trustworthy identity is the one the validator bound to the request during+ verification, so capture it here for get_token_response to read back.+ """+ core = self.get_oauthlib_core()+ uri, http_method, body, headers = core._extract_params(request)+ oauth_request = OauthlibRequest(uri, http_method, body, headers)+ if not core.server.request_validator.authenticate_client(oauth_request):+ return False+ request.oauth_authenticated_client = oauth_request.client+ return True+def _client_credentials_client_id(self, request) -> str | None:- """The client_id that authenticated this request via client credentials, or None.+ """The effective_client_id the server verified via client credentials, or None.None means the request reached us through the bearer-token path instead (self-- introspection or the `introspection` scope): ClientProtectedResourceMixin.dispatch- only sets `resource_owner` on that path, since a successful `authenticate_client`- (the client-credentials path) skips it entirely. The client_id is read back rather- than re-verified, because dispatch already proved this request holds a valid secret- for it.+ introspection or the `introspection` scope), where ClientProtectedResourceMixin.dispatch+ sets `resource_owner` rather than authenticating a client. On the client-credentials+ path the identity comes only from the application the validator actually verified (see+ authenticate_client), never from unverified request headers or body params."""if hasattr(request, "resource_owner"):return None- credentials = client_credentials_from_basic_auth(request)- if credentials is not None:- return credentials.client_id- return request.POST.get("client_id") or None+ client = getattr(request, "oauth_authenticated_client", None)+ return client.effective_client_id if client is not None else Nonedef get_token_response(self, request, token_value=None):"""@@ -2096,6 +2113,14 @@ 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.+ is_client_credentials = not hasattr(request, "resource_owner")+ if is_client_credentials and credential_client_id 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:@@ -2106,8 +2131,13 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):if access_token:# A client-credentials caller may only introspect its own tokens. Being# confidential is not a meaningful barrier on its own, since /oauth/register/- # 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:+ # issues a confidential client_id and secret to anyone who asks. Compared against+ # effective_client_id, not client_id, since a CIMD client's wire identity is its+ # metadata URL, never the opaque client_id column.+ if (+ credential_client_id+ and getattr(access_token.application, "effective_client_id", None) != credential_client_id+ ):return JsonResponse({"active": False}, status=200)# RFC 7662 Section 2.2: expired tokens MUST return {"active": false}if not access_token.is_valid():@@ -2133,7 +2163,10 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):refresh_token = Noneif refresh_token:- if credential_client_id and getattr(refresh_token.application, "client_id", None) != credential_client_id:+ if (+ credential_client_id+ and getattr(refresh_token.application, "effective_client_id", None) != credential_client_id+ ):return JsonResponse({"active": False}, status=200)# Refresh tokens lack scope and exp fields on AbstractRefreshToken,# so we only return the fields that are available