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: move xaa token endpoint to oauth token endpoint (#63828)

Reece Jones66414775b94a
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx
index 614e0e876cd2..38012c337cf6 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx
@@ -1,22 +1,18 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { verifiedDomainsLogic } from './verifiedDomainsLogic'
export function ConfigureIdJagModal(): JSX.Element {
const { configureIdJagModalId, isIdJagConfigSubmitting, idJagConfig } = useValues(verifiedDomainsLogic)
const { setConfigureIdJagModalId } = useActions(verifiedDomainsLogic)
- const { preflight } = useValues(preflightLogic)
- const siteUrl = (preflight?.site_url ?? window.location.origin).replace(/\/$/, '')
const idJagReady = Boolean(idJagConfig.id_jag_issuer_url)
@@ -31,9 +27,6 @@ export function ConfigureIdJagModal(): JSX.Element {
<h3>Configure XAA (ID-JAG)</h3>
</LemonModal.Header>
<LemonModal.Content className="deprecated-space-y-2">
- <LemonField label="Token endpoint" name="_tokenEndpoint">
- <CopyToClipboardInline>{`${siteUrl}/id-jag/token`}</CopyToClipboardInline>
- </LemonField>
<LemonField
name="id_jag_issuer_url"
label="IdP issuer URL"
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index 9baee5182491..33e2533a3196 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -8,26 +8,17 @@ to us, or get a personal API token to programmatically access our API.
"""
import uuid
-from collections.abc import Sequence
from datetime import UTC, datetime, timedelta
from typing import Any, TypedDict, cast
from django.conf import settings
from django.core.cache import cache
-from django.utils.decorators import method_decorator
-from django.views.decorators.csrf import csrf_exempt
import jwt
import requests
import structlog
from oauth2_provider.utils import jwk_from_pem
from rest_framework import status
-from rest_framework.exceptions import ParseError, UnsupportedMediaType
-from rest_framework.parsers import FormParser, JSONParser
-from rest_framework.permissions import AllowAny
-from rest_framework.request import Request
-from rest_framework.response import Response
-from rest_framework.views import APIView
from posthog.constants import AvailableFeature
from posthog.models.organization_domain import OrganizationDomain
@@ -68,12 +59,6 @@ class IdJagError(Exception):
if http_status is not None:
self.http_status = http_status
- def to_response(self) -> Response:
- return Response(
- {"error": self.error_code, "error_description": self.description},
- status=self.http_status,
- )
-
class InvalidRequestError(IdJagError):
error_code = "invalid_request"
@@ -450,38 +435,6 @@ def _construct_access_token(payload: dict[str, Any]) -> str:
)
-def _parse_request_data(request: Request) -> dict[str, Any]:
- """Read the token-endpoint request body via DRF's unified `request.data` so
- both content types land on the same path:
-
- * `application/x-www-form-urlencoded` (RFC 6749 §4.5 — the canonical OAuth
- shape; PyJWT-bearer / SDK clients typically use this), parsed by
- `FormParser` into a `QueryDict`.
- * `application/json`, parsed by `JSONParser` into a `dict`.
-
- Both `QueryDict` and `dict` support `.items()`; we normalize to a plain
- `dict[str, Any]` so callers don't have to care which parser ran.
-
- Unsupported content types and malformed bodies surface as
- `InvalidRequestError` so they map to RFC 6749 `invalid_request` rather than
- DRF's default 415/400 HTML.
- """
-
- try:
- data = request.data
- except UnsupportedMediaType:
- raise InvalidRequestError(
- f"Unsupported Content-Type: {request.content_type or 'unset'}. "
- "Use application/x-www-form-urlencoded or application/json.",
- )
- except ParseError as e:
- raise InvalidRequestError(f"Request body could not be parsed: {e.detail}")
-
- if not hasattr(data, "items"):
- return {}
- return dict(data.items())
-
-
def _parse_scope_list(value: str | list[str] | None) -> list[str]:
if value is None:
return []
@@ -521,62 +474,3 @@ def issue_access_token(
)
token = _construct_access_token(payload)
return token, granted, settings.ID_JAG_ACCESS_TOKEN_TTL_SECONDS
-
-
-@method_decorator(csrf_exempt, name="dispatch")
-class IdJagViewSet(APIView):
- """
- Token endpoint for the JWT Bearer Grant (RFC 7523) — exchanges an ID-JAG
- issued by a trusted IdP for a short-lived PostHog access token.
-
- The XAA flow puts this at the AS `token_endpoint`. We host it at
- `/id-jag/token` to keep it cleanly separated from the OAuth 2.0 token
- endpoint at `/oauth/token`.
-
- https://xaa.dev/docs/step3
- https://xaa.dev/docs/byor-auth-server
- """
-
- authentication_classes: Sequence[type[Any]] = ()
- permission_classes = [AllowAny]
- parser_classes = [FormParser, JSONParser]
- schema = None
-
- def post(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- try:
- data = _parse_request_data(request)
- except IdJagError as e:
- return e.to_response()
-
- grant_type = data.get("grant_type")
- if not grant_type:
- return InvalidRequestError("grant_type is required").to_response()
- if grant_type != JWT_BEARER_GRANT_TYPE:
- return UnsupportedGrantTypeError(
- f"grant_type must be {JWT_BEARER_GRANT_TYPE}",
- ).to_response()
-
- assertion = data.get("assertion")
- if not assertion or not isinstance(assertion, str):
- return InvalidRequestError("assertion is required").to_response()
-
- requested_scope = data.get("scope")
- request_client_id = data.get("client_id")
-
- try:
- token, granted, expires_in_seconds = issue_access_token(assertion, requested_scope, request_client_id)
- except IdJagError as e:
- logger.info("id_jag_token_rejected", error=e.error_code, description=e.description)
- return e.to_response()
-
- return Response(
- {
- "access_token": token,
- "token_type": "Bearer",
- "expires_in": expires_in_seconds,
- "scope": " ".join(granted),
- }
- )
-
- def get(self, _request: Request, *_args: Any, **_kwargs: Any) -> Response:
- return InvalidRequestError("Token endpoint only accepts POST", error_code="invalid_request").to_response()
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 592b968bdc97..4077ff6d2a70 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -3886,7 +3886,10 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
metadata = response.json()
self.assertEqual(metadata["response_types_supported"], ["code"])
- self.assertEqual(metadata["grant_types_supported"], ["authorization_code", "refresh_token"])
+ self.assertEqual(
+ metadata["grant_types_supported"],
+ ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:jwt-bearer"],
+ )
self.assertEqual(metadata["code_challenge_methods_supported"], ["S256"])
self.assertIn("none", metadata["token_endpoint_auth_methods_supported"])
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 9ba2c1c604e9..d69f343f8ec4 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -37,6 +37,7 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.api import id_jag
from posthog.api.oauth.cimd import (
CIMD_THROTTLE_CLASSES,
CIMDFetchError,
@@ -1118,7 +1119,9 @@ class OAuthTokenView(TokenView):
OAuth2 Token endpoint.
This implements a POST request with the following parameters:
- - grant_type: The type of grant to use - only "authorization_code" is supported.
+ - grant_type: The type of grant to use. "authorization_code" and "refresh_token" are
+ supported by the OAuth 2.0 flow; the ID-JAG (XAA) JWT Bearer grant
+ ("urn:ietf:params:oauth:grant-type:jwt-bearer", RFC 7523) is also served here.
- code: The authorization code received from the /authorize request.
- redirect_uri: The redirect URI to use - this is the same as the redirect_uri used in the authorization request.
- code_verifier: The code verifier that was used to generate the code_challenge. The code_challenge is a sha256 hash
@@ -1127,6 +1130,42 @@ class OAuthTokenView(TokenView):
RFC 6749 requires x-www-form-urlencoded, but this endpoint also accepts application/json for convenience.
"""
+ def _handle_jwt_bearer_grant(self, request) -> JsonResponse:
+ """ID-JAG (XAA) JWT Bearer grant (RFC 7523). The XAA spec puts the
+ ID-JAG → access-token exchange at the Authorization Server's
+ token_endpoint, so it is served from this shared endpoint rather than a
+ dedicated one. Verification and minting are delegated to
+ `posthog.api.id_jag.issue_access_token`."""
+ assertion = request.POST.get("assertion")
+ if not assertion or not isinstance(assertion, str):
+ return JsonResponse(
+ {"error": "invalid_request", "error_description": "assertion is required"},
+ status=400,
+ )
+
+ requested_scope = request.POST.get("scope")
+ request_client_id = request.POST.get("client_id")
+
+ try:
+ token, granted, expires_in_seconds = id_jag.issue_access_token(
+ assertion, requested_scope, request_client_id
+ )
+ except id_jag.IdJagError as e:
+ logger.info("id_jag_token_rejected", error=e.error_code, description=e.description)
+ return JsonResponse(
+ {"error": e.error_code, "error_description": e.description},
+ status=e.http_status,
+ )
+
+ return JsonResponse(
+ {
+ "access_token": token,
+ "token_type": "Bearer",
+ "expires_in": expires_in_seconds,
+ "scope": " ".join(granted),
+ }
+ )
+
def post(self, request, *args, **kwargs):
if request.content_type == "application/json" and request.body:
try:
@@ -1141,6 +1180,10 @@ class OAuthTokenView(TokenView):
)
grant_type = request.POST.get("grant_type", "unknown")
+
+ if grant_type == id_jag.JWT_BEARER_GRANT_TYPE:
+ return self._handle_jwt_bearer_grant(request)
+
client_id = request.POST.get("client_id", "")
client_id_prefix = client_id[:8] if client_id else "unknown"
redirect_uri = request.POST.get("redirect_uri", "")
@@ -1453,7 +1496,11 @@ class OAuthAuthorizationServerMetadataView(APIView):
"scopes_supported": all_scopes,
"response_types_supported": ["code"],
"response_modes_supported": ["query"],
- "grant_types_supported": ["authorization_code", "refresh_token"],
+ "grant_types_supported": [
+ "authorization_code",
+ "refresh_token",
+ id_jag.JWT_BEARER_GRANT_TYPE,
+ ],
"token_endpoint_auth_methods_supported": ["none", "client_secret_post"],
"code_challenge_methods_supported": ["S256"],
# Service documentation
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 2330d15f5587..2f70e5db4050 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -139,7 +139,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.addCleanup(self._jwks_patch.stop)
def _post_token(self, body: dict[str, Any]) -> Any:
- return self.client.post("/id-jag/token", data=body, content_type="application/json")
+ return self.client.post("/oauth/token", data=body, content_type="application/json")
def test_issues_access_token_for_valid_id_jag(self) -> None:
assertion = _make_id_jag()
@@ -224,7 +224,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
# that aren't emails. Issuance was already keyed off the `email`
# claim, but the resource-side authenticator was keying off the
# userSub half of `sub` — which 401'd every request. Drive the whole
- # flow end-to-end here: real /id-jag/token → real /api/users/@me/.
+ # flow end-to-end here: real /oauth/token → real /api/users/@me/.
assertion = _make_id_jag(
sub="auth0|opaque-id-abc123",
scope="user:read",
@@ -337,7 +337,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
assertion = _make_id_jag()
resp = self.client.post(
- "/id-jag/token",
+ "/oauth/token",
data=urlencode({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}),
content_type="application/x-www-form-urlencoded",
)
@@ -350,7 +350,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
assertion = _make_id_jag()
resp = self.client.post(
- "/id-jag/token",
+ "/oauth/token",
data=urlencode({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}),
content_type="application/x-www-form-urlencoded; charset=UTF-8",
)
@@ -363,7 +363,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
assertion = _make_id_jag(scope="feature_flag:read feature_flag:write")
resp = self.client.post(
- "/id-jag/token",
+ "/oauth/token",
data=urlencode(
{
"grant_type": JWT_BEARER_GRANT_TYPE,
@@ -376,43 +376,16 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp.json()["scope"], "feature_flag:read")
- def test_rejects_unsupported_content_type(self) -> None:
- assertion = _make_id_jag()
- resp = self.client.post(
- "/id-jag/token",
- data=f"grant_type={JWT_BEARER_GRANT_TYPE}&assertion={assertion}",
- content_type="text/plain",
- )
- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
- body = resp.json()
- self.assertEqual(body["error"], "invalid_request")
- self.assertIn("application/x-www-form-urlencoded", body["error_description"])
-
- def test_cors_headers_on_response(self) -> None:
- # Without CORS headers, browsers strip the response body on cross-origin
- # 4xx replies — the user-visible symptom is Chrome saying "Failed to
- # load response data" in DevTools even though the status is visible.
- # Verify the endpoint is in `CORS_URLS_REGEX` so the middleware adds the
- # right headers to both success and error responses.
- assertion = _make_id_jag()
- resp = self.client.post(
- "/id-jag/token",
- data={"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion},
- content_type="application/json",
- HTTP_ORIGIN="https://example.com",
- )
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
- self.assertIn("Access-Control-Allow-Origin", resp.headers)
-
# Error responses must also carry the CORS header — that's the whole
# point of this test (the body would otherwise be hidden in DevTools).
bad = self.client.post(
- "/id-jag/token",
- data={},
+ "/oauth/token",
+ data={"grant_type": JWT_BEARER_GRANT_TYPE},
content_type="application/json",
HTTP_ORIGIN="https://example.com",
)
self.assertEqual(bad.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(bad.json()["error"], "invalid_request")
self.assertIn("Access-Control-Allow-Origin", bad.headers)
def test_cors_preflight(self) -> None:
@@ -420,7 +393,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
# actual POST. The CORS middleware short-circuits this when the path
# matches `CORS_URLS_REGEX`.
resp = self.client.options(
- "/id-jag/token",
+ "/oauth/token",
HTTP_ORIGIN="https://example.com",
HTTP_ACCESS_CONTROL_REQUEST_METHOD="POST",
HTTP_ACCESS_CONTROL_REQUEST_HEADERS="content-type",
@@ -430,25 +403,11 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.assertIn("Access-Control-Allow-Methods", resp.headers)
self.assertIn("POST", resp.headers["Access-Control-Allow-Methods"])
- def test_missing_grant_type(self) -> None:
- resp = self._post_token({"assertion": _make_id_jag()})
- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(resp.json()["error"], "invalid_request")
-
- def test_unsupported_grant_type(self) -> None:
- resp = self._post_token({"grant_type": "authorization_code", "assertion": _make_id_jag()})
- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(resp.json()["error"], "unsupported_grant_type")
-
def test_missing_assertion(self) -> None:
resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE})
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(resp.json()["error"], "invalid_request")
- def test_get_is_rejected(self) -> None:
- resp = self.client.get("/id-jag/token")
- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
-
def test_rejects_wrong_typ_header(self) -> None:
assertion = _make_id_jag(typ_header="JWT") # not oauth-id-jag+jwt
resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
diff --git a/posthog/auth.py b/posthog/auth.py
index 7b4e14e499b0..ff4a7095834b 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -515,8 +515,9 @@ class JwtAuthentication(authentication.BaseAuthentication):
class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
"""
- Authenticates inbound API requests using an access token minted by our
- ID-JAG token endpoint (`posthog.api.id_jag`). Validates the JWT against the
+ Authenticates inbound API requests using an access token minted by the
+ ID-JAG (XAA) JWT Bearer grant served from the OAuth token endpoint
+ (`/oauth/token`, logic in `posthog.api.id_jag`). Validates the JWT against the
RS256 public key derived from `OIDC_RSA_PRIVATE_KEY` and binds the request
to the User whose email matches the `userSub` half of the token's `sub`
claim (`{provider}:{userSub}` per
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 246a23da3b2a..d11fa48aee5e 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -248,7 +248,7 @@ LOGIN_URL = "/login"
LOGOUT_URL = "/logout"
LOGIN_REDIRECT_URL = "/"
APPEND_SLASH = False
-CORS_URLS_REGEX = r"^(/site_app/|/array/|/static/|/oauth/token/|/id-jag/token/?|/toolbar_oauth/check|/api/(?!early_access_features|surveys|web_experiments).*$)"
+CORS_URLS_REGEX = r"^(/site_app/|/array/|/static/|/oauth/token/?|/toolbar_oauth/check|/api/(?!early_access_features|surveys|web_experiments).*$)"
CORS_ALLOW_HEADERS = default_headers + CORS_ALLOWED_TRACING_HEADERS
X_FRAME_OPTIONS = "SAMEORIGIN"
diff --git a/posthog/urls.py b/posthog/urls.py
index e1c565fa85b7..d10e4d45a8d7 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -30,7 +30,6 @@ from posthog.api import (
user,
)
from posthog.api.github_callback.personal_finish import github_link_complete
-from posthog.api.id_jag import IdJagViewSet
from posthog.api.oauth.connected_apps import ConnectedAppsViewSet
from posthog.api.oauth.raycast_metadata import RAYCAST_METADATA_PATH, RaycastClientMetadataView
from posthog.api.oauth.wizard_metadata import WIZARD_METADATA_PATH, WizardClientMetadataView
@@ -402,7 +401,6 @@ urlpatterns = [
path("site_app/<int:id>/<str:token>/<str:hash>/", site_app.get_site_app),
re_path(r"^demo.*", login_required(demo_route)),
path("", include((oauth2_urls, "oauth2_provider"), namespace="oauth2_provider")),
- opt_slash_path("id-jag/token", IdJagViewSet.as_view(), name="id_jag_token"),
# ingestion
# NOTE: When adding paths here that should be public make sure to update ALWAYS_ALLOWED_ENDPOINTS in middleware.py
opt_slash_path("report", report.get_csp_event), # CSP violation reports
diff --git a/services/mcp/src/lib/auth-errors.ts b/services/mcp/src/lib/auth-errors.ts
index ab4f4dc1ab68..55313f11424f 100644
--- a/services/mcp/src/lib/auth-errors.ts
+++ b/services/mcp/src/lib/auth-errors.ts
@@ -82,7 +82,7 @@ export function buildInvalidTokenFormatResponse(): Response {
// Validate the bearer token format. Accepts:
// * Personal API keys (`phx_…`) and OAuth access tokens (`pha_…`).
// * ID-JAG access tokens — RFC 9068 JWTs with `typ: at+jwt` (issued by the
-// PostHog ID-JAG endpoint at `/id-jag/token`).
+// ID-JAG JWT Bearer grant served from the OAuth token endpoint at `/oauth/token`).
// Returns the auth-error response if invalid, or null if the token is well-formed.
export function validateBearerToken(
token: string | undefined,