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): gate introspection on confidential clients (#74436)

Tom Piccirello850a37e4918b
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index b7450dd7efc0..6c84477efe53 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -3296,6 +3296,31 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response_data["error"], "invalid_request")
self.assertIn("Invalid JSON", response_data["error_description"])
+ @parameterized.expand(
+ [
+ ("array", "[]"),
+ ("null", "null"),
+ ("string", '"authorization_code"'),
+ ("number", "1"),
+ ("non_string_value", '{"grant_type": "authorization_code", "client_id": {"nested": "object"}}'),
+ ]
+ )
+ def test_token_endpoint_rejects_json_payloads_that_are_not_string_objects(self, _name: str, body: str):
+ response = self.client.post("/oauth/token/", data=body, content_type="application/json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "invalid_request")
+
+ def test_token_endpoint_rejects_deeply_nested_json_payload(self):
+ # json.loads raises RecursionError, not JSONDecodeError, once nesting exceeds the
+ # interpreter's recursion limit -- a second parser failure mode the shape guard above
+ # must also turn into a 400 rather than an unhandled 500.
+ body = '{"a":' + "[" * 10000 + "]" * 10000 + "}"
+ response = self.client.post("/oauth/token/", data=body, content_type="application/json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "invalid_request")
+
def _create_access_and_refresh_tokens(self, scopes: str = "openid") -> tuple[OAuthAccessToken, OAuthRefreshToken]:
response = self.client.post(
"/oauth/authorize/",
@@ -3372,6 +3397,40 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["token_type"], "refresh_token")
self.assertNotIn("scope", data)
+ @parameterized.expand(["access_token", "refresh_token"])
+ def test_introspection_with_client_credentials_rejects_a_different_clients_token(self, token_type):
+ # Client credentials prove who is asking, not which token they may see. Being a
+ # confidential client is cheap -- /oauth/register/ mints one to anyone -- so the
+ # response must be bound to the authenticated client's own tokens.
+ other_confidential_app = OAuthApplication.objects.create(
+ name="Other Confidential App",
+ client_id="other_confidential_client_id",
+ client_secret="other_confidential_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",
+ )
+
+ access_token, refresh_token = self._create_access_and_refresh_tokens()
+ token = access_token if token_type == "access_token" else refresh_token
+
+ response = self.post(
+ "/oauth/introspect/",
+ {
+ "token": token.token,
+ "client_id": other_confidential_app.client_id,
+ "client_secret": "other_confidential_client_secret",
+ },
+ )
+
+ 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_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()
@@ -3425,6 +3484,36 @@ class TestOAuthAPI(APIBaseTest):
self.assertFalse(data["active"])
self.assertEqual(len(data), 1)
+ def test_introspection_self_check_with_deeply_nested_json_body_does_not_500(self):
+ # _is_self_introspection parses the body before any token is validated, with the
+ # same except clause the token endpoint's shape guard has -- and the same missing
+ # RecursionError case.
+ body = '{"a":' + "[" * 10000 + "]" * 10000 + "}"
+ response = self.client.post(
+ "/oauth/introspect/",
+ data=body,
+ content_type="application/json",
+ headers={"Authorization": "Bearer whatever"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_introspection_post_with_deeply_nested_json_body_does_not_500(self):
+ authorization_header = self.get_basic_auth_header(
+ "test_confidential_client_id", "test_confidential_client_secret"
+ )
+ body = '{"a":' + "[" * 10000 + "]" * 10000 + "}"
+
+ response = self.client.post(
+ "/oauth/introspect/",
+ data=body,
+ content_type="application/json",
+ headers={"Authorization": authorization_header},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertFalse(response.json()["active"])
+
def test_introspection_without_authentication_fails(self):
access_token, _ = self._create_access_and_refresh_tokens()
@@ -3432,6 +3521,28 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ @parameterized.expand(["request_body", "http_basic"])
+ def test_introspection_rejects_a_public_client_claiming_the_device_code_grant(self, transport: str):
+ # oauth2_provider's `_authenticate_basic_auth` and `_authenticate_request_body` each
+ # return True for a public client presenting this grant type before either one reaches
+ # `_check_secret`, so the blank-secret guard in `verify_client_secret` never sees it.
+ access_token, _ = self._create_access_and_refresh_tokens()
+
+ body = {
+ "token": access_token.token,
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ }
+ headers = None
+
+ if transport == "request_body":
+ body["client_id"] = self.public_application.client_id
+ else:
+ headers = {"Authorization": self.get_basic_auth_header(self.public_application.client_id, "wrong-secret")}
+
+ response = self.post("/oauth/introspect/", body, headers=headers)
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
def test_introspection_with_wrong_client_credentials_fails(self):
access_token, _ = self._create_access_and_refresh_tokens()
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 3192a3f4aaca..4bb60dc7de5a 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -20,6 +20,7 @@ import posthoganalytics
from oauth2_provider.compat import login_not_required
from oauth2_provider.exceptions import FatalClientError, OAuthToolkitError
from oauth2_provider.http import OAuth2ResponseRedirect
+from oauth2_provider.models import AbstractApplication
from oauth2_provider.oauth2_validators import OAuth2Validator
from oauth2_provider.settings import oauth2_settings
from oauth2_provider.views import (
@@ -55,7 +56,7 @@ from posthog.api.oauth.client_assertion import (
resolve_client_assertion,
verify_client_assertion,
)
-from posthog.api.oauth.client_auth import verify_client_secret
+from posthog.api.oauth.client_auth import client_credentials_from_basic_auth, verify_client_secret
from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
from posthog.middleware import is_read_only_impersonation
@@ -1707,16 +1708,36 @@ class OAuthTokenView(TokenView):
if request.content_type == "application/json" and request.body:
try:
json_data = json.loads(request.body)
- request.POST = request.POST.copy()
- for key, value in json_data.items():
- request.POST[key] = value
- except (json.JSONDecodeError, ValueError):
+ except (json.JSONDecodeError, ValueError, RecursionError):
self._capture_token_rejected("unknown", "", "invalid_request")
return JsonResponse(
{"error": "invalid_request", "error_description": "Invalid JSON payload"},
status=400,
)
+ if not isinstance(json_data, dict):
+ return JsonResponse(
+ {"error": "invalid_request", "error_description": "JSON payload must be an object"},
+ status=400,
+ )
+
+ # Everything downstream (oauthlib, our own logging) treats these as form
+ # parameters, so anything that isn't a scalar is rejected here rather than
+ # left to blow up as a string operation on a dict or a list.
+ request.POST = request.POST.copy()
+ for key, value in json_data.items():
+ if value is None:
+ continue
+ if isinstance(value, dict | list):
+ return JsonResponse(
+ {
+ "error": "invalid_request",
+ "error_description": f"Parameter '{key}' must be a string",
+ },
+ status=400,
+ )
+ request.POST[str(key)] = str(value)
+
grant_type = request.POST.get("grant_type", "unknown")
if grant_type == id_jag.JWT_BEARER_GRANT_TYPE:
@@ -1860,6 +1881,27 @@ class OAuthRevokeTokenView(RevokeTokenView):
pass
+class ConfidentialClientOnlyOAuthValidator(OAuthValidator):
+ """Client-credentials gate that only a confidential client can pass.
+
+ A public client holds no secret to prove, so it must never satisfy an endpoint whose
+ only authentication is client credentials. The library does let it: both
+ `_authenticate_basic_auth` and `_authenticate_request_body` return True for a public
+ client whose request carries `grant_type=urn:ietf:params:oauth:grant-type:device_code`,
+ and they do so before reaching `_check_secret`, so the blank-secret guard in
+ `verify_client_secret` never runs on that path. `grant_type` is read from the request
+ body, so the application's own configured grant does not constrain it.
+
+ Kept separate from `OAuthValidator` because the token endpoint legitimately tolerates a
+ public client presenting a secret it then ignores (the grant is bound by PKCE instead).
+ """
+
+ def authenticate_client(self, request, *args, **kwargs):
+ if not super().authenticate_client(request, *args, **kwargs):
+ return False
+ return getattr(request.client, "client_type", None) == AbstractApplication.CLIENT_CONFIDENTIAL
+
+
@method_decorator(csrf_exempt, name="dispatch")
@method_decorator(login_not_required, name="dispatch")
class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
@@ -1869,7 +1911,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
To access this view the request must pass a OAuth2 Bearer Token
which is allowed to access the scope `introspection`. Alternatively,
- if the client_id and client_secret are provided, the request is
+ if a confidential client's client_id and client_secret are provided, the request is
authenticated using client credentials and does not require the `introspection` scope.
Self-introspection: An access token can always introspect itself without
@@ -1879,6 +1921,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
"""
required_scopes = ["introspection"]
+ validator_class = ConfidentialClientOnlyOAuthValidator
def _is_self_introspection(self, request) -> bool:
"""
@@ -1899,7 +1942,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
if not token_to_introspect and request.content_type == "application/json" and request.body:
try:
token_to_introspect = json.loads(request.body).get("token")
- except (json.JSONDecodeError, ValueError):
+ except (json.JSONDecodeError, ValueError, RecursionError):
pass
return bool(bearer_token and token_to_introspect and bearer_token == token_to_introspect)
@@ -1923,8 +1966,25 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
return True, request
return super().verify_request(request)
- @staticmethod
- def get_token_response(token_value=None):
+ def _client_credentials_client_id(self, request) -> str | None:
+ """The client_id that authenticated this request 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.
+ """
+ if hasattr(request, "resource_owner"):
+ return None
+
+ credentials = client_credentials_from_basic_auth(request)
+ if credentials is not None:
+ return credentials[0]
+ return request.POST.get("client_id") or None
+
+ def get_token_response(self, request, token_value=None):
"""
RFC 7662 Token Introspection response.
@@ -1939,6 +1999,8 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
if not token_value:
return JsonResponse({"active": False}, status=200)
+ credential_client_id = self._client_credentials_client_id(request)
+
# Try access token first (indexed lookup via token_checksum)
token_checksum = hashlib.sha256(token_value.encode("utf-8")).hexdigest()
try:
@@ -1947,6 +2009,11 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
access_token = None
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:
+ 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)
@@ -1971,6 +2038,8 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
refresh_token = None
if refresh_token:
+ if credential_client_id and getattr(refresh_token.application, "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
data = {
@@ -1991,7 +2060,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
Get the token from the URL parameters.
URL: https://example.com/introspect?token=mF_9.B5f-4.1JqM
"""
- return self.get_token_response(request.GET.get("token", None))
+ return self.get_token_response(request, request.GET.get("token", None))
def post(self, request, *args, **kwargs):
"""
@@ -2004,9 +2073,9 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
try:
json_data = json.loads(request.body)
token = json_data.get("token")
- except (json.JSONDecodeError, ValueError):
+ except (json.JSONDecodeError, ValueError, RecursionError):
pass
- return self.get_token_response(token)
+ return self.get_token_response(request, token)
class OAuthConnectDiscoveryInfoView(ConnectDiscoveryInfoView):
diff --git a/posthog/management/commands/generate_stripe_app_tokens.py b/posthog/management/commands/generate_stripe_app_tokens.py
index 5ea80134ca25..64e5649230e8 100644
--- a/posthog/management/commands/generate_stripe_app_tokens.py
+++ b/posthog/management/commands/generate_stripe_app_tokens.py
@@ -17,6 +17,7 @@ from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone as tz
+from oauth2_provider.generators import generate_client_secret
from oauthlib.common import generate_token
from posthog.models import Team, User
@@ -178,10 +179,12 @@ class Command(BaseCommand):
# Create a new OAuthApplication
self.stdout.write("No OAuthApplication found for the Stripe App, creating one...")
new_client_id = generate_token()
+ # The row stores only a hash of this, so it is printed once and never recoverable.
+ new_client_secret = generate_client_secret()
oauth_app = OAuthApplication.objects.create(
name=STRIPE_APP_NAME,
client_id=new_client_id,
- client_secret="",
+ client_secret=new_client_secret,
client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="https://localhost",
@@ -190,6 +193,9 @@ class Command(BaseCommand):
self.stdout.write(
self.style.SUCCESS(f"Created OAuthApplication '{STRIPE_APP_NAME}' (client_id={new_client_id})")
)
+ self.stdout.write(
+ self.style.WARNING(f"Save this client secret now, it is not shown again: {new_client_secret}")
+ )
self._write_client_id_to_env(new_client_id)
return oauth_app