: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): require client authentication on the id-jag jwt-bearer grant (#113013)
Rafael Audibert0c30fcb16949
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.pyindex c9cc60e2b3bf..439a92a73cd4 100644--- a/posthog/api/id_jag.py+++ b/posthog/api/id_jag.py@@ -258,7 +258,7 @@ def _get_scopes(id_jag_scopes: list[str], requested_scopes: list[str] | None) ->return intersected-def _verify_and_extract_id_jag_token(assertion: str) -> _VerifiedIdJag:+def _verify_and_extract_id_jag_token(assertion: str, authenticated_client_id: str) -> _VerifiedIdJag:"""Verifies the provided ID-JAG token against the IdP's JWKS and returns theclaims, the provider name we stamp into the issued access token's `sub`,@@ -379,6 +379,10 @@ def _verify_and_extract_id_jag_token(assertion: str) -> _VerifiedIdJag:if not client_id:raise InvalidGrantError("ID-JAG is missing the client_id claim")+ # Checked before the jti is consumed, so another client holding a captured ID-JAG cannot burn it.+ if client_id != authenticated_client_id:+ raise InvalidGrantError("ID-JAG client_id doesn't match the authenticating client")+# validate allowed clients if set in configif idp_config.id_jag_allowed_clients and client_id not in idp_config.id_jag_allowed_clients:raise InvalidClientError(f"client_id {client_id!r} is not allowed for this domain")@@ -507,23 +511,21 @@ def _parse_scope_list(value: str | list[str] | None) -> list[str]:def issue_access_token(- assertion: str, requested_scope: str | list[str] | None, request_client_id: str | None+ assertion: str, requested_scope: str | list[str] | None, authenticated_client_id: str) -> IssuedAccessToken:"""Validate an ID-JAG `assertion` and mint an access token. Pulled out of theview so the same path is exercised by tests, batch tools, and the HTTP- handler.+ handler. `authenticated_client_id` must come from verified client+ authentication, never from an unchecked request field."""- verified_id_jag = _verify_and_extract_id_jag_token(assertion)+ verified_id_jag = _verify_and_extract_id_jag_token(assertion, authenticated_client_id)organization = verified_id_jag.identity_provider_config.organizationif not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):raise AccessDeniedError("ID-JAG (XAA) is not enabled for this organization")- if request_client_id and request_client_id != verified_id_jag.claims.get("client_id"):- raise InvalidGrantError("ID-JAG client_id doesn't match the authenticating client")-id_jag_scopes = _parse_scope_list(verified_id_jag.claims.get("scope"))parsed_requested = _parse_scope_list(requested_scope) if requested_scope is not None else Nonediff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 6f1a1fa6f8e6..8d08c1c4d280 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -1402,6 +1402,48 @@ def _login_required_with_pending_connection(view):return handler+def cimd_creation_throttled(request, view, client_id: str) -> bool:+ """Whether creating an application for an unseen CIMD client_id is over its rate limit.++ Checked on the view, not in the OAuthValidator, because the validator only receives an+ oauthlib Request, which lacks request.META for IP extraction."""+ if not is_cimd_client_id(client_id) or OAuthApplication.objects.filter(client_id=client_id).exists():+ return False+ for throttle_cls in CIMD_THROTTLE_CLASSES:+ throttle = throttle_cls()+ if not throttle.allow_request(request, view=view):+ logger.warning("cimd_rate_limited", client_id=client_id, scope=throttle.scope, wait=throttle.wait())+ return True+ return False+++def authenticated_oauth_client(view, request, *, resolve_cimd: bool = False) -> OAuthApplication | None:+ """The application the request's client credentials verify as, or None.++ The identity is the application the validator bound during verification. Request fields+ are not trusted for it: an `Authorization: Basic` header or a `client_id` param can name+ any client without proving anything.++ `resolve_cimd` covers a CIMD client presenting credentials before it ever authorized, so+ it has no row yet. Its document is fetched first, so its assertion can be verified against+ the keys the document publishes."""+ core = view.get_oauthlib_core()+ uri, http_method, body, headers = core._extract_params(request)+ oauth_request = OauthlibRequest(uri, http_method, body, headers)+ validator = core.server.request_validator+ if resolve_cimd:+ # RFC 7523 lets a private_key_jwt client omit client_id and name itself in the assertion.+ resolved_assertion = OAuthValidator._resolve_request_assertion(oauth_request)+ client_id = resolved_assertion.client_id if resolved_assertion else request.POST.get("client_id") or ""+ if cimd_creation_throttled(request, view, client_id):+ return None+ if is_cimd_client_id(client_id) and not validator.validate_client_id(client_id, oauth_request):+ return None+ if not validator.authenticate_client(oauth_request):+ return None+ return oauth_request.client++class OAuthAuthorizationView(OAuthLibMixin, APIView):"""This view handles incoming requests to /authorize.@@ -1517,21 +1559,14 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):@method_decorator(_login_required_with_pending_connection)def get(self, request, *args, **kwargs):# Rate-limit new CIMD application creation by IP.- # Must happen here (not in the OAuthValidator) because the validator- # only receives an oauthlib Request which lacks request.META for IP extraction.- client_id = request.query_params.get("client_id")- if is_cimd_client_id(client_id) and not OAuthApplication.objects.filter(client_id=client_id).exists():- for throttle_cls in CIMD_THROTTLE_CLASSES:- throttle = throttle_cls()- if not throttle.allow_request(request, view=self):- logger.warning("cimd_rate_limited", client_id=client_id, scope=throttle.scope, wait=throttle.wait())- return Response(- {- "error": "invalid_client",- "error_description": "Too many new client registrations. Try again later.",- },- status=status.HTTP_400_BAD_REQUEST,- )+ if cimd_creation_throttled(request, self, request.query_params.get("client_id") or ""):+ return Response(+ {+ "error": "invalid_client",+ "error_description": "Too many new client registrations. Try again later.",+ },+ status=status.HTTP_400_BAD_REQUEST,+ )try:scopes, credentials = self.validate_authorization_request(request)@@ -2060,14 +2095,32 @@ class OAuthTokenView(TokenView):status=400,)- requested_scope = request.POST.get("scope")- request_client_id = request.POST.get("client_id")+ # The ID-JAG draft binds the assertion to the client that presents it and supports the+ # grant for confidential clients only, so a client presenting no credential is refused.+ client = authenticated_oauth_client(self, request, resolve_cimd=True)+ if client is None:+ self._capture_token_rejected(+ id_jag.JWT_BEARER_GRANT_TYPE,+ request.POST.get("client_id") or "",+ "invalid_client",+ self._request_client_auth_method(request),+ )+ return JsonResponse(+ {+ "error": "invalid_client",+ "error_description": (+ "Client authentication failed. The jwt-bearer grant needs a registered client that "+ "authenticates with a client secret or private_key_jwt."+ ),+ },+ status=401,+ )try:- issued_access_token = id_jag.issue_access_token(assertion, requested_scope, request_client_id)+ issued_access_token = id_jag.issue_access_token(assertion, request.POST.get("scope"), client.client_id)except id_jag.IdJagError as e:logger.info("id_jag_token_rejected", error=e.error_code, description=e.description)- self._capture_token_rejected(id_jag.JWT_BEARER_GRANT_TYPE, request_client_id or "", e.error_code)+ self._capture_token_rejected(id_jag.JWT_BEARER_GRANT_TYPE, client.client_id, e.error_code)return JsonResponse({"error": e.error_code, "error_description": e.description},status=e.http_status,@@ -2077,11 +2130,11 @@ class OAuthTokenView(TokenView):# the funnel. There is no resource owner to attribute it to, so it stays personless# and keyed on the client.posthoganalytics.capture(- distinct_id=request_client_id or "unknown",+ distinct_id=client.client_id,event="oauth_token_issued",properties={"grant_type": id_jag.JWT_BEARER_GRANT_TYPE,- "client_id": request_client_id or "",+ "client_id": client.client_id,"granted_scopes": " ".join(issued_access_token.granted_scopes),"granted_scope_count": len(issued_access_token.granted_scopes),"$process_person_profile": False,@@ -2378,12 +2431,10 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):only trustworthy identity is the one the validator bound to the request duringverification, 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):+ client = authenticated_oauth_client(self, request)+ if client is None:return False- request.oauth_authenticated_client = oauth_request.client+ request.oauth_authenticated_client = clientreturn Truedef _client_credentials_client_id(self, request) -> str | None:diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex 72d9e3a45eea..5ca03d045b18 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -13,6 +13,7 @@ The strategy is:import timefrom typing import Any+from urllib.parse import urlencodefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -35,12 +36,14 @@ from posthog.api.id_jag import (_get_sub,issue_access_token,)+from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARERfrom posthog.auth import IDJagAccessTokenAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.activity_logging.utils import ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTHfrom posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfigfrom posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig+from posthog.models.oauth import OAuthApplicationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomainfrom posthog.models.user import User as UserModel@@ -63,12 +66,32 @@ _SITE_URL = "https://posthog.test"_AUTH_SERVER_URL = _SITE_URL_RESOURCE_URL = _SITE_URL_RESOURCE_CLIENT_ID = "client_abc-at-posthog"+_CLIENT_SECRET = "id-jag-test-client-secret"def _public_key_for(pem: str) -> Any:return serialization.load_pem_private_key(pem.encode(), password=None).public_key()+def _create_client(+ client_id: str,+ *,+ client_type: str = OAuthApplication.CLIENT_CONFIDENTIAL,+ client_secret: str = _CLIENT_SECRET,+ jwks_uri: str | None = None,+) -> OAuthApplication:+ return OAuthApplication.objects.create(+ name=client_id,+ client_id=client_id,+ client_secret=client_secret,+ client_type=client_type,+ jwks_uri=jwks_uri,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://client.example.com/callback",+ algorithm="RS256",+ )++def _make_id_jag(*,issuer: str = _IDP_ISSUER,@@ -141,6 +164,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):organization=cls.organization, name=_IDP_CONFIG_NAME, id_jag_issuer_url=_IDP_ISSUER)LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)+ _create_client(_RESOURCE_CLIENT_ID)def setUp(self) -> None:super().setUp()@@ -157,8 +181,20 @@ class TestIdJagTokenEndpoint(APIBaseTest):self._jwks_patch.start()self.addCleanup(self._jwks_patch.stop)- def _post_token(self, body: dict[str, Any]) -> Any:- return self.client.post("/oauth/token", data=body, content_type="application/json")+ def _post_token(+ self,+ body: dict[str, Any],+ *,+ client_id: str = _RESOURCE_CLIENT_ID,+ credentials: dict[str, str] | None = None,+ content_type: str = "application/json",+ ) -> Any:+ if credentials is None:+ credentials = {"client_id": client_id, "client_secret": _CLIENT_SECRET}+ data = {**credentials, **body}+ if content_type.startswith("application/x-www-form-urlencoded"):+ return self.client.post("/oauth/token", data=urlencode(data), content_type=content_type)+ return self.client.post("/oauth/token", data=data, content_type=content_type)@parameterized.expand([@@ -220,7 +256,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):assertion = _make_id_jag()with self.assertRaises(AccessDeniedError):- issue_access_token(assertion, requested_scope=None, request_client_id=None)+ issue_access_token(assertion, requested_scope=None, authenticated_client_id=_RESOURCE_CLIENT_ID)def test_email_claim_is_preferred_over_sub_for_user_lookup(self) -> None:# IdPs are not required to put an email in `sub` — it may be an opaque@@ -360,12 +396,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):self.assertEqual(resp.json()["scope"], "feature_flag:read")def test_accepts_form_urlencoded_body(self) -> None:- from urllib.parse import urlencode-assertion = _make_id_jag()- resp = self.client.post(- "/oauth/token",- data=urlencode({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}),+ resp = self._post_token(+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},content_type="application/x-www-form-urlencoded",)self.assertEqual(resp.status_code, status.HTTP_200_OK)@@ -373,12 +406,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):def test_accepts_form_urlencoded_body_with_charset_suffix(self) -> None:# RFC 6749 doesn't pin the charset, and real-world clients tack on a# `; charset=utf-8` (or UTF-8) — DRF's FormParser must still match.- from urllib.parse import urlencode-assertion = _make_id_jag()- resp = self.client.post(- "/oauth/token",- data=urlencode({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}),+ resp = self._post_token(+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},content_type="application/x-www-form-urlencoded; charset=UTF-8",)self.assertEqual(resp.status_code, status.HTTP_200_OK)@@ -386,18 +416,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):def test_form_urlencoded_with_scope_parameter(self) -> None:# Scope is a space-separated string per RFC 6749 §3.3 and must survive# the form-encoded round-trip without being treated as a multi-value.- from urllib.parse import urlencode-assertion = _make_id_jag(scope="feature_flag:read feature_flag:write")- resp = self.client.post(- "/oauth/token",- data=urlencode(- {- "grant_type": JWT_BEARER_GRANT_TYPE,- "assertion": assertion,- "scope": "feature_flag:read",- }- ),+ resp = self._post_token(+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion, "scope": "feature_flag:read"},content_type="application/x-www-form-urlencoded",)self.assertEqual(resp.status_code, status.HTTP_200_OK)@@ -581,24 +602,95 @@ class TestIdJagTokenEndpoint(APIBaseTest):resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})self.assertEqual(resp.status_code, expected_status, resp.json())- def test_rejects_request_client_id_mismatch(self) -> None:- assertion = _make_id_jag(client_id="client_abc-at-posthog")+ def test_rejects_id_jag_issued_to_another_client(self) -> None:+ _create_client("client_other-at-posthog")+ assertion = _make_id_jag(client_id=_RESOURCE_CLIENT_ID)resp = self._post_token(- {- "grant_type": JWT_BEARER_GRANT_TYPE,- "assertion": assertion,- "client_id": "client_DIFFERENT-at-posthog",- }+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},+ client_id="client_other-at-posthog",)self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(resp.json()["error"], "invalid_grant")- def test_arbitrary_client_id_is_accepted_when_no_allowlist(self) -> None:- # When `OrganizationDomain.id_jag_allowed_clients` is empty (the default),- # any `client_id` value passes — the IdP signature is the binding.- # We still require the claim to be present.+ retry = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(retry.status_code, status.HTTP_200_OK, retry.json())++ @parameterized.expand(+ [+ ("no_credentials", {"client_id": _RESOURCE_CLIENT_ID}),+ ("wrong_secret", {"client_id": _RESOURCE_CLIENT_ID, "client_secret": "wrong"}),+ ("unregistered_client", {"client_id": "client_unknown", "client_secret": _CLIENT_SECRET}),+ ("public_client", {"client_id": "client_public"}),+ ]+ )+ def test_rejects_unauthenticated_client_without_consuming_the_assertion(+ self, _name: str, credentials: dict[str, str]+ ) -> None:+ _create_client("client_public", client_type=OAuthApplication.CLIENT_PUBLIC, client_secret="")+ assertion = _make_id_jag()+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}, credentials=credentials)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)+ self.assertEqual(resp.json()["error"], "invalid_client")++ retry = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(retry.status_code, status.HTTP_200_OK, retry.json())++ @parameterized.expand([("allowed", True, status.HTTP_200_OK), ("throttled", False, status.HTTP_401_UNAUTHORIZED)])+ def test_first_seen_cimd_client_authenticates_with_private_key_jwt(+ self, _name: str, throttle_allows: bool, expected_status: int+ ) -> None:+ client_id = "https://agent.example.com/client.json"+ throttle = MagicMock(scope="cimd_burst")+ throttle.allow_request.return_value = throttle_allows+ client_key = ec.generate_private_key(ec.SECP256R1())+ jwk = jwt.algorithms.ECAlgorithm.to_jwk(client_key.public_key(), as_dict=True)+ jwk.update({"kid": "client-key", "alg": "ES256", "use": "sig"})+ now = int(time.time())+ client_assertion = jwt.encode(+ {+ "iss": client_id,+ "sub": client_id,+ "aud": f"{_SITE_URL}/oauth/token/",+ "jti": f"client-assertion-{now}",+ "iat": now,+ "exp": now + 60,+ },+ client_key,+ algorithm="ES256",+ headers={"kid": "client-key"},+ )++ with (+ patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=({"keys": [jwk]}, None)+ ),+ patch(+ "posthog.api.oauth.views.get_or_create_cimd_application",+ side_effect=lambda cimd_client_id: _create_client(+ cimd_client_id, client_secret="", jwks_uri="https://agent.example.com/jwks.json"+ ),+ ) as create_cimd_application,+ patch("posthog.api.oauth.views.CIMD_THROTTLE_CLASSES", new=[MagicMock(return_value=throttle)]),+ ):+ resp = self._post_token(+ {+ "grant_type": JWT_BEARER_GRANT_TYPE,+ "assertion": _make_id_jag(client_id=client_id),+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ "client_assertion": client_assertion,+ },+ credentials={},+ )+ self.assertEqual(resp.status_code, expected_status, resp.json())+ self.assertEqual(create_cimd_application.called, throttle_allows)++ def test_any_authenticated_client_is_accepted_when_no_allowlist(self) -> None:+ _create_client("client_anything-at-posthog")assertion = _make_id_jag(client_id="client_anything-at-posthog")- resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ resp = self._post_token(+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},+ client_id="client_anything-at-posthog",+ )self.assertEqual(resp.status_code, status.HTTP_200_OK)body = resp.json()claims = jwt.decode(@@ -735,8 +827,12 @@ class TestIdJagTokenEndpoint(APIBaseTest):config.id_jag_allowed_clients = ["client_first", "client_second"]config.save()+ _create_client("client_second")assertion = _make_id_jag(client_id="client_second")- resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ resp = self._post_token(+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},+ client_id="client_second",+ )self.assertEqual(resp.status_code, status.HTTP_200_OK)def test_allowed_clients_rejects_unlisted_client_id(self) -> None:@@ -745,8 +841,12 @@ class TestIdJagTokenEndpoint(APIBaseTest):config.id_jag_allowed_clients = ["client_first", "client_second"]config.save()+ _create_client("client_third")assertion = _make_id_jag(client_id="client_third")- resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ resp = self._post_token(+ {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},+ client_id="client_third",+ )self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)self.assertEqual(resp.json()["error"], "invalid_client")@@ -785,7 +885,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):def test_issue_access_token_helper(self) -> None:assertion = _make_id_jag()issued_access_token = issue_access_token(- assertion, requested_scope="feature_flag:read", request_client_id=_RESOURCE_CLIENT_ID+ assertion, requested_scope="feature_flag:read", authenticated_client_id=_RESOURCE_CLIENT_ID)self.assertEqual(issued_access_token.granted_scopes, ["feature_flag:read"])self.assertEqual(issued_access_token.expires_in_seconds, 300)diff --git a/posthog/templates/auth_md.md b/posthog/templates/auth_md.mdindex 147f629e1743..4203b74613f1 100644--- a/posthog/templates/auth_md.md+++ b/posthog/templates/auth_md.md@@ -14,7 +14,7 @@ PostHog is an open-source platform for product analytics, session replay, featur## Agent registration via ID-JAG (Enterprise, beta)-Available on the Enterprise plan with XAA enabled, and currently in beta, so most clients should use one of the options above. With it configured, an agent presents an [ID-JAG](https://xaa.dev) identity assertion (`identity_assertion`) to the token endpoint using the JWT-bearer grant (`urn:ietf:params:oauth:grant-type:jwt-bearer`) and receives a scoped, short-lived OAuth access token bound to the user. See https://posthog.com/docs/settings/id-jag+Available on the Enterprise plan with XAA enabled, and currently in beta, so most clients should use one of the options above. With it configured, an agent presents an [ID-JAG](https://xaa.dev) identity assertion (`identity_assertion`) to the token endpoint using the JWT-bearer grant (`urn:ietf:params:oauth:grant-type:jwt-bearer`) and receives a scoped, short-lived OAuth access token bound to the user. The agent must also authenticate as a registered client, with a client secret or `private_key_jwt`, and the ID-JAG's `client_id` must name that client. See https://posthog.com/docs/settings/id-jag- Identity endpoint: `{{ base_url }}/oauth/token/`- Assertion type: `urn:ietf:params:oauth:token-type:id-jag`