: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): accept the id-jag resource as a token request parameter (#130461)
Rafael Audibert08b0a224ed4b
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.pyindex ac6c0191528d..7fe80b9423fe 100644--- a/posthog/api/id_jag.py+++ b/posthog/api/id_jag.py@@ -262,7 +262,27 @@ def _get_scopes(id_jag_scopes: list[str], requested_scopes: list[str] | None) ->return intersected-def _verify_and_extract_id_jag_token(assertion: str, authenticated_client_id: str) -> _VerifiedIdJag:+def _resolve_resource(claim_resource: str | None, requested_resource: str | None) -> str:+ """The resource the minted token is for, as one of `get_allowed_resources()`.++ The ID-JAG draft makes the `resource` claim optional, and the token request can carry the+ RFC 8707 `resource` parameter instead. Claude-issued assertions use only the parameter, and+ an IdP adds the claim only when the client asked it to. With neither, the token is for this+ deployment, which the PostHog API and the MCP server both accept.+ """+ claim = (claim_resource or "").rstrip("/")+ requested = (requested_resource or "").rstrip("/")+ if claim and requested and claim != requested:+ raise InvalidTargetError("The resource parameter doesn't match the ID-JAG resource claim")+ resource = claim or requested or _get_site_url()+ if resource not in get_allowed_resources():+ raise InvalidTargetError(f"ID-JAG resource {resource!r} does not match this resource server")+ return resource+++def _verify_and_extract_id_jag_token(+ assertion: str, authenticated_client_id: str, requested_resource: str | None+) -> _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`,@@ -370,14 +390,8 @@ def _verify_and_extract_id_jag_token(assertion: str, authenticated_client_id: st)raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)- resource = claims.get("resource")- if not resource:- raise InvalidGrantError("ID-JAG is missing the resource claim (RFC 8707)")- resource = resource.rstrip("/")- if resource not in get_allowed_resources():- raise InvalidTargetError(f"ID-JAG resource {resource!r} does not match this resource server")- # Store the normalized value back so the minted token's `aud` is consistent.- claims["resource"] = resource+ # Store the resolved value back so the minted token's `aud` is consistent.+ claims["resource"] = _resolve_resource(claims.get("resource"), requested_resource)client_id = claims.get("client_id")if not client_id:@@ -566,16 +580,20 @@ def _parse_scope_list(value: str | list[str] | None) -> list[str]:def issue_access_token(- assertion: str, requested_scope: str | list[str] | None, authenticated_client_id: str+ assertion: str,+ requested_scope: str | list[str] | None,+ authenticated_client_id: str,+ requested_resource: str | None = None,) -> 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 HTTPhandler. `authenticated_client_id` must come from verified client- authentication, never from an unchecked request field.+ authentication, never from an unchecked request field. `requested_resource`+ is the token request's RFC 8707 `resource` parameter."""- verified_id_jag = _verify_and_extract_id_jag_token(assertion, authenticated_client_id)+ verified_id_jag = _verify_and_extract_id_jag_token(assertion, authenticated_client_id, requested_resource)organization = verified_id_jag.identity_provider_config.organizationif not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex dbe26bc1f05c..3654b41ac346 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -2233,7 +2233,9 @@ class OAuthTokenView(TokenView):)try:- issued_access_token = id_jag.issue_access_token(assertion, request.POST.get("scope"), client.client_id)+ issued_access_token = id_jag.issue_access_token(+ assertion, request.POST.get("scope"), client.client_id, request.POST.get("resource")+ )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, client.client_id, e.error_code)diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex 41879d4ce0b9..f6e797201dd1 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -939,25 +939,43 @@ class TestIdJagTokenEndpoint(APIBaseTest):self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)self.assertEqual(resp.json()["error"], "invalid_client")- def test_rejects_missing_resource_claim(self) -> None:- assertion = jwt.encode(- {- "iss": _IDP_ISSUER,- "sub": "[email protected]",- "aud": _AUTH_SERVER_URL,- "client_id": _RESOURCE_CLIENT_ID,- # resource intentionally missing- "scope": "feature_flag:read",- "iat": int(time.time()),- "exp": int(time.time()) + 300,- },- _IDP_PRIVATE_KEY_PEM,- algorithm="RS256",- headers={"typ": ID_JAG_TOKEN_TYPE},+ @parameterized.expand(+ [+ ("parameter_only", None, "https://mcp.posthog.com/mcp", "https://mcp.posthog.com/mcp", None),+ ("neither", None, None, _SITE_URL, None),+ ("claim_and_parameter_differ", _SITE_URL, "https://mcp.posthog.com/mcp", None, "invalid_target"),+ ("parameter_not_allowed", None, "https://other-resource.example.com", None, "invalid_target"),+ ]+ )+ @override_settings(ID_JAG_ALLOWED_RESOURCES=["https://mcp.posthog.com/mcp"])+ def test_resource_from_claim_or_request_parameter(+ self,+ _name: str,+ claim_resource: str | None,+ requested_resource: str | None,+ expected_aud: str | None,+ expected_error: str | None,+ ) -> None:+ assertion = _make_id_jag(resource=claim_resource) if claim_resource else _make_id_jag(omit_claims=("resource",))+ body = {"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}+ if requested_resource:+ body["resource"] = requested_resource++ resp = self._post_token(body)++ if expected_error:+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST, resp.content)+ self.assertEqual(resp.json()["error"], expected_error)+ return+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ claims = jwt.decode(+ resp.json()["access_token"],+ _public_key_for(_AS_PRIVATE_KEY_PEM),+ algorithms=["RS256"],+ audience=expected_aud,+ issuer=_AUTH_SERVER_URL,)- resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(resp.json()["error"], "invalid_grant")+ self.assertEqual(claims["aud"], expected_aud)def test_get_sub_format(self) -> None:self.assertEqual(_get_sub("example.com", "[email protected]"), "example.com:[email protected]")