: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
feat(auth): add xaa support pt. 1 (#59907)
Reece Jonesec79c93fe8f4
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.pynew file mode 100644index 000000000000..06ba921bfa07--- /dev/null+++ b/posthog/api/id_jag.py@@ -0,0 +1,566 @@+"""+ID-JAG (XAA) implementation. See https://xaa.dev for more information.++TLDR: ID-JAG is a protocol where IdP's issue JWT tokens to their users+which they can send to us to issue a short-lived JWT token which can be+used to access our API. This eliminates the need for the user to oauth+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 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.models.organization_domain import OrganizationDomain+from posthog.models.user import User+from posthog.scopes import get_oauth_scopes_supported+from posthog.security.url_validation import is_url_allowed++logger = structlog.get_logger(__name__)++# https://xaa.dev/docs/token-structure#id-jag — IdP issues ID-JAGs with this header `typ`.+ID_JAG_TOKEN_TYPE = "oauth-id-jag+jwt"++# https://xaa.dev/docs/token-structure#access-token — RFC 9068 access-token `typ`.+ACCESS_TOKEN_TYPE = "at+jwt"++# RFC 7521/7523 — JWT Bearer grant type identifier.+JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"+++GENERIC_ID_JAG_REJECTION = "ID-JAG could not be verified"+++class IdJagError(Exception):+ """+ OAuth-style token-endpoint error. The HTTP body shape follows RFC 6749+ section 5.2 and the XAA error-code table at+ https://xaa.dev/docs/error-codes+ """++ http_status: int = status.HTTP_400_BAD_REQUEST+ error_code: str = "invalid_request"++ def __init__(self, description: str, *, error_code: str | None = None, http_status: int | None = None) -> None:+ super().__init__(description)+ self.description = description+ if error_code is not None:+ self.error_code = error_code+ 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"+++class InvalidGrantError(IdJagError):+ error_code = "invalid_grant"+++class InvalidClientError(IdJagError):+ error_code = "invalid_client"+ http_status = status.HTTP_401_UNAUTHORIZED+++class UnsupportedGrantTypeError(IdJagError):+ error_code = "unsupported_grant_type"+++class InvalidScopeError(IdJagError):+ error_code = "invalid_scope"+++class InvalidTargetError(IdJagError):+ # XAA error-code table lists `invalid_target` for resource-connection mismatch.+ # https://xaa.dev/docs/error-codes#idp-token-exchange+ error_code = "invalid_target"+++class IdJagClaims(TypedDict, total=False):+ iss: str+ sub: str+ email: str | None+ email_verified: bool+ aud: str | list[str]+ client_id: str+ scope: str+ resource: str+ jti: str+ iat: int+ nbf: int+ exp: int+++def _get_site_url() -> str:+ """The deployment's public URL — used as `aud` for inbound ID-JAGs and as+ `iss`/`aud` for the access tokens we mint. Stripped of trailing slash so+ audience equality checks don't fight URL normalization."""+ site_url = (settings.SITE_URL or "").rstrip("/")+ if not site_url:+ raise InvalidGrantError(+ "ID-JAG authentication is not configured: SITE_URL is empty",+ http_status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ error_code="server_error",+ )+ return site_url+++def _get_jwks_client(issuer: str, jwks_url: str | None = None) -> jwt.PyJWKClient:+ """Resolve a `PyJWKClient` for the given IdP issuer.++ If `jwks_url` is provided (set on the `OrganizationDomain.id_jag_jwks_url`+ field), skip OIDC discovery and point PyJWKClient at it directly. Otherwise+ do OIDC discovery against `<issuer>/.well-known/openid-configuration` and+ cache the resulting `jwks_uri` for `ID_JAG_JWKS_CACHE_TTL_SECONDS`. We+ don't cache the `PyJWKClient` object itself because it already does+ in-process key caching (`lifespan` seconds) — caching only the URI keeps+ key rotation responsive while avoiding redundant discovery hits.++ Network and parse failures during discovery are normalized to+ `InvalidGrantError` so callers only have to handle one error type.+ """++ def _check_url(url: str, label: str) -> None:+ # SSRF guard+ allowed, reason = is_url_allowed(url)+ if not allowed:+ raise InvalidGrantError(f"IdP {label} URL is not allowed: {reason}")++ if jwks_url:+ _check_url(jwks_url, "JWKS")+ return jwt.PyJWKClient(jwks_url, timeout=10)++ _check_url(issuer, "issuer")+ cache_key = f"id_jag:jwks_uri:{issuer}"+ jwks_uri = cache.get(cache_key)+ if not jwks_uri:+ try:+ resp = requests.get(f"{issuer}/.well-known/openid-configuration", timeout=10, allow_redirects=False)+ resp.raise_for_status()+ metadata = resp.json()+ except requests.RequestException as e:+ raise InvalidGrantError(f"IdP {issuer} OIDC discovery request failed: {e}")+ except ValueError as e:+ # `resp.json()` raises `json.JSONDecodeError` (a ValueError subclass).+ raise InvalidGrantError(f"IdP {issuer} OIDC discovery response was not valid JSON: {e}")+ jwks_uri = metadata.get("jwks_uri")+ if not jwks_uri:+ raise InvalidGrantError(f"IdP {issuer} discovery metadata missing jwks_uri")+ cache.set(cache_key, jwks_uri, settings.ID_JAG_JWKS_CACHE_TTL_SECONDS)++ _check_url(jwks_uri, "discovered JWKS")+ return jwt.PyJWKClient(jwks_uri, timeout=10)+++def _get_sub(provider_name: str, id_jag_sub: str) -> str:+ """+ Returns the `sub` claim in the expected ID-JAG format.++ {identity provider name}:{sub from ID-JAG token}++ Note: The ID-JAG token is the JWT issued by the identity provider which is passed+ in the API request to our django backend to issue a JWT access token to the caller.++ https://xaa.dev/docs/token-structure#sub-claim-format+ """+ return f"{provider_name}:{id_jag_sub}"+++def _get_scopes(id_jag_scopes: list[str], requested_scopes: list[str] | None) -> list[str]:+ """+ Basically just takes the intersection of scopes requested in the caller+ and the scopers granted by the IdP in the ID-JAG token.++ https://xaa.dev/docs/token-structure#scope-intersection-rule++ Per spec, the intersection MAY be empty — the AS still issues a token, which+ then fails at the resource server with `403 insufficient_scope`. We mirror+ that behavior so clients see the documented failure mode, not a 400 here.++ `requested_scopes=None` means the client didn't pass a `scope` param, in+ which case the issued scope is exactly what the ID-JAG authorized. When+ `requested_scopes` is given, the result follows its order so deterministic+ output is stable across calls.+ """+ if requested_scopes is None:+ return list(id_jag_scopes)+ id_jag_set = set(id_jag_scopes)+ seen: set[str] = set()+ intersected: list[str] = []+ for scope in requested_scopes:+ if scope in id_jag_set and scope not in seen:+ seen.add(scope)+ intersected.append(scope)+ return intersected+++def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str, "OrganizationDomain"]:+ """+ Verifies the provided ID-JAG token against the IdP's JWKS and returns the+ claims, the provider name we stamp into the issued access token's `sub`,+ and the `OrganizationDomain` row that owns the trusted IdP config (used to+ bind the issued access token to a single organization).++ Raises `IdJagError` (with the right RFC 6749 error code) on every documented+ failure mode at https://xaa.dev/docs/error-codes+ """+ try:+ header = jwt.get_unverified_header(assertion)+ except jwt.PyJWTError as e:+ raise InvalidGrantError(f"ID-JAG header could not be parsed: {e}")++ if header.get("typ") != ID_JAG_TOKEN_TYPE:+ raise InvalidGrantError(f"ID-JAG typ header is not {ID_JAG_TOKEN_TYPE}")++ try:+ # Intentional: we need `iss` (and `email`/`sub`) to discover which IdP's+ # JWKS to fetch before we can verify the signature — the standard OIDC+ # bootstrap pattern. The verified `jwt.decode(...)` below is the+ # authoritative pass; nothing from `unverified_claims` is trusted past+ # the IdP-config lookup, and the verified pass re-reads every claim we+ # actually act on.+ # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode+ unverified_claims = jwt.decode(assertion, options={"verify_signature": False})+ except jwt.PyJWTError as e:+ raise InvalidGrantError(f"ID-JAG payload could not be parsed: {e}")++ issuer = (unverified_claims.get("iss") or "").rstrip("/")+ if not issuer:+ raise InvalidGrantError("ID-JAG is missing the iss claim")++ id_jag_email = unverified_claims.get("email") or unverified_claims.get("sub") or ""++ org_domain, error = OrganizationDomain.objects.get_verified_for_email_address_and_issuer(id_jag_email, issuer)+ if org_domain is None or error:+ # Do not echo the specific reason — see GENERIC_ID_JAG_REJECTION.+ logger.info(+ "id_jag_token_rejected",+ reason=error or "ID-JAG configuration is invalid",+ issuer=issuer,+ stage="pre_signature_domain_lookup",+ )+ raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)++ expected_issuer = (org_domain.id_jag_issuer_url or "").rstrip("/")+ provider_name = org_domain.domain++ try:+ jwks_client = _get_jwks_client(expected_issuer, jwks_url=org_domain.id_jag_jwks_url or None)+ signing_key = jwks_client.get_signing_key_from_jwt(assertion)+ except jwt.PyJWTError as e:+ raise InvalidGrantError(f"ID-JAG signing key resolution failed: {e}")++ expected_audience = _get_site_url()++ try:+ claims = cast(+ IdJagClaims,+ jwt.decode(+ assertion,+ signing_key.key,+ algorithms=["RS256", "RS384", "RS512"],+ audience=expected_audience,+ leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,+ options={+ "require": ["iss", "sub", "aud", "exp", "iat", "client_id"],+ "verify_signature": True,+ "verify_exp": True,+ "verify_nbf": True,+ "verify_iat": True,+ "verify_aud": True,+ # We verify `iss` manually below so the comparison is+ # trailing-slash-tolerant — PyJWT's built-in check is+ # strict string equality.+ "verify_iss": False,+ },+ ),+ )+ except jwt.ExpiredSignatureError:+ raise InvalidGrantError("ID-JAG has expired")+ except jwt.ImmatureSignatureError as e:+ # PyJWT raises this for both `nbf > now+leeway` and `iat > now+leeway`,+ # and the message disambiguates between them.+ # https://xaa.dev/docs/token-structure#clock-skew-tolerance+ raise InvalidGrantError(f"ID-JAG is not yet valid (clock-skew window exceeded): {e}")+ except jwt.InvalidAudienceError:+ raise InvalidGrantError("ID-JAG aud doesn't match this Auth Server's URL")+ except jwt.MissingRequiredClaimError as e:+ raise InvalidGrantError(f"ID-JAG is missing required claim: {e.claim}")+ except jwt.PyJWTError as e:+ raise InvalidGrantError(f"ID-JAG signature verification failed: {e}")++ claim_issuer = (claims.get("iss") or "").rstrip("/")+ if claim_issuer != expected_issuer:+ # Mirror the pre-signature path so the response surface is uniform.+ logger.info(+ "id_jag_token_rejected",+ reason="ID-JAG iss does not match the IdP configured for this email's domain",+ claim_issuer=claim_issuer,+ expected_issuer=expected_issuer,+ stage="post_signature_iss_check",+ )+ raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)++ resource = claims.get("resource")+ if not resource:+ raise InvalidGrantError("ID-JAG is missing the resource claim (RFC 8707)")+ if resource.rstrip("/") != expected_audience:+ raise InvalidTargetError(f"ID-JAG resource {resource!r} does not match this resource server")++ client_id = claims.get("client_id")+ if not client_id:+ raise InvalidGrantError("ID-JAG is missing the client_id claim")++ # validate allowed clients if set in config+ if org_domain.id_jag_allowed_clients and client_id not in org_domain.id_jag_allowed_clients:+ raise InvalidClientError(f"client_id {client_id!r} is not allowed for this domain")++ # prevent replayed tokens from being used again+ jti = claims.get("jti")+ if jti:+ cache_key = f"id_jag:jti:{expected_issuer}:{jti}"+ exp = int(claims.get("exp") or 0)+ now = int(datetime.now(tz=UTC).timestamp())+ ttl = max(1, exp - now + settings.ID_JAG_CLOCK_SKEW_SECONDS)+ # `cache.add` is SETNX semantics: returns True only if the key was+ # newly created. A False return means we've already seen this jti.+ if not cache.add(cache_key, "1", ttl):+ raise InvalidGrantError("ID-JAG assertion has already been used (jti replay)")+ else:+ logger.info("id_jag_assertion_missing_jti", issuer=expected_issuer)++ # Some IdPs let a user set an arbitrary `email` with `email_verified: false`+ if claims.get("email") is not None and claims.get("email_verified") is False:+ logger.info(+ "id_jag_token_rejected",+ reason="email_not_verified",+ issuer=expected_issuer,+ stage="post_signature_email_verified_check",+ )+ raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)++ verified_email = claims.get("email") or claims.get("sub") or ""++ # The user must be an active member of the *specific* organization whose+ # OrganizationDomain pinned this IdP — not merely a member of any org that+ # also verified this domain. The issued access token is scoped to+ # `org_domain.organization_id` downstream, so membership must be enforced+ # on that exact org.+ is_member = User.objects.filter(+ is_active=True,+ email__iexact=verified_email,+ organization_membership__organization_id=org_domain.organization.pk,+ ).exists()+ if not is_member:+ raise InvalidGrantError(+ "ID-JAG sub is not an active member of the organization that owns this IdP configuration"+ )++ return claims, provider_name, org_domain+++def _construct_access_token_payload(+ claims: IdJagClaims,+ provider_name: str,+ granted_scopes: list[str],+ organization_id: Any,+ verified_email: str,+) -> dict[str, Any]:+ """+ Constructs the payload for the JWT access token which will be issued to the ID-JAG caller.++ https://xaa.dev/docs/token-structure#access-token+ """++ now = datetime.now(tz=UTC)+ expires_at = now + timedelta(seconds=settings.ID_JAG_ACCESS_TOKEN_TTL_SECONDS)++ payload: dict[str, Any] = {+ "iss": _get_site_url(),+ "sub": _get_sub(provider_name, cast(str, claims.get("sub"))),+ "email": verified_email,+ "aud": claims.get("resource"),+ "client_id": claims.get("client_id"),+ "scope": " ".join(granted_scopes),+ "app_org": provider_name,+ "org_id": str(organization_id),+ "jti": str(uuid.uuid4()),+ "iat": int(now.timestamp()),+ "exp": int(expires_at.timestamp()),+ }+ return payload+++def _get_signing_key() -> str:+ """RS256 private key used to sign access tokens. Reuses the OIDC key already+ deployed for OAuth so resource servers can verify access tokens against the+ existing `/.well-known/jwks.json` endpoint without extra wiring."""+ key = getattr(settings, "OIDC_RSA_PRIVATE_KEY", None)+ if not key:+ raise InvalidGrantError(+ "ID-JAG access tokens cannot be signed: OIDC_RSA_PRIVATE_KEY is not configured",+ http_status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ error_code="server_error",+ )+ return key+++def _construct_access_token(payload: dict[str, Any]) -> str:+ return jwt.encode(+ payload,+ _get_signing_key(),+ algorithm="RS256",+ headers={"typ": ACCESS_TOKEN_TYPE},+ )+++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 []+ if isinstance(value, list):+ return [s for s in value if s]+ return [s for s in value.split() if s]+++def issue_access_token(+ assertion: str, requested_scope: str | list[str] | None, request_client_id: str | None+) -> tuple[str, list[str], int]:+ """+ Validate an ID-JAG `assertion` and mint an access token. Pulled out of the+ view so the same path is exercised by tests, batch tools, and the HTTP+ handler. Returns `(access_token, granted_scopes, expires_in_seconds)`.+ """++ claims, provider_name, org_domain = _verify_and_extract_id_jag_token(assertion)++ if request_client_id and request_client_id != claims.get("client_id"):+ raise InvalidGrantError("ID-JAG client_id doesn't match the authenticating client")++ id_jag_scopes = _parse_scope_list(claims.get("scope"))+ parsed_requested = _parse_scope_list(requested_scope) if requested_scope is not None else None++ known_scopes = set(get_oauth_scopes_supported())+ sanitized_id_jag_scopes = [s for s in id_jag_scopes if s in known_scopes]++ granted = _get_scopes(sanitized_id_jag_scopes, parsed_requested)+ verified_email = claims.get("email") or claims.get("sub") or ""+ payload = _construct_access_token_payload(+ claims, provider_name, granted, org_domain.organization.pk, cast(str, verified_email)+ )+ 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/routing.py b/posthog/api/routing.pyindex 8d2eae38610c..e1eda3fad6af 100644--- a/posthog/api/routing.py+++ b/posthog/api/routing.py@@ -12,6 +12,7 @@ from rest_framework_extensions.settings import extensions_api_settingsfrom posthog.api.utils import get_tokenfrom posthog.auth import (+ IDJagAccessTokenAuthentication,InternalAPIAuthentication,JwtAuthentication,OAuthAccessTokenAuthentication,@@ -205,7 +206,18 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):authentication_classes.append(SharingAccessTokenAuthentication)authentication_classes.extend(- [JwtAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication]+ [+ # IDJagAccessTokenAuthentication runs before JwtAuthentication because the latter+ # decodes with HS256+SECRET_KEY and treats algorithm mismatches as hard auth+ # failures (401) rather than "not my token". ID-JAG uses RS256, so it would be+ # rejected before its own authenticator could run. IDJagAccessTokenAuthentication+ # has a strict `typ == "at+jwt"` precheck and cleanly defers for other JWTs.+ IDJagAccessTokenAuthentication,+ JwtAuthentication,+ OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,+ SessionAuthentication,+ ])return [auth() for auth in authentication_classes]diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pynew file mode 100644index 000000000000..0961810e8bd0--- /dev/null+++ b/posthog/api/test/test_id_jag.py@@ -0,0 +1,951 @@+"""+Tests for the ID-JAG token endpoint + the resource-server side+authentication backend.++The strategy is:+ * Generate a throwaway RSA keypair in `setUpClass` and use it to sign a+ synthetic IdP-issued ID-JAG. We patch `posthog.api.id_jag._get_jwks_client`+ to return a `PyJWK` whose `.key` is the matching public key so signature+ verification succeeds without HTTP calls.+ * For access tokens, we use the OIDC private key already configured for OAuth+ by overriding `settings.OIDC_RSA_PRIVATE_KEY` (mirrors the OAuth test suite).+"""++import time+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import override_settings+from django.utils import timezone++import jwt+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa+from rest_framework import status++from posthog.api.id_jag import (+ ACCESS_TOKEN_TYPE,+ ID_JAG_TOKEN_TYPE,+ JWT_BEARER_GRANT_TYPE,+ _get_scopes,+ _get_sub,+ issue_access_token,+)+from posthog.auth import IDJagAccessTokenAuthentication+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.organization_domain import OrganizationDomain+from posthog.models.user import User as UserModel+++def _generate_rsa_pem() -> str:+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ pem = private_key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.TraditionalOpenSSL,+ encryption_algorithm=serialization.NoEncryption(),+ )+ return pem.decode("utf-8")+++# rsa operations are expensive, keep this at the module-level to avoid slow tests+_IDP_PRIVATE_KEY_PEM = _generate_rsa_pem()+_AS_PRIVATE_KEY_PEM = _generate_rsa_pem()++_IDP_ISSUER = "https://idp.example.com"+_VERIFIED_DOMAIN = "example.com"+_PROVIDER_NAME = _VERIFIED_DOMAIN+_SITE_URL = "https://posthog.test"+_AUTH_SERVER_URL = _SITE_URL+_RESOURCE_URL = _SITE_URL+_RESOURCE_CLIENT_ID = "client_abc-at-posthog"+++def _public_key_for(pem: str) -> Any:+ return serialization.load_pem_private_key(pem.encode(), password=None).public_key()+++def _make_id_jag(+ *,+ issuer: str = _IDP_ISSUER,+ sub: str = "[email protected]",+ audience: str = _AUTH_SERVER_URL,+ client_id: str = _RESOURCE_CLIENT_ID,+ resource: str = _RESOURCE_URL,+ scope: str = "feature_flag:read feature_flag:write",+ iat: int | None = None,+ nbf: int | None = None,+ exp_seconds: int = 300,+ typ_header: str = ID_JAG_TOKEN_TYPE,+ extra_claims: dict[str, Any] | None = None,+ signing_pem: str | None = None,+) -> str:+ """Forge a synthetic IdP-issued ID-JAG for the test suite."""++ now = int(time.time())+ payload: dict[str, Any] = {+ "iss": issuer,+ "sub": sub,+ "aud": audience,+ "client_id": client_id,+ "resource": resource,+ "scope": scope,+ "jti": f"id-jag-{now}",+ "iat": iat if iat is not None else now,+ "nbf": nbf if nbf is not None else now,+ "exp": now + exp_seconds,+ }+ if extra_claims:+ payload.update(extra_claims)+ return jwt.encode(+ payload,+ signing_pem or _IDP_PRIVATE_KEY_PEM,+ algorithm="RS256",+ headers={"typ": typ_header, "alg": "RS256"},+ )+++@override_settings(+ OIDC_RSA_PRIVATE_KEY=_AS_PRIVATE_KEY_PEM,+ SITE_URL=_SITE_URL,+ ID_JAG_ACCESS_TOKEN_TTL_SECONDS=300,+ ID_JAG_CLOCK_SKEW_SECONDS=30,+ CORS_ALLOW_ALL_ORIGINS=True,+)+class TestIdJagTokenEndpoint(APIBaseTest):+ CONFIG_AUTO_LOGIN = False++ @classmethod+ def setUpTestData(cls) -> None:+ super().setUpTestData()+ cls.user.email = "[email protected]"+ cls.user.save()+ OrganizationDomain.objects.create(+ organization=cls.organization,+ domain=_VERIFIED_DOMAIN,+ verified_at=timezone.now(),+ id_jag_issuer_url=_IDP_ISSUER,+ )++ def setUp(self) -> None:+ super().setUp()++ # Stub the JWKS fetch so PyJWKClient resolves to our test public key+ # without hitting the network. `get_signing_key_from_jwt` is the only+ # surface area we use.+ signing_key = MagicMock()+ signing_key.key = _public_key_for(_IDP_PRIVATE_KEY_PEM)+ mock_jwks_client = MagicMock()+ mock_jwks_client.get_signing_key_from_jwt.return_value = signing_key++ self._jwks_patch = patch("posthog.api.id_jag._get_jwks_client", return_value=mock_jwks_client)+ self._jwks_patch.start()+ 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")++ def test_issues_access_token_for_valid_id_jag(self) -> None:+ assertion = _make_id_jag()+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})++ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ body = resp.json()+ self.assertEqual(body["token_type"], "Bearer")+ self.assertEqual(body["expires_in"], 300)+ self.assertEqual(set(body["scope"].split()), {"feature_flag:read", "feature_flag:write"})++ claims = jwt.decode(+ body["access_token"],+ _public_key_for(_AS_PRIVATE_KEY_PEM),+ algorithms=["RS256"],+ audience=_RESOURCE_URL,+ issuer=_AUTH_SERVER_URL,+ )+ self.assertEqual(claims["sub"], f"{_PROVIDER_NAME}:[email protected]")+ self.assertEqual(claims["aud"], _RESOURCE_URL)+ self.assertEqual(claims["client_id"], _RESOURCE_CLIENT_ID)+ self.assertEqual(claims["app_org"], _PROVIDER_NAME)+ self.assertIn("jti", claims)+ self.assertIn("iat", claims)+ self.assertIn("exp", claims)++ header = jwt.get_unverified_header(body["access_token"])+ self.assertEqual(header["typ"], ACCESS_TOKEN_TYPE)+ self.assertEqual(header["alg"], "RS256")++ 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+ # stable identifier. When the `email` claim is present we should use it+ # for domain verification and membership lookup; `sub` is still stamped+ # into the issued access token as the subject identifier.+ opaque_sub = "auth0|abc123"+ assertion = _make_id_jag(sub=opaque_sub, extra_claims={"email": "[email protected]"})+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})++ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ claims = jwt.decode(+ resp.json()["access_token"],+ _public_key_for(_AS_PRIVATE_KEY_PEM),+ algorithms=["RS256"],+ audience=_RESOURCE_URL,+ issuer=_AUTH_SERVER_URL,+ )+ # The stamped sub preserves the IdP's opaque identifier; the resolved+ # PostHog user identity is stamped separately into `email` so the+ # resource-side authenticator can find the User row without trying to+ # parse an email out of `sub`.+ self.assertEqual(claims["sub"], f"{_PROVIDER_NAME}:{opaque_sub}")+ self.assertEqual(claims["email"], "[email protected]")++ def test_round_trip_with_opaque_sub_authenticates_on_resource_side(self) -> None:+ # Regression: opaque-sub IdPs (Okta, Auth0, Entra) emit `sub` values+ # 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/.+ assertion = _make_id_jag(+ sub="auth0|opaque-id-abc123",+ scope="user:read",+ extra_claims={"email": "[email protected]", "email_verified": True},+ )+ issue_resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(issue_resp.status_code, status.HTTP_200_OK, issue_resp.content)+ access_token = issue_resp.json()["access_token"]++ api_resp = self.client.get("/api/users/@me/", HTTP_AUTHORIZATION=f"Bearer {access_token}")+ self.assertEqual(api_resp.status_code, status.HTTP_200_OK, api_resp.content)+ self.assertEqual(api_resp.json()["email"], "[email protected]")++ def test_rejects_when_email_claim_is_explicitly_unverified(self) -> None:+ # OIDC Core §5.1 — the `email` claim is mutable; only the IdP's+ # `email_verified` boolean signals ownership. Without this gate, a+ # user authenticated under their own `sub` could set the `email`+ # claim to a victim's address and slip past the membership check.+ assertion = _make_id_jag(+ sub="auth0|attacker",+ extra_claims={"email": "[email protected]", "email_verified": False},+ )+ 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(resp.json()["error_description"], "ID-JAG could not be verified")++ def test_accepts_when_email_verified_is_true(self) -> None:+ assertion = _make_id_jag(+ sub="auth0|abc123",+ extra_claims={"email": "[email protected]", "email_verified": True},+ )+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ def test_accepts_when_email_verified_is_omitted(self) -> None:+ # Many valid IdPs (notably Okta in some configs) omit `email_verified`+ # rather than emitting `true`. Requiring it true would break them, so+ # we only reject the explicit-false case.+ assertion = _make_id_jag(+ sub="auth0|abc123",+ extra_claims={"email": "[email protected]"},+ )+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ def test_email_verified_false_is_ignored_when_no_email_claim_is_present(self) -> None:+ # The gate only matters when we're about to trust the `email` claim.+ # If the IdP didn't send one, the membership lookup falls back to+ # `sub` and `email_verified: false` is irrelevant.+ assertion = _make_id_jag(+ sub="[email protected]",+ extra_claims={"email_verified": False},+ )+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ def test_rejects_when_email_claim_domain_is_not_verified(self) -> None:+ # When the `email` claim is present it takes precedence — a verified-+ # domain email in `sub` should not rescue an unverified `email` claim.+ assertion = _make_id_jag(+ sub="[email protected]",+ extra_claims={"email": "[email protected]"},+ )+ 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(resp.json()["error_description"], "ID-JAG could not be verified")++ def test_intersection_with_requested_scope(self) -> None:+ assertion = _make_id_jag(scope="feature_flag:read feature_flag:write dashboard:read")+ resp = self._post_token(+ {+ "grant_type": JWT_BEARER_GRANT_TYPE,+ "assertion": assertion,+ "scope": "feature_flag:read dashboard:write",+ }+ )+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ # Only feature_flag:read intersects — dashboard:write was not in ID-JAG.+ self.assertEqual(resp.json()["scope"], "feature_flag:read")++ def test_empty_intersection_still_issues_token(self) -> None:+ """https://xaa.dev/docs/token-structure#scope-intersection-rule++ The AS issues a token with empty scope; the resource server is the one+ that denies with 403 insufficient_scope.+ """+ assertion = _make_id_jag(scope="feature_flag:read")+ resp = self._post_token(+ {+ "grant_type": JWT_BEARER_GRANT_TYPE,+ "assertion": assertion,+ "scope": "dashboard:read",+ }+ )+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ self.assertEqual(resp.json()["scope"], "")++ def test_unknown_scopes_in_id_jag_are_dropped(self) -> None:+ """We never propagate scope strings we don't recognize as PostHog scopes —+ otherwise a malformed IdP could smuggle arbitrary tokens into requests."""+ assertion = _make_id_jag(scope="feature_flag:read totally_bogus:thing")+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ 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(+ "/id-jag/token",+ data=urlencode({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion}),+ content_type="application/x-www-form-urlencoded",+ )+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ 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(+ "/id-jag/token",+ data=urlencode({"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)++ 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(+ "/id-jag/token",+ data=urlencode(+ {+ "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)+ 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={},+ content_type="application/json",+ HTTP_ORIGIN="https://example.com",+ )+ self.assertEqual(bad.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("Access-Control-Allow-Origin", bad.headers)++ def test_cors_preflight(self) -> None:+ # Preflight (OPTIONS) needs to succeed before browsers will send the+ # actual POST. The CORS middleware short-circuits this when the path+ # matches `CORS_URLS_REGEX`.+ resp = self.client.options(+ "/id-jag/token",+ HTTP_ORIGIN="https://example.com",+ HTTP_ACCESS_CONTROL_REQUEST_METHOD="POST",+ HTTP_ACCESS_CONTROL_REQUEST_HEADERS="content-type",+ )+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ self.assertIn("Access-Control-Allow-Origin", resp.headers)+ 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})+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)+ body = resp.json()+ self.assertEqual(body["error"], "invalid_grant")+ self.assertIn(ID_JAG_TOKEN_TYPE, body["error_description"])++ def test_rejects_unverified_domain_in_sub(self) -> None:+ # Trust is rooted in the verified-domain → org mapping. An ID-JAG whose+ # `sub` doesn't belong to a verified domain on any PostHog org is+ # rejected with the uniform pre-signature error so we don't leak which+ # domains a tenant has verified.+ assertion = _make_id_jag(sub="[email protected]")+ 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(resp.json()["error_description"], "ID-JAG could not be verified")++ def test_rejects_when_no_matching_user_exists(self) -> None:+ # Domain is verified but no User row exists for the sub email — fail+ # fast at issuance so we don't mint a token that 401s on every API call.+ assertion = _make_id_jag(sub="[email protected]")+ 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.assertIn("active member", resp.json()["error_description"])++ def test_rejects_when_user_is_inactive(self) -> None:+ # An existing user that has been deactivated should not be able to+ # receive a token via ID-JAG.+ self.user.is_active = False+ self.user.save()+ try:+ assertion = _make_id_jag()+ 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.assertIn("active member", resp.json()["error_description"])+ finally:+ self.user.is_active = True+ self.user.save()++ def test_rejects_when_user_belongs_to_different_org(self) -> None:+ # Cross-org attack: attacker's org verifies a domain, then tries to mint+ # tokens for users at that domain who actually belong to a DIFFERENT+ # org. With the org-membership check, signature + domain verification+ # alone is not enough — the user must belong to the org that owns the+ # verified domain.++ attacker_org = Organization.objects.create(name="attacker-org")+ OrganizationDomain.objects.create(+ organization=attacker_org,+ domain="bigco.example",+ verified_at=timezone.now(),+ id_jag_issuer_url=_IDP_ISSUER,+ )++ # Victim user whose email is on the attacker's verified domain but who+ # belongs to a completely unrelated org.+ unrelated_org = Organization.objects.create(name="unrelated-org")+ victim = UserModel.objects.create_user(+ email="[email protected]",+ password="x",+ first_name="V",+ )+ OrganizationMembership.objects.create(organization=unrelated_org, user=victim)++ assertion = _make_id_jag(sub="[email protected]")+ 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.assertIn("active member", resp.json()["error_description"])++ def test_rejects_signature_from_unrecognized_key(self) -> None:+ other_pem = _generate_rsa_pem()+ assertion = _make_id_jag(signing_pem=other_pem)+ 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")++ def test_rejects_expired_id_jag(self) -> None:+ assertion = _make_id_jag(exp_seconds=-60)+ 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.assertIn("expired", resp.json()["error_description"].lower())++ def test_rejects_nbf_in_future(self) -> None:+ future = int(time.time()) + 120 # past the 30s leeway+ assertion = _make_id_jag(nbf=future)+ 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.assertIn("not yet valid", resp.json()["error_description"].lower())++ def test_rejects_iat_in_future_beyond_skew(self) -> None:+ future = int(time.time()) + 120+ # PyJWT validates iat in the future beyond `leeway` as+ # ImmatureSignatureError (https://pyjwt.readthedocs.io/) — we just need+ # to confirm the error surfaces as invalid_grant per ID-JAG spec.+ assertion = _make_id_jag(iat=future, nbf=future - 200)+ 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")++ def test_accepts_iat_in_future_within_skew(self) -> None:+ future = int(time.time()) + 10 # within 30s skew+ assertion = _make_id_jag(iat=future, nbf=future - 200)+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ def test_rejects_aud_mismatch(self) -> None:+ assertion = _make_id_jag(audience="https://different-as.example.com")+ 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")++ def test_rejects_missing_required_claims(self) -> None:+ assertion = jwt.encode(+ {+ "iss": _IDP_ISSUER,+ "sub": "[email protected]",+ "aud": _AUTH_SERVER_URL,+ # client_id intentionally missing+ "resource": _RESOURCE_URL,+ "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},+ )+ 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")++ def test_rejects_request_client_id_mismatch(self) -> None:+ assertion = _make_id_jag(client_id="client_abc-at-posthog")+ resp = self._post_token(+ {+ "grant_type": JWT_BEARER_GRANT_TYPE,+ "assertion": assertion,+ "client_id": "client_DIFFERENT-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.+ assertion = _make_id_jag(client_id="client_anything-at-posthog")+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ body = resp.json()+ claims = jwt.decode(+ body["access_token"],+ _public_key_for(_AS_PRIVATE_KEY_PEM),+ algorithms=["RS256"],+ audience=_RESOURCE_URL,+ issuer=_AUTH_SERVER_URL,+ )+ self.assertEqual(claims["client_id"], "client_anything-at-posthog")++ def test_rejects_resource_not_matching_site_url(self) -> None:+ assertion = _make_id_jag(resource="https://other-resource.example.com")+ 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_target")++ def test_rejects_when_domain_has_no_id_jag_issuer_configured(self) -> None:+ # ID-JAG is opt-in per domain. With `id_jag_issuer_url` cleared, an+ # otherwise valid ID-JAG must be rejected — the org hasn't bound an IdP yet.+ domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)+ domain.id_jag_issuer_url = None+ domain.save(update_fields=["id_jag_issuer_url"])++ assertion = _make_id_jag()+ 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")+ # Uniform response — the specific reason (id_jag_issuer_url unset) must+ # not be echoed to unauthenticated callers; it's logged for ops only.+ self.assertEqual(resp.json()["error_description"], "ID-JAG could not be verified")++ def test_rejects_when_id_jag_iss_does_not_match_domain_issuer(self) -> None:+ # The IdP binding is exact-match on the issuer URL — even a sibling IdP+ # that happens to know the same user is rejected unless explicitly bound.+ domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)+ domain.id_jag_issuer_url = "https://idp.example.com"+ domain.save(update_fields=["id_jag_issuer_url"])++ assertion = _make_id_jag(issuer="https://other-idp.example.com")+ 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")+ # Uniform response — do not disclose that the IdP issuer is wrong vs.+ # that the domain isn't bound at all.+ self.assertEqual(resp.json()["error_description"], "ID-JAG could not be verified")++ def test_issuer_match_is_slash_normalized(self) -> None:+ # Store the issuer without trailing slash; ID-JAG carries one. The+ # comparison must succeed because we rstrip on both sides — otherwise+ # legitimate IdPs that always include a trailing slash on `iss` would+ # be impossible to bind.+ domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)+ domain.id_jag_issuer_url = _IDP_ISSUER+ domain.save(update_fields=["id_jag_issuer_url"])++ assertion = _make_id_jag(issuer=_IDP_ISSUER + "/")+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ def test_custom_jwks_url_is_passed_to_jwks_client(self) -> None:+ # When `id_jag_jwks_url` is set on the domain, we skip OIDC discovery and+ # point PyJWKClient at the explicit URL. We assert by inspecting the+ # arguments passed to `_get_jwks_client` rather than reasserting the+ # signature (the mock already returns our test public key).+ domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)+ domain.id_jag_jwks_url = "https://idp.example.com/keys.json"+ domain.save(update_fields=["id_jag_jwks_url"])++ # Re-patch to capture call args; the base setUp patch doesn't expose+ # them in a way that survives across multiple tests.+ signing_key = MagicMock()+ signing_key.key = _public_key_for(_IDP_PRIVATE_KEY_PEM)+ mock_jwks_client = MagicMock()+ mock_jwks_client.get_signing_key_from_jwt.return_value = signing_key+ with patch("posthog.api.id_jag._get_jwks_client", return_value=mock_jwks_client) as mock_get:+ assertion = _make_id_jag()+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ mock_get.assert_called_once()+ _, kwargs = mock_get.call_args+ self.assertEqual(kwargs.get("jwks_url"), "https://idp.example.com/keys.json")++ def test_allowed_clients_permits_listed_client_id(self) -> None:+ domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)+ domain.id_jag_allowed_clients = ["client_first", "client_second"]+ domain.save(update_fields=["id_jag_allowed_clients"])++ assertion = _make_id_jag(client_id="client_second")+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, status.HTTP_200_OK)++ def test_allowed_clients_rejects_unlisted_client_id(self) -> None:+ domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)+ domain.id_jag_allowed_clients = ["client_first", "client_second"]+ domain.save(update_fields=["id_jag_allowed_clients"])++ assertion = _make_id_jag(client_id="client_third")+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ 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},+ )+ 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")++ def test_get_sub_format(self) -> None:+ self.assertEqual(_get_sub("example.com", "[email protected]"), "example.com:[email protected]")++ def test_get_scopes_intersection(self) -> None:+ self.assertEqual(_get_scopes(["a", "b", "c"], ["b", "c", "d"]), ["b", "c"])+ # Order follows the requested list.+ self.assertEqual(_get_scopes(["a", "b", "c"], ["c", "a"]), ["c", "a"])+ # No requested scope means we issue exactly what the ID-JAG authorized.+ self.assertEqual(_get_scopes(["a", "b"], None), ["a", "b"])+ # Empty intersection returns [] (token still issues per spec).+ self.assertEqual(_get_scopes(["a"], ["b"]), [])++ def test_issue_access_token_helper(self) -> None:+ assertion = _make_id_jag()+ token, granted, expires_in = issue_access_token(+ assertion, requested_scope="feature_flag:read", request_client_id=_RESOURCE_CLIENT_ID+ )+ self.assertEqual(granted, ["feature_flag:read"])+ self.assertEqual(expires_in, 300)+ # Token decodable with the AS public key.+ jwt.decode(+ token,+ _public_key_for(_AS_PRIVATE_KEY_PEM),+ algorithms=["RS256"],+ audience=_RESOURCE_URL,+ issuer=_AUTH_SERVER_URL,+ )+++@override_settings(+ OIDC_RSA_PRIVATE_KEY=_AS_PRIVATE_KEY_PEM,+ SITE_URL=_SITE_URL,+ ID_JAG_ACCESS_TOKEN_TTL_SECONDS=300,+ ID_JAG_CLOCK_SKEW_SECONDS=30,+)+class TestIDJagAccessTokenAuthentication(APIBaseTest):+ """Resource-server side: verify inbound access tokens authenticate the+ matching user and surface the scope claim for downstream permission checks.+ """++ CONFIG_AUTO_LOGIN = False++ def setUp(self) -> None:+ super().setUp()+ self.user.email = "[email protected]"+ self.user.save()++ def _mint_access_token(+ self,+ *,+ sub: str | None = None,+ email: str | None = None,+ aud: str = _RESOURCE_URL,+ iss: str = _AUTH_SERVER_URL,+ scope: str = "feature_flag:read",+ client_id: str = _RESOURCE_CLIENT_ID,+ exp_seconds: int = 300,+ typ_header: str = ACCESS_TOKEN_TYPE,+ signing_pem: str | None = None,+ extra_claims: dict[str, Any] | None = None,+ ) -> str:+ now = int(time.time())+ payload: dict[str, Any] = {+ "iss": iss,+ "sub": sub if sub is not None else f"{_PROVIDER_NAME}:{self.user.email}",+ "email": email if email is not None else self.user.email,+ "aud": aud,+ "client_id": client_id,+ "scope": scope,+ "app_org": _PROVIDER_NAME,+ "org_id": str(self.organization.id),+ "iat": now,+ "exp": now + exp_seconds,+ "jti": f"at-{now}",+ }+ if extra_claims:+ payload.update(extra_claims)+ return jwt.encode(+ payload,+ signing_pem or _AS_PRIVATE_KEY_PEM,+ algorithm="RS256",+ headers={"typ": typ_header},+ )++ def _call_authenticated(self, token: str) -> Any:+ return self.client.get("/api/users/@me/", HTTP_AUTHORIZATION=f"Bearer {token}")++ def test_valid_token_authenticates_user(self) -> None:+ token = self._mint_access_token(scope="user:read")+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertEqual(resp.json()["email"], self.user.email)++ def test_scope_claim_drives_permission(self) -> None:+ # `user:read` is the scope needed for /api/users/@me/.+ ok = self._mint_access_token(scope="user:read")+ self.assertEqual(self._call_authenticated(ok).status_code, status.HTTP_200_OK)++ # Empty scope → no access at any resource endpoint.+ empty = self._mint_access_token(scope="")+ self.assertEqual(self._call_authenticated(empty).status_code, status.HTTP_403_FORBIDDEN)++ # Wrong scope → permission denied (403).+ wrong = self._mint_access_token(scope="feature_flag:read")+ self.assertEqual(self._call_authenticated(wrong).status_code, status.HTTP_403_FORBIDDEN)++ def test_expired_token_rejected(self) -> None:+ token = self._mint_access_token(exp_seconds=-60, scope="user:read")+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_wrong_audience_rejected(self) -> None:+ token = self._mint_access_token(aud="https://different-resource.example.com", scope="user:read")+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_wrong_issuer_rejected(self) -> None:+ token = self._mint_access_token(iss="https://attacker.example.com", scope="user:read")+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_invalid_signature_rejected(self) -> None:+ other_pem = _generate_rsa_pem()+ token = self._mint_access_token(scope="user:read", signing_pem=other_pem)+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_missing_required_claim_rejected(self) -> None:+ # Hand-craft without `scope`+ now = int(time.time())+ payload = {+ "iss": _AUTH_SERVER_URL,+ "sub": f"{_PROVIDER_NAME}:{self.user.email}",+ "aud": _RESOURCE_URL,+ "client_id": _RESOURCE_CLIENT_ID,+ # scope intentionally missing+ "iat": now,+ "exp": now + 300,+ }+ token = jwt.encode(payload, _AS_PRIVATE_KEY_PEM, algorithm="RS256", headers={"typ": ACCESS_TOKEN_TYPE})+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_unknown_user_email_rejected(self) -> None:+ token = self._mint_access_token(+ sub=f"{_PROVIDER_NAME}:[email protected]",+ email="[email protected]",+ scope="user:read",+ )+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_opaque_sub_with_email_claim_authenticates_user(self) -> None:+ # OIDC IdPs (Okta, Auth0, Entra) emit opaque `sub` values — the user's+ # PostHog identity is in the separate `email` claim. The resource-side+ # authenticator must key off `email`, not the userSub half of `sub`.+ token = self._mint_access_token(+ sub=f"{_PROVIDER_NAME}:auth0|opaque-id-abc123",+ email=self.user.email,+ scope="user:read",+ )+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertEqual(resp.json()["email"], self.user.email)++ def test_missing_email_claim_rejected(self) -> None:+ # `email` is the authenticated identity — a token without it must not+ # fall back to parsing `sub` for an email.+ now = int(time.time())+ payload = {+ "iss": _AUTH_SERVER_URL,+ "sub": f"{_PROVIDER_NAME}:{self.user.email}",+ # email intentionally missing+ "aud": _RESOURCE_URL,+ "client_id": _RESOURCE_CLIENT_ID,+ "scope": "user:read",+ "org_id": str(self.organization.id),+ "iat": now,+ "exp": now + 300,+ }+ token = jwt.encode(payload, _AS_PRIVATE_KEY_PEM, algorithm="RS256", headers={"typ": ACCESS_TOKEN_TYPE})+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_malformed_sub_claim_rejected(self) -> None:+ token = self._mint_access_token(sub="no_provider_prefix", scope="user:read")+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_non_id_jag_jwt_passes_through(self) -> None:+ """A JWT without `typ: at+jwt` must not be claimed by ID-JAG auth — it+ could be e.g. a sharing JWT handled by another backend."""+ now = int(time.time())+ non_id_jag = jwt.encode(+ {"sub": "x", "iat": now, "exp": now + 60},+ _AS_PRIVATE_KEY_PEM,+ algorithm="RS256",+ headers={"typ": "JWT"},+ )+ auth = IDJagAccessTokenAuthentication()+ from unittest.mock import Mock++ req = Mock()+ req.headers = {"authorization": f"Bearer {non_id_jag}"}+ self.assertIsNone(auth.authenticate(req))++ def test_personal_api_key_prefix_passes_through(self) -> None:+ auth = IDJagAccessTokenAuthentication()+ from unittest.mock import Mock++ for prefix in ("phx_abc", "pha_abc", "phs_abc"):+ req = Mock()+ req.headers = {"authorization": f"Bearer {prefix}"}+ self.assertIsNone(auth.authenticate(req))++ def test_no_authorization_header_passes_through(self) -> None:+ auth = IDJagAccessTokenAuthentication()+ from unittest.mock import Mock++ req = Mock()+ req.headers = {}+ self.assertIsNone(auth.authenticate(req))++ def test_routing_mixin_endpoint_authenticates_before_jwt_authentication(self) -> None:+ """Regression test: viewsets that inherit the routing mixin (e.g.+ `/api/projects/@current/`) get a default authenticator chain that+ includes `JwtAuthentication` ahead of other token-based backends.++ `JwtAuthentication.decode_jwt` hard-codes HS256+SECRET_KEY and raises+ `AuthenticationFailed` (→ 401) on any non-`jwt.DecodeError` exception,+ including the `InvalidAlgorithmError` that fires for an RS256 ID-JAG+ access token. If `IDJagAccessTokenAuthentication` doesn't run first,+ valid ID-JAG tokens get a 401 on every routing-mixin-based endpoint+ and never reach the resource server's scope check.++ Hitting `/api/projects/@current/` with a `project:read` ID-JAG token+ must return 200 — not 401.+ """+ token = self._mint_access_token(scope="project:read")+ resp = self.client.get(f"/api/projects/@current/", HTTP_AUTHORIZATION=f"Bearer {token}")+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertEqual(resp.json()["id"], self.team.id)diff --git a/posthog/api/user.py b/posthog/api/user.pyindex dbd7069af7f4..897f423758cc 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -60,6 +60,7 @@ from posthog.api.services.flags_service import get_flags_from_servicefrom posthog.api.shared import OrganizationBasicSerializer, TeamBasicSerializerfrom posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action, unparsed_hostname_in_allowed_url_listfrom posthog.auth import (+ IDJagAccessTokenAuthentication,OAuthAccessTokenAuthentication,PersonalAPIKeyAuthentication,SessionAuthentication,@@ -800,9 +801,10 @@ class UserViewSet(throttle_classes = [UserAuthenticationThrottle]serializer_class = UserSerializerauthentication_classes = [+ IDJagAccessTokenAuthentication,SessionAuthentication,- PersonalAPIKeyAuthentication,OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,]permission_classes = [IsAuthenticated,diff --git a/posthog/auth.py b/posthog/auth.pyindex 81e35d97d5f2..0082e2c03658 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -31,7 +31,7 @@ from zxcvbn import zxcvbnfrom posthog.clickhouse.query_tagging import tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.helpers.two_factor_session import enforce_two_factor-from posthog.jwt import PosthogJwtAudience, decode_jwt+from posthog.jwt import PosthogJwtAudience, decode_jwt, get_oidc_public_keyfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrandfrom posthog.models.personal_api_key import (LEGACY_PERSONAL_API_KEY_SALT,@@ -446,6 +446,171 @@ class JwtAuthentication(authentication.BaseAuthentication):return cls.keyword+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+ 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+ https://xaa.dev/docs/token-structure#sub-claim-format).++ Scope enforcement lives in `posthog.permissions.APIScopePermission`; this+ class only handles signature + claim validation and user resolution.+ """++ _ID_JAG_ACCESS_TOKEN_TYPE = "at+jwt"++ keyword = "Bearer"++ id_jag_claims: dict[str, Any]+ scopes: list[str]+ organization_id: str++ @classmethod+ def _extract_token(cls, request: Union[HttpRequest, Request]) -> Optional[str]:+ auth_header = request.headers.get("authorization")+ if not auth_header:+ return None+ match = re.match(rf"^{cls.keyword}\s+(\S.+)$", auth_header)+ if not match:+ return None+ token = match.group(1).strip()++ return token++ @classmethod+ def _parse_sub(cls, sub: str) -> Optional[tuple[str, str]]:+ """`{providerName}:{userSub}` per spec — split into (provider, user_sub).++ Returns None if the format is malformed (no colon, empty provider, empty+ user_sub) so the caller can fail with `invalid_token`.+ """+ if not sub or ":" not in sub:+ return None+ provider, user_sub = sub.split(":", 1)+ if not provider or not user_sub:+ return None+ return provider, user_sub++ @classmethod+ def _is_id_jag_token(cls, token: str) -> bool:+ # Personal/OAuth API key prefixes are reserved for those auth backends.+ if token.startswith(("phx_", "pha_", "phs_")):+ return False++ if token.count(".") != 2:+ return False+ try:+ header = jwt.get_unverified_header(token)+ except jwt.PyJWTError:+ return False+ return header.get("typ") == cls._ID_JAG_ACCESS_TOKEN_TYPE++ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:+ with tracer.start_as_current_span("posthog.auth.id_jag"):+ token = self._extract_token(request)+ if not token:+ return None+ if not self._is_id_jag_token(token):+ return None++ public_key = get_oidc_public_key()+ if public_key is None:+ raise AuthenticationFailed(detail="ID-JAG access tokens are not configured on this server.")++ site_url = (settings.SITE_URL or "").rstrip("/")+ if not site_url:+ raise AuthenticationFailed(detail="ID-JAG access tokens are not configured on this server.")++ try:+ claims = jwt.decode(+ token,+ public_key,+ algorithms=["RS256"],+ audience=site_url,+ issuer=site_url,+ leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,+ options={+ "require": [+ "iss",+ "sub",+ "email",+ "aud",+ "exp",+ "iat",+ "client_id",+ "scope",+ "org_id",+ ],+ "verify_signature": True,+ "verify_exp": True,+ "verify_aud": True,+ "verify_iss": True,+ },+ )+ except jwt.ExpiredSignatureError:+ raise AuthenticationFailed(detail="ID-JAG access token has expired.")+ except jwt.InvalidAudienceError:+ raise AuthenticationFailed(detail="ID-JAG access token audience does not match this resource server.")+ except jwt.InvalidIssuerError:+ raise AuthenticationFailed(detail="ID-JAG access token has an unexpected issuer.")+ except jwt.MissingRequiredClaimError as e:+ raise AuthenticationFailed(detail=f"ID-JAG access token is missing required claim: {e.claim}.")+ except jwt.PyJWTError:+ raise AuthenticationFailed(detail="ID-JAG access token is invalid.")++ sub_parts = self._parse_sub(str(claims.get("sub", "")))+ if sub_parts is None:+ raise AuthenticationFailed(+ detail="ID-JAG access token sub claim is not in the expected '{provider}:{userSub}' format."+ )++ organization_id = str(claims.get("org_id") or "")+ if not organization_id:+ raise AuthenticationFailed(detail="ID-JAG access token is missing the org_id claim.")++ token_email = str(claims.get("email") or "")+ if not token_email:+ raise AuthenticationFailed(detail="ID-JAG access token is missing the email claim.")++ # Resolve the user by (email, org_id) so the token only authenticates+ # against the specific organization it was minted for. This prevents+ # a token from authenticating as another user that happens to share+ # the email, and re-validates membership at every request (the user+ # may have been removed from the org after the token was issued).+ user_qs = User.objects.filter(+ is_active=True,+ email__iexact=token_email,+ organization_membership__organization_id=organization_id,+ ).distinct()+ users = list(user_qs[:2])+ if not users:+ raise AuthenticationFailed(+ detail="No active PostHog user matches the ID-JAG access token subject for this organization."+ )+ if len(users) > 1:+ raise AuthenticationFailed(+ detail="ID-JAG access token resolves to multiple users; refusing to authenticate."+ )+ user = users[0]++ self.id_jag_claims = claims+ self.scopes = str(claims.get("scope") or "").split()+ self.organization_id = organization_id++ tag_queries(+ user_id=user.pk,+ team_id=user.current_team_id,+ access_method="id_jag",+ )++ return user, None++ def authenticate_header(self, request) -> str:+ return self.keyword++class ExportRendererAuthentication(authentication.BaseAuthentication):"""Scoped JWT auth for the export renderer. Only accepted on viewsets that opt in.diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex aeefabb3af63..f1b988126fa5 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -27,6 +27,7 @@ class AccessMethod(StrEnum):PERSONAL_API_KEY = "personal_api_key"OAUTH = "oauth"SHARING_TOKEN = "sharing_token"+ ID_JAG = "id_jag"class Product(StrEnum):diff --git a/posthog/jwt.py b/posthog/jwt.pyindex a20376f518b6..96a640d45aab 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -5,6 +5,7 @@ from typing import Anyfrom django.conf import settingsimport jwt+from cryptography.hazmat.primitives import serializationclass PosthogJwtAudience(Enum):@@ -40,3 +41,17 @@ def decode_jwt(token: str, audience: PosthogJwtAudience) -> dict[str, Any]:info = jwt.decode(token, settings.SECRET_KEY, audience=audience.value, algorithms=["HS256"])return info+++def get_oidc_public_key() -> Any:+ """Derive the verification key from the configured OIDC RSA private key.++ We don't memoize because the PEM is parsed once per request and parsing+ is cheap (~ tens of microseconds); caching would risk staleness on+ in-process key rotation.+ """+ pem = getattr(settings, "OIDC_RSA_PRIVATE_KEY", None)+ if not pem:+ return None+ private_key = serialization.load_pem_private_key(pem.encode(), password=None)+ return private_key.public_key()diff --git a/posthog/migrations/1192_id_jag_organization_domain_fields.py b/posthog/migrations/1192_id_jag_organization_domain_fields.pynew file mode 100644index 000000000000..236a8487044b--- /dev/null+++ b/posthog/migrations/1192_id_jag_organization_domain_fields.py@@ -0,0 +1,45 @@+# Generated by Django 5.2.14 on 2026-05-25 12:40++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1191_delete_relationless_subscriptions"),+ ]++ operations = [+ migrations.AddField(+ model_name="organizationdomain",+ name="id_jag_allowed_clients",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=256),+ blank=True,+ default=list,+ null=True,+ help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ size=None,+ ),+ ),+ migrations.AddField(+ model_name="organizationdomain",+ name="id_jag_issuer_url",+ field=models.CharField(+ blank=True,+ help_text="Trusted IdP issuer URL for ID-JAG. Required to enable ID-JAG on this domain.",+ max_length=512,+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="organizationdomain",+ name="id_jag_jwks_url",+ field=models.CharField(+ blank=True,+ help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ max_length=512,+ null=True,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex b34f5af4145d..2d525e19cf70 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1191_delete_relationless_subscriptions+1192_id_jag_organization_domain_fieldsdiff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.pyindex 19954ad52050..fae68a87a739 100644--- a/posthog/models/organization_domain.py+++ b/posthog/models/organization_domain.py@@ -1,6 +1,7 @@import secretsfrom typing import Optional+from django.contrib.postgres.fields import ArrayFieldfrom django.db import modelsfrom django.utils import timezone@@ -33,6 +34,47 @@ class OrganizationDomainManager(models.Manager):domain = email[email.index("@") + 1 :]return self.verified_domains().filter(domain__iexact=domain).first()+ def get_verified_for_email_address_and_issuer(+ self, email: str, issuer: str+ ) -> tuple[Optional["OrganizationDomain"], Optional[str]]:+ """+ Resolve the `OrganizationDomain` that should authorize an ID-JAG+ assertion for `email` signed by `issuer`. Returns+ `(org_domain, error)` where `error` is `None` on success or a+ human-readable description of the failure mode otherwise.++ Lookup is by `(domain, issuer)` (not `.first()`) so the chosen org is+ deterministic and cannot be steered by row ordering when multiple+ organizations have verified the same domain. The returned org is the+ one whose IdP signed the assertion — callers should scope the issued+ access token to that org and require user membership there.+ """+ if "@" not in email:+ return None, "ID-JAG sub email domain is not a verified domain for any PostHog organization"+ domain = email[email.index("@") + 1 :].lower()+ normalized_issuer = (issuer or "").rstrip("/")++ verified_for_domain = list(self.verified_domains().filter(domain__iexact=domain))+ if not verified_for_domain:+ return None, "ID-JAG sub email domain is not a verified domain for any PostHog organization"++ configured = [d for d in verified_for_domain if (d.id_jag_issuer_url or "").rstrip("/")]+ if not configured:+ return None, "ID-JAG is not configured for this domain (id_jag_issuer_url is unset)"++ matching = [d for d in configured if (d.id_jag_issuer_url or "").rstrip("/") == normalized_issuer]+ if not matching:+ return None, "ID-JAG iss does not match the IdP configured for this email's domain"++ if len(matching) > 1:+ # Ambiguous config — multiple orgs verified the same domain AND+ # configured the same IdP issuer. This is a case that will rqeuire+ # manual intervention to resolve since it is not clear if one of+ # or both of the org domains are valid+ return None, "ID-JAG configuration is ambiguous: multiple OrganizationDomains share this (domain, issuer)"++ return matching[0], None+def get_is_saml_available_for_email(self, email: str) -> bool:"""Returns whether SAML is available for a specific email address.@@ -151,9 +193,56 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):max_length=255, blank=True, null=True, help_text="Hashed bearer token for SCIM authentication")+ # ---- ID-JAG attributes ----+ id_jag_issuer_url = models.CharField(+ max_length=512,+ blank=True,+ null=True,+ help_text="Trusted IdP issuer URL for ID-JAG. Required to enable ID-JAG on this domain.",+ )+ # Defaults to `{id_jag_issuer_url}/.well-known/openid-configuration`.+ id_jag_jwks_url = models.CharField(+ max_length=512,+ blank=True,+ null=True,+ help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ )+ id_jag_allowed_clients = ArrayField(+ models.CharField(max_length=256),+ default=list,+ blank=True,+ null=True,+ help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ )+class Meta:verbose_name = "domain"+ def clean(self) -> None:+ # Validate ID-JAG IdP URLs at write time as a UX guard against the+ # common admin mistake of pointing them at an internal/loopback/+ # metadata host. This is best-effort — DNS rebinding and post-write+ # config changes can still produce an unsafe URL at fetch time, so+ # `posthog.api.id_jag._get_jwks_client` re-validates before every+ # network call. Callers must invoke `full_clean()` (or use a+ # ModelForm / DRF serializer that does) for this to take effect.+ # Imported lazily to keep this app's import graph free of security/.+ from django.core.exceptions import ValidationError++ from posthog.security.url_validation import is_url_allowed++ errors: dict[str, str] = {}+ for field_name in ("id_jag_issuer_url", "id_jag_jwks_url"):+ url = getattr(self, field_name, None)+ if not url:+ continue+ allowed, reason = is_url_allowed(url)+ if not allowed:+ errors[field_name] = f"URL is not allowed: {reason}"+ if errors:+ raise ValidationError(errors)+ super().clean()+@propertydef is_verified(self) -> bool:"""diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 005d653ca6cf..c1e01a94bd43 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -15,6 +15,7 @@ from rest_framework.views import APIViewfrom rest_framework.viewsets import ViewSetfrom posthog.auth import (+ IDJagAccessTokenAuthentication,OAuthAccessTokenAuthentication,PersonalAPIKeyAuthentication,ProjectSecretAPIKeyAuthentication,@@ -489,6 +490,11 @@ class APIScopePermission(ScopeBasePermission):if not key_scopes:self.message = "OAuth token has no scopes and cannot access this resource"return False+ elif isinstance(request.successful_authenticator, IDJagAccessTokenAuthentication):+ key_scopes = list(request.successful_authenticator.scopes)+ if not key_scopes:+ self.message = "ID-JAG access token has no scopes and cannot access this resource"+ return Falseelse:# Session (and other non-token) auth normally bypasses API-scope checks — scopes# are a PAK/OAuth concept; logged-in users are gated by team membership + access@@ -562,6 +568,14 @@ class APIScopePermission(ScopeBasePermission):elif isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication):scoped_organizations = request.successful_authenticator.personal_api_key.scoped_organizationsscoped_teams = request.successful_authenticator.personal_api_key.scoped_teams+ elif isinstance(request.successful_authenticator, IDJagAccessTokenAuthentication):+ # ID-JAG access tokens are bound to the specific PostHog Organization+ # whose OrganizationDomain pinned the trusted IdP — carried in the+ # `org_id` claim. Pin `scoped_organizations` to that single org so+ # the token cannot reach other orgs the resolved user happens to+ # be a member of (cross-org confused-deputy defense).+ scoped_organizations = [request.successful_authenticator.organization_id]+ scoped_teams = Noneelse:raise ValueError("Unexpected authentication type")diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e1b61c0ade86..f11d6b4cf29a 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -237,7 +237,7 @@ LOGIN_URL = "/login"LOGOUT_URL = "/logout"LOGIN_REDIRECT_URL = "/"APPEND_SLASH = False-CORS_URLS_REGEX = r"^(/site_app/|/array/|/static/|/oauth/token/|/toolbar_oauth/check|/api/(?!early_access_features|surveys|web_experiments).*$)"+CORS_URLS_REGEX = r"^(/site_app/|/array/|/static/|/oauth/token/|/id-jag/token/?|/toolbar_oauth/check|/api/(?!early_access_features|surveys|web_experiments).*$)"CORS_ALLOW_HEADERS = default_headers + CORS_ALLOWED_TRACING_HEADERSX_FRAME_OPTIONS = "SAMEORIGIN"@@ -801,6 +801,10 @@ OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "posthog.OAuthRefreshToken"OAUTH2_PROVIDER_ID_TOKEN_MODEL = "posthog.OAuthIDToken"OAUTH2_PROVIDER_GRANT_MODEL = "posthog.OAuthGrant"+ID_JAG_ACCESS_TOKEN_TTL_SECONDS: int = get_from_env("ID_JAG_ACCESS_TOKEN_TTL_SECONDS", 60 * 60 * 2, type_cast=int)+ID_JAG_CLOCK_SKEW_SECONDS: int = get_from_env("ID_JAG_CLOCK_SKEW_SECONDS", 30, type_cast=int)+ID_JAG_JWKS_CACHE_TTL_SECONDS: int = get_from_env("ID_JAG_JWKS_CACHE_TTL_SECONDS", 60 * 60, type_cast=int)+TOOLBAR_OAUTH_STATE_TTL_SECONDS = 60 * 5TOOLBAR_OAUTH_EXCHANGE_TIMEOUT_SECONDS = 10TOOLBAR_OAUTH_APPLICATION_NAME = "PostHog Toolbar"diff --git a/posthog/urls.py b/posthog/urls.pyindex 7bad4db9fadf..d539f46e8e9a 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -33,6 +33,7 @@ from posthog.api import (user,)from posthog.api.github_callback.personal_finish import github_link_complete+from posthog.api.id_jag import IdJagViewSetfrom posthog.api.oauth.connected_apps import ConnectedAppsViewSetfrom posthog.api.oauth.wizard_metadata import WIZARD_METADATA_PATH, WizardClientMetadataViewfrom posthog.api.query import progress@@ -392,6 +393,7 @@ 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.pyopt_slash_path("report", report.get_csp_event), # CSP violation reportsdiff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex d59e4c34ccda..8d4907295673 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -5,6 +5,7 @@ import {findPostHogPermissionError,formatPermissionErrorMessage,} from '@/lib/errors'+import { isIdJagAccessToken } from '@/lib/id-jag'import { RequestLogger, withLogging } from '@/lib/logging'import { extractClientInfoFromBody } from '@/lib/mcp-client-info'import { getPostHogClient } from '@/lib/posthog'@@ -299,7 +300,7 @@ const handleRequest = async ()}- if (!token.startsWith('phx_') && !token.startsWith('pha_')) {+ if (!token.startsWith('phx_') && !token.startsWith('pha_') && !isIdJagAccessToken(token)) {log.extend({ authError: 'invalid_token_format' })return new Response(`Invalid token, please provide a valid API token. View the documentation for more information: ${MCP_DOCS_URL}`,diff --git a/services/mcp/src/lib/auth-errors.ts b/services/mcp/src/lib/auth-errors.tsindex 72f517524a2e..ab4f4dc1ab68 100644--- a/services/mcp/src/lib/auth-errors.ts+++ b/services/mcp/src/lib/auth-errors.ts@@ -7,13 +7,14 @@import type { CloudRegion } from '@/tools/types'-import { MCP_DOCS_URL } from './oauth-constants'import {buildInsufficientScopeChallenge,ErrorCode,findPostHogPermissionError,formatPermissionErrorMessage,} from './errors'+import { isIdJagAccessToken } from './id-jag'+import { MCP_DOCS_URL } from './oauth-constants'import { getPublicUrl } from './routing'// Map a thrown error to the appropriate auth response, or null if not auth-related.@@ -78,7 +79,10 @@ export function buildInvalidTokenFormatResponse(): Response {)}-// Validate the bearer token format (must be present and `phx_`/`pha_` prefixed).+// 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`).// Returns the auth-error response if invalid, or null if the token is well-formed.export function validateBearerToken(token: string | undefined,@@ -88,8 +92,11 @@ export function validateBearerToken(if (!token) {return buildMissingTokenResponse(request, effectiveRegion)}- if (!token.startsWith('phx_') && !token.startsWith('pha_')) {- return buildInvalidTokenFormatResponse()+ if (token.startsWith('phx_') || token.startsWith('pha_')) {+ return null}- return null+ if (isIdJagAccessToken(token)) {+ return null+ }+ return buildInvalidTokenFormatResponse()}diff --git a/services/mcp/src/lib/id-jag.ts b/services/mcp/src/lib/id-jag.tsnew file mode 100644index 000000000000..415c7e5b1248--- /dev/null+++ b/services/mcp/src/lib/id-jag.ts@@ -0,0 +1,31 @@+// RFC 9068 `typ` for OAuth 2.0 access tokens. ID-JAG access tokens+// (`posthog.api.id_jag`) are issued with this header so the resource server+// can distinguish them from sharing/export JWTs.+const ID_JAG_ACCESS_TOKEN_TYPE = 'at+jwt'++function base64UrlToBase64(input: string): string {+ const replaced = input.replace(/-/g, '+').replace(/_/g, '/')+ const padding = (4 - (replaced.length % 4)) % 4+ return replaced + '='.repeat(padding)+}++// Cheap header-only inspection — signature verification is the PostHog API's+// job (`IDJagAccessTokenAuthentication` in `posthog/auth.py`). We just need+// to recognize the token so we don't reject it at the MCP gate.+export function isIdJagAccessToken(token: string): boolean {+ const segments = token.split('.')+ if (segments.length !== 3) {+ return false+ }+ try {+ const headerRaw = segments[0]+ if (!headerRaw) {+ return false+ }+ const headerJson = atob(base64UrlToBase64(headerRaw))+ const header = JSON.parse(headerJson) as { typ?: unknown }+ return header.typ === ID_JAG_ACCESS_TOKEN_TYPE+ } catch {+ return false+ }+}diff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.tsindex 767c80c1e723..803961c331ed 100644--- a/services/mcp/tests/hono/app-routes.test.ts+++ b/services/mcp/tests/hono/app-routes.test.ts@@ -248,6 +248,61 @@ describe('Hono App Routes', () => {const body = await res.text()expect(body).not.toContain('Invalid token')})++ it('should pass auth check for ID-JAG access tokens (typ: at+jwt)', async () => {+ // Synthesize a JWT-shaped token: header `{"typ":"at+jwt","alg":"RS256"}`,+ // a stub payload, and a placeholder signature. The MCP gate only inspects+ // the header — the PostHog API verifies the signature downstream.+ const headerB64 = btoa('{"typ":"at+jwt","alg":"RS256"}')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ const payloadB64 = btoa('{"sub":"example.com:[email protected]","aud":"https://posthog.test"}')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ const idJagToken = `${headerB64}.${payloadB64}.signature`++ const { app } = createApp(mockRedis)+ const res = await app.request('/mcp', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${idJagToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'test', version: '1.0' },+ },+ id: 1,+ }),+ })+ const body = await res.text()+ expect(body).not.toContain('Invalid token')+ })++ it('should reject non-id-jag JWTs (e.g. typ: JWT)', async () => {+ // A JWT without `typ: at+jwt` is not an ID-JAG access token — e.g.+ // a sharing JWT — and must be rejected here so the right backend+ // takes over (or fails with the documented invalid-token response).+ const headerB64 = btoa('{"typ":"JWT","alg":"HS256"}')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ const wrongJwt = `${headerB64}.eyJzdWIiOiJ4In0.sig`++ const { app } = createApp(mockRedis)+ const res = await app.request('/mcp', {+ method: 'POST',+ headers: { Authorization: `Bearer ${wrongJwt}` },+ })+ expect(res.status).toBe(401)+ expect(await res.text()).toContain('Invalid token')+ })})describe('OAuth redirect routes', () => {diff --git a/services/mcp/tests/workers/mcp-protocol.test.ts b/services/mcp/tests/workers/mcp-protocol.test.tsindex cd1ebd2c0722..682e302c094f 100644--- a/services/mcp/tests/workers/mcp-protocol.test.ts+++ b/services/mcp/tests/workers/mcp-protocol.test.ts@@ -56,6 +56,42 @@ describe('MCP HTTP entry point (Cloudflare Workers)', () => {expect(response.status).toBe(401)expect(await response.text()).toContain('Invalid token')})++ it('returns 401 for JWTs without typ: at+jwt (not an ID-JAG token)', async () => {+ const headerB64 = btoa('{"typ":"JWT","alg":"HS256"}')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ const response = await SELF.fetch('https://mcp.posthog.com/mcp', {+ method: 'POST',+ headers: { Authorization: `Bearer ${headerB64}.eyJzdWIiOiJ4In0.sig` },+ })++ expect(response.status).toBe(401)+ expect(await response.text()).toContain('Invalid token')+ })++ it('passes the gate for ID-JAG access tokens (typ: at+jwt)', async () => {+ // The MCP gate only checks the header. Signature verification happens+ // downstream against the PostHog API (`IDJagAccessTokenAuthentication`).+ // Here we assert the response is NOT the gate's "Invalid token" 401 —+ // anything else (init failure against a missing PostHog API, etc.) is+ // acceptable since this test exercises only the gate.+ const headerB64 = btoa('{"typ":"at+jwt","alg":"RS256"}')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ const payloadB64 = btoa('{"sub":"example.com:[email protected]"}')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ const response = await SELF.fetch('https://mcp.posthog.com/mcp', {+ method: 'POST',+ headers: { Authorization: `Bearer ${headerB64}.${payloadB64}.sig` },+ })++ expect(await response.text()).not.toContain('Invalid token')+ })})describe('Authorization server redirects', () => {