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): accept private_key_jwt at the standard token endpoint (#80081)

posthog[bot]84cbbfedfdc3
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 343f053ca369..05c02eadefcf 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -57,6 +57,8 @@ CapturePhEvent = Callable[..., object]
# Limits per the CIMD specification
CIMD_MAX_DOCUMENT_SIZE = 5 * 1024 # 5KB
CIMD_FETCH_TIMEOUT_SECONDS = 5
+# Sized past the refresh task's 30s time_limit, so the sentinel outlives any task it gates.
+CIMD_REFRESH_PENDING_TTL_SECONDS = 60
# Cache TTL bounds (seconds)
CIMD_CACHE_DEFAULT_TTL = 3600 # 1 hour
@@ -915,8 +917,14 @@ def enqueue_cimd_refresh_if_stale(url: str) -> None:
provisioning auth path) so document changes are picked up on the same TTL, instead
of freezing the app's scopes and config at first registration.
"""
- if not cache.get(_cache_key(url)):
- refresh_cimd_metadata_task.delay(url)
+ if cache.get(_cache_key(url)):
+ return
+ # One pending refresh per URL: staleness is checked before any client authentication,
+ # so without this an unauthenticated burst against a public client_id would enqueue a
+ # task per request, each repeating the outbound fetch and database upsert.
+ if not cache.add(f"{_cache_key(url)}:refresh-pending", True, timeout=CIMD_REFRESH_PENDING_TTL_SECONDS):
+ return
+ refresh_cimd_metadata_task.delay(url)
def get_application_by_client_id(client_id: str) -> OAuthApplication:
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 80ce18249882..041d2490b782 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -45,6 +45,10 @@ JWKS_CACHE_TTL_SECONDS = 3600
# Short negative TTL so a client that has just fixed a broken JWKS isn't locked out for an
# hour, while a persistently broken one still can't trigger a fetch per request.
JWKS_NEGATIVE_CACHE_TTL_SECONDS = 60
+# A rotated key legitimately shows up as unknown until the cached JWKS expires, so one
+# forced re-fetch is allowed per interval. The bound keeps assertions naming bogus kids from
+# turning every exchange into an outbound fetch.
+JWKS_ROTATION_REFRESH_MIN_INTERVAL_SECONDS = 60
JWKS_MAX_DOCUMENT_SIZE = 16 * 1024
JWKS_MAX_KEYS = 10
@@ -55,6 +59,10 @@ class ClientAssertionError(Exception):
"""The assertion is missing, malformed, or does not verify. The message is wire-safe."""
+class UnknownSigningKeyError(ClientAssertionError):
+ """The assertion names a ``kid`` that the client's cached key set does not contain."""
+
+
def _request_field(request: Any, name: str) -> str:
"""Read a field from the request body, falling back to the query string.
@@ -76,16 +84,28 @@ def extract_client_assertion(request: Any) -> tuple[str, str] | None:
``client_id`` is optional on the wire for this method (RFC 7521 section 4.2 allows the
assertion to carry the identity), so it falls back to the assertion's own ``sub``.
"""
- assertion = _request_field(request, "client_assertion")
- assertion_type = _request_field(request, "client_assertion_type")
+ return resolve_client_assertion(
+ _request_field(request, "client_assertion"),
+ _request_field(request, "client_assertion_type"),
+ _request_field(request, "client_id"),
+ )
+
+
+def resolve_client_assertion(assertion: str, assertion_type: str, client_id: str) -> tuple[str, str] | None:
+ """Return the ``(client_assertion, client_id)`` from raw field values, or None.
+
+ Kept separate from ``extract_client_assertion`` so the oauthlib-backed token endpoint,
+ whose request object exposes these fields as plain attributes rather than through the DRF
+ ``request.data`` interface, can share the same resolution and ``sub`` fallback.
+ """
if not assertion or assertion_type != CLIENT_ASSERTION_TYPE_JWT_BEARER:
return None
- client_id = _request_field(request, "client_id") or _unverified_subject(assertion)
- if not client_id:
+ resolved_client_id = client_id or _unverified_subject(assertion)
+ if not resolved_client_id:
return None
- return assertion, client_id
+ return assertion, resolved_client_id
def _unverified_subject(assertion: str) -> str:
@@ -196,13 +216,35 @@ def _select_key(key_set: PyJWKSet, assertion: str) -> PyJWK:
try:
return key_set[kid]
except KeyError as e:
- raise ClientAssertionError("Client assertion is signed by an unknown key") from e
+ raise UnknownSigningKeyError("Client assertion is signed by an unknown key") from e
if len(key_set.keys) == 1:
return key_set.keys[0]
raise ClientAssertionError("Client assertion must carry a kid when the JWKS holds several keys")
+def _select_key_allowing_rotation(jwks_uri: str, assertion: str) -> PyJWK:
+ """Select the assertion's signing key, re-fetching the JWKS once when the key is unknown.
+
+ A client that rotates keys signs with the new ``kid`` while our cached copy of its key
+ set still holds only the old ones, which would reject the client until the cache
+ expires. The marker caps forced re-fetches at one per interval per URI.
+ """
+ try:
+ return _select_key(load_jwks(jwks_uri), assertion)
+ except UnknownSigningKeyError:
+ marker = f"{JWKS_CACHE_PREFIX}rotation-refresh:{jwks_uri}"
+ if not cache.add(marker, True, timeout=JWKS_ROTATION_REFRESH_MIN_INTERVAL_SECONDS):
+ raise
+ # Fetched directly rather than through load_jwks(force_refresh=True), whose failure
+ # path writes the negative sentinel over the cached set: one assertion naming a bogus
+ # kid while the client's JWKS endpoint is down would then lock out every assertion
+ # signed with an already-cached key for the negative-cache window.
+ parsed = _fetch_jwks_document(jwks_uri)
+ cache.set(f"{JWKS_CACHE_PREFIX}{jwks_uri}", parsed, timeout=JWKS_CACHE_TTL_SECONDS)
+ return _select_key(PyJWKSet.from_dict(parsed), assertion)
+
+
def _consume_jti(client_id: str, jti: str, expires_at: int) -> None:
"""Reject a replayed assertion. Scoped per client so one client cannot burn another's
identifiers. Held until the assertion would have expired anyway, so the cache never has
@@ -224,7 +266,7 @@ def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences:
if not app.uses_private_key_jwt_auth or not app.jwks_uri:
raise ClientAssertionError("This client is not registered for private_key_jwt authentication")
- key = _select_key(load_jwks(app.jwks_uri), assertion)
+ key = _select_key_allowing_rotation(app.jwks_uri, assertion)
# A CIMD client names itself by its metadata URL, not by the opaque client_id column, so
# that is the identity its assertion carries.
client_identifier = app.effective_client_id
@@ -258,7 +300,13 @@ def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences:
raise ClientAssertionError("Client assertion subject does not match the client")
expires_at = claims["exp"]
- if expires_at - claims["iat"] > MAX_ASSERTION_LIFETIME_SECONDS:
+ issued_at = claims["iat"]
+ # PyJWT validates timestamps after int() coercion but hands back the original claim
+ # values, so a numeric-string exp or iat survives decoding and would make the arithmetic
+ # below a TypeError, surfacing as a 500 instead of invalid_client.
+ if not isinstance(expires_at, (int, float)) or not isinstance(issued_at, (int, float)):
+ raise ClientAssertionError("Client assertion timestamps must be numeric")
+ if expires_at - issued_at > MAX_ASSERTION_LIFETIME_SECONDS:
raise ClientAssertionError(f"Client assertion lifetime exceeds {MAX_ASSERTION_LIFETIME_SECONDS} seconds")
_consume_jti(client_identifier, str(claims["jti"]), int(expires_at))
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index 409b20fc2c65..dbdf1ea52175 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -27,6 +27,7 @@ from posthog.api.oauth.cimd import (
_resolve_scopes,
_update_cimd_application,
apply_provisioning_defaults,
+ enqueue_cimd_refresh_if_stale,
fetch_and_upsert_cimd_application,
fetch_cimd_metadata,
get_application_by_client_id,
@@ -454,6 +455,15 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
self.assertEqual(result.name, "Original Name")
mock_task.delay.assert_called_once_with(VALID_CIMD_URL)
+ def test_stale_refresh_enqueues_one_task_while_pending(self, _url_mock):
+ real_cache.clear()
+ # The staleness check runs before any client authentication, so a burst of requests
+ # against a stale document must coalesce into one queued task, not one per request.
+ with patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task") as mock_task:
+ enqueue_cimd_refresh_if_stale(VALID_CIMD_URL)
+ enqueue_cimd_refresh_if_stale(VALID_CIMD_URL)
+ mock_task.delay.assert_called_once_with(VALID_CIMD_URL)
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_new_client_fetch_failure_raises(self, mock_get, _url_mock):
mock_get.side_effect = requests.ConnectionError("DNS resolution failed")
diff --git a/posthog/api/oauth/test_client_assertion.py b/posthog/api/oauth/test_client_assertion.py
index 8b7902c300db..22cbb0f7b1c8 100644
--- a/posthog/api/oauth/test_client_assertion.py
+++ b/posthog/api/oauth/test_client_assertion.py
@@ -149,6 +149,57 @@ class TestClientAssertion(BaseTest):
with self.assertRaises(ClientAssertionError):
self._verify(self._assertion(kid="rotated-out-key"))
+ def test_rotated_key_verifies_after_one_jwks_refresh(self):
+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)):
+ load_jwks(JWKS_URI)
+
+ rotated = _jwks_for(self.private_key, kid="rotated-key")
+ with patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(rotated, None)
+ ) as fetch:
+ verify_client_assertion(self.app, self._assertion(kid="rotated-key"))
+ # The cached set doesn't hold the new kid, so exactly one forced re-fetch runs.
+ fetch.assert_called_once()
+
+ def test_failed_rotation_refresh_keeps_cached_keys(self):
+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)):
+ load_jwks(JWKS_URI)
+
+ with patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document",
+ side_effect=CIMDFetchError("unreachable"),
+ ):
+ with self.assertRaises(ClientAssertionError):
+ verify_client_assertion(self.app, self._assertion(kid="bogus-kid"))
+
+ # The failed forced fetch must not evict the cached set: an assertion signed with the
+ # already-cached key still verifies, without another outbound fetch.
+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document") as fetch:
+ verify_client_assertion(self.app, self._assertion())
+ fetch.assert_not_called()
+
+ def test_unknown_kid_refresh_is_rate_limited(self):
+ with patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)
+ ) as fetch:
+ with self.assertRaises(ClientAssertionError):
+ verify_client_assertion(self.app, self._assertion(kid="bogus-1"))
+ with self.assertRaises(ClientAssertionError):
+ verify_client_assertion(self.app, self._assertion(kid="bogus-2"))
+ # Initial load plus the one allowed rotation refresh: the second bogus kid must
+ # not produce a third outbound fetch.
+ assert fetch.call_count == 2
+
+ @parameterized.expand([("iat",), ("exp",)])
+ def test_numeric_string_timestamp_is_rejected(self, field):
+ now = int(time.time())
+ values: dict = {"iat": now, "exp": now + 60}
+ values[field] = str(values[field])
+ # PyJWT coerces numeric strings during its own validation, so without the explicit
+ # type check this would raise TypeError instead of the wire-safe rejection.
+ with self.assertRaises(ClientAssertionError):
+ self._verify(self._assertion(**values))
+
def test_kid_required_when_jwks_holds_several_keys(self):
self.jwks = {"keys": [*self.jwks["keys"], *_jwks_for(OTHER_KEY, kid="partner-key-2")["keys"]]}
with self.assertRaises(ClientAssertionError):
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index f61bdb3df769..5246a0ce012b 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -1,4 +1,5 @@
import os
+import json
import base64
import hashlib
import importlib
@@ -23,9 +24,12 @@ from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from oauth2_provider.utils import jwk_from_pem
from parameterized import parameterized
+from redis.exceptions import RedisError
from rest_framework import status
from posthog.api.oauth import OAuthAuthorizationSerializer
+from posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODS
+from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER
from posthog.api.oauth.views import OAuthValidator
from posthog.models.oauth import (
OAuthAccessToken,
@@ -635,6 +639,146 @@ class TestOAuthAPI(APIBaseTest):
self.assertIn("refresh_token", body)
self.assertTrue(OAuthRefreshToken.objects.filter(application=other_app).exists())
+ def _create_private_key_jwt_app_and_grant(
+ self,
+ ) -> tuple[OAuthApplication, OAuthGrant, rsa.RSAPrivateKey]:
+ cimd_url = "https://partner.example.com/oauth/client-metadata"
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ app = OAuthApplication.objects.create(
+ name="Private Key JWT CIMD Client",
+ client_id="cimd-pkjwt-client-id",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://partner.example.com/callback",
+ user=self.user,
+ algorithm="RS256",
+ is_cimd_client=True,
+ cimd_metadata_url=cimd_url,
+ jwks_uri="https://partner.example.com/.well-known/jwks.json",
+ )
+ grant = OAuthGrant.objects.create(
+ application=app,
+ user=self.user,
+ code="pkjwt-code",
+ code_challenge=self.code_challenge,
+ code_challenge_method="S256",
+ expires=timezone.now() + timedelta(minutes=1),
+ redirect_uri="https://partner.example.com/callback",
+ scope="openid",
+ scoped_organizations=[str(self.organization.id)],
+ scoped_teams=[],
+ )
+ return app, grant, private_key
+
+ def _signed_assertion_and_jwks(self, app: OAuthApplication, private_key: rsa.RSAPrivateKey) -> tuple[str, dict]:
+ now = int(timezone.now().timestamp())
+ assertion = jwt.encode(
+ {
+ "iss": app.cimd_metadata_url,
+ "sub": app.cimd_metadata_url,
+ "aud": "https://us.posthog.com/oauth/token/",
+ "jti": "pkjwt-assertion-1",
+ "iat": now,
+ "exp": now + 60,
+ },
+ private_key,
+ algorithm="RS256",
+ headers={"kid": "partner-key-1"},
+ )
+ jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key()))
+ jwk.update({"kid": "partner-key-1", "use": "sig", "alg": "RS256"})
+ return assertion, {"keys": [jwk]}
+
+ def _post_assertion_exchange(self, app: OAuthApplication, grant: OAuthGrant, assertion: str):
+ return self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "client_id": app.client_id,
+ "redirect_uri": "https://partner.example.com/callback",
+ "code_verifier": self.code_verifier,
+ "code": grant.code,
+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,
+ "client_assertion": assertion,
+ },
+ )
+
+ @freeze_time("2025-01-01 00:00:00")
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_private_key_jwt_cimd_client_completes_token_exchange(self):
+ # A private_key_jwt CIMD client is confidential but holds no secret, so the secret
+ # paths can never authenticate it and only the assertion path can finish an install.
+ 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") as refresh,
+ ):
+ response = self._post_assertion_exchange(app, grant, assertion)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertIn("access_token", response.json())
+ # Token exchanges are the only traffic a refresh-grant-only client sends, so the
+ # assertion path has to be what keeps its CIMD registration fresh.
+ refresh.assert_called_once_with(app.cimd_metadata_url)
+
+ @freeze_time("2025-01-01 00:00:00")
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_private_key_jwt_exchange_survives_refresh_enqueue_failure(self):
+ # Metadata freshness is best-effort: a broker outage must not fail a valid exchange.
+ 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",
+ side_effect=Exception("broker down"),
+ ),
+ ):
+ response = self._post_assertion_exchange(app, grant, assertion)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ @freeze_time("2025-01-01 00:00:00")
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_private_key_jwt_exchange_maps_redis_failure_to_retryable(self):
+ # The assertion path reads Redis for the JWKS and jti caches, so an outage must
+ # produce the retryable temporarily_unavailable response, not an unhandled 500.
+ app, grant, private_key = self._create_private_key_jwt_app_and_grant()
+ assertion, _ = self._signed_assertion_and_jwks(app, private_key)
+
+ with patch("posthog.api.oauth.client_assertion.cache") as mock_cache:
+ mock_cache.get.side_effect = RedisError("connection refused")
+ response = self._post_assertion_exchange(app, grant, assertion)
+
+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE, response.content)
+ self.assertEqual(response.json()["error"], "temporarily_unavailable")
+
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_private_key_jwt_cimd_client_rejected_without_assertion(self):
+ # The confidential client must still fail closed when it presents no credential at all.
+ app, grant, _ = self._create_private_key_jwt_app_and_grant()
+ response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "client_id": app.client_id,
+ "redirect_uri": "https://partner.example.com/callback",
+ "code_verifier": self.code_verifier,
+ "code": grant.code,
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
+
@freeze_time("2025-01-01 00:00:00")
def test_token_endpoint_invalid_client_credentials(self):
grant = OAuthGrant.objects.create(
@@ -4288,6 +4432,14 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
self.assertEqual(metadata["code_challenge_methods_supported"], ["S256"])
self.assertIn("none", metadata["token_endpoint_auth_methods_supported"])
+ def test_metadata_advertises_every_method_cimd_registers_under(self):
+ # Guards the drift that broke CIMD installs: a client registers under a method the
+ # discovery document does not advertise, picks a method we reject, and fails the
+ # token exchange. Every method CIMD accepts must appear here.
+ response = self.client.get("/.well-known/oauth-authorization-server")
+ advertised = set(response.json()["token_endpoint_auth_methods_supported"])
+ self.assertTrue(CIMD_SUPPORTED_AUTH_METHODS <= advertised)
+
def test_metadata_advertises_id_jag_grant_profile(self):
response = self.client.get("/.well-known/oauth-authorization-server")
metadata = response.json()
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 79f2dd67323d..06d2da08ceea 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -32,6 +32,7 @@ from oauth2_provider.views import (
)
from oauth2_provider.views.mixins import OAuthLibMixin
from oauthlib.oauth2 import InvalidGrantError
+from redis.exceptions import RedisError
from rest_framework import serializers, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
@@ -43,10 +44,17 @@ from posthog.api.oauth.cimd import (
CIMD_THROTTLE_CLASSES,
CIMDFetchError,
CIMDValidationError,
+ enqueue_cimd_refresh_if_stale,
get_application_by_client_id,
get_or_create_cimd_application,
is_cimd_client_id,
)
+from posthog.api.oauth.client_assertion import (
+ ClientAssertionError,
+ expected_assertion_audiences,
+ resolve_client_assertion,
+ verify_client_assertion,
+)
from posthog.api.oauth.client_auth import 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
@@ -102,6 +110,11 @@ CLIENT_IDS_WITHOUT_REFRESH_TOKEN: frozenset[str] = frozenset(
# distinguishable from "not resolved yet".
_IMPERSONATOR_CACHE_UNSET: object = object()
+# Paths this endpoint answers on, so a private_key_jwt assertion minted for either the
+# issuer or the token_endpoint advertised in discovery is accepted (RFC 7523 section 3).
+# Both slash forms are listed because opt_slash_path serves the route with and without one.
+STANDARD_TOKEN_ENDPOINT_PATHS = ("/oauth/token/", "/oauth/token")
+
def get_region_info() -> dict | None:
"""Return region metadata if running on PostHog Cloud US/EU, else None."""
@@ -360,6 +373,60 @@ class OAuthValidator(OAuth2Validator):
request.client = app
return request.client
+ def authenticate_client(self, request, *args, **kwargs):
+ """Authenticate a confidential client, adding ``private_key_jwt`` (RFC 7523).
+
+ CIMD clients register as confidential with a ``jwks_uri`` and never receive a secret,
+ so the library's secret-based paths cannot authenticate them. A client presenting a
+ signed assertion is verified here against the keys it publishes; every other client
+ falls through to the library's HTTP Basic and request-body secret checks.
+ """
+ if self._authenticate_client_assertion(request):
+ return True
+ return super().authenticate_client(request, *args, **kwargs)
+
+ def _authenticate_client_assertion(self, request) -> bool:
+ assertion = resolve_client_assertion(
+ getattr(request, "client_assertion", None) or "",
+ getattr(request, "client_assertion_type", None) or "",
+ getattr(request, "client_id", None) or "",
+ )
+ if assertion is None:
+ return False
+
+ assertion_value, client_id = assertion
+ app = self._load_application(client_id, request)
+ if app is None or not app.uses_private_key_jwt_auth:
+ return False
+
+ if app.is_cimd_client and app.cimd_metadata_url:
+ # Token and refresh exchanges never pass through validate_client_id, which is
+ # where a CIMD document is normally re-read, so a client living on refresh
+ # grants alone would otherwise keep a stale auth method or key source forever.
+ # Best-effort: a broker outage must not fail an otherwise valid exchange.
+ try:
+ enqueue_cimd_refresh_if_stale(app.cimd_metadata_url)
+ except Exception as e:
+ logger.warning(
+ "oauth_cimd_refresh_enqueue_error",
+ client_id=client_id,
+ error=str(e),
+ error_type=type(e).__name__,
+ )
+
+ try:
+ verify_client_assertion(
+ app,
+ assertion_value,
+ audiences=expected_assertion_audiences(*STANDARD_TOKEN_ENDPOINT_PATHS),
+ )
+ except ClientAssertionError as e:
+ logger.warning("oauth_client_assertion_rejected", client_id=client_id, error=str(e))
+ return False
+
+ request.client = app
+ return True
+
# PostHog deliberately does NOT support OIDC silent authentication (`prompt=none`). Every
# authorization must go through the interactive login + consent prompt — we never issue a
# token without showing UI. oauthlib gates `prompt=none` on two validators in sequence
@@ -1393,6 +1460,17 @@ class OAuthTokenView(TokenView):
error=str(e),
)
return _temporarily_unavailable_response()
+ except RedisError as e:
+ # Client authentication reads Redis on the private_key_jwt path (JWKS cache, jti
+ # replay cache), so a transient Redis failure otherwise surfaces as an unhandled
+ # 500 instead of a retryable response.
+ logger.warning(
+ "oauth_token_redis_unavailable",
+ grant_type=grant_type,
+ client_id_prefix=client_id_prefix,
+ error=str(e),
+ )
+ return _temporarily_unavailable_response()
logger.info(
"oauth_token_response",
@@ -1679,11 +1757,13 @@ class OAuthAuthorizationServerMetadataView(_PublicMetadataView):
id_jag.JWT_BEARER_GRANT_TYPE,
],
"authorization_grant_profiles_supported": [id_jag.ID_JAG_GRANT_PROFILE],
- # private_key_jwt is deliberately absent: it is implemented on the agentic token
- # endpoint, not on the endpoint this document describes.
+ # Every method a client can register under (including CIMD's private_key_jwt) must
+ # appear here, or a client reads this document, picks a method we do not accept, and
+ # fails the token exchange.
"token_endpoint_auth_methods_supported": [
TokenEndpointAuthMethod.NONE.value,
TokenEndpointAuthMethod.CLIENT_SECRET_POST.value,
+ TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value,
],
"code_challenge_methods_supported": ["S256"],
# Service documentation