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.

feat(mcp): support enterprise-managed authorization end to end (#113015)

Rafael Audibertec5e5e09fedc
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 8d08c1c4d280..af9aa2e36b70 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -5,7 +5,7 @@ import calendar
from collections.abc import Iterable
from datetime import datetime, timedelta
from functools import wraps
-from typing import TypedDict, cast
+from typing import Any, TypedDict, cast
from urllib.parse import parse_qs, urlparse
from django.conf import settings
@@ -37,7 +37,7 @@ from oauthlib.common import Request as OauthlibRequest
from oauthlib.oauth2 import InvalidClientIdError, InvalidGrantError
from redis.exceptions import RedisError
from rest_framework import serializers, status
-from rest_framework.exceptions import NotFound
+from rest_framework.exceptions import AuthenticationFailed, NotFound
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
@@ -68,7 +68,7 @@ from posthog.api.oauth.metadata import (
openid_provider_metadata,
protected_resource_metadata,
)
-from posthog.auth import SessionAuthentication
+from posthog.auth import IDJagAccessTokenAuthentication, SessionAuthentication
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
from posthog.helpers.oauth_pending_connection import (
PendingOAuthConnection,
@@ -2349,6 +2349,31 @@ class ConfidentialClientOnlyOAuthValidator(OAuthValidator):
return getattr(request.client, "client_type", None) == AbstractApplication.CLIENT_CONFIDENTIAL
+def _active_access_token_response(
+ *,
+ scope: str,
+ expires_at: int,
+ is_impersonated: bool,
+ scoped_teams: list[int],
+ scoped_organizations: list[str],
+ application: OAuthApplication | None,
+) -> JsonResponse:
+ """RFC 7662 response for an active access token, whether it is stored or a signed JWT."""
+ data: dict[str, Any] = {
+ "active": True,
+ "token_type": "access_token",
+ "scope": scope,
+ "is_impersonated": is_impersonated,
+ "scoped_teams": scoped_teams,
+ "scoped_organizations": scoped_organizations,
+ "exp": expires_at,
+ }
+ if application:
+ data["client_id"] = application.client_id
+ data["client_name"] = application.name
+ return JsonResponse(data)
+
+
@method_decorator(csrf_exempt, name="dispatch")
@method_decorator(login_not_required, name="dispatch")
class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
@@ -2408,6 +2433,9 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
"""
if self._is_self_introspection(request):
bearer_token = request.headers.get("Authorization", "")[7:]
+ # An ID-JAG access token has no row to look up; get_token_response verifies it.
+ if IDJagAccessTokenAuthentication.is_id_jag_token(bearer_token):
+ return True, request
token_checksum = hashlib.sha256(bearer_token.encode("utf-8")).hexdigest()
try:
request.oauth_caller_access_token = OAuthAccessToken.objects.get(token_checksum=token_checksum)
@@ -2452,6 +2480,30 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
client = getattr(request, "oauth_authenticated_client", None)
return client.client_id if client is not None else None
+ def _id_jag_token_response(self, request, token_value: str, credential_client_id: str | None) -> JsonResponse:
+ """An ID-JAG access token is a signed JWT with no row, so it is read from its verified
+ claims. A caller sees it only when the caller is the token itself, or the client the
+ token was issued to."""
+ try:
+ verified = IDJagAccessTokenAuthentication.verify_access_token(token_value)
+ except AuthenticationFailed:
+ return JsonResponse({"active": False}, status=200)
+ if not self._is_self_introspection(request):
+ caller_token = getattr(request, "oauth_caller_access_token", None)
+ caller_client_id = credential_client_id or getattr(
+ getattr(caller_token, "application", None), "client_id", None
+ )
+ if caller_client_id != verified.client_id:
+ return JsonResponse({"active": False}, status=200)
+ return _active_access_token_response(
+ scope=" ".join(verified.scopes),
+ expires_at=verified.expires_at,
+ is_impersonated=False,
+ scoped_teams=[],
+ scoped_organizations=[verified.organization_id],
+ application=OAuthApplication.objects.filter(client_id=verified.client_id).first(),
+ )
+
def get_token_response(self, request, token_value=None):
"""
RFC 7662 Token Introspection response.
@@ -2477,6 +2529,9 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
if is_client_credentials and credential_client_id is None:
return JsonResponse({"active": False}, status=200)
+ if IDJagAccessTokenAuthentication.is_id_jag_token(token_value):
+ return self._id_jag_token_response(request, token_value, credential_client_id)
+
# The bearer caller is identified by the application its own token belongs to. The
# `introspection` scope says a caller may introspect, not whose tokens it may read,
# and `/oauth/register/` hands the scope to anyone, so the scope alone would let one
@@ -2520,19 +2575,14 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
# `user` is null for a client-credentials grant, which has no resource owner.
if access_token.user is not None and not access_token.user.is_active:
return JsonResponse({"active": False}, status=200)
- data = {
- "active": True,
- "token_type": "access_token",
- "scope": access_token.scope,
- "is_impersonated": access_token.impersonated_by_id is not None,
- "scoped_teams": access_token.scoped_teams or [],
- "scoped_organizations": access_token.scoped_organizations or [],
- "exp": int(calendar.timegm(access_token.expires.timetuple())),
- }
- if access_token.application:
- data["client_id"] = access_token.application.client_id
- data["client_name"] = access_token.application.name
- return JsonResponse(data)
+ return _active_access_token_response(
+ scope=access_token.scope,
+ expires_at=int(calendar.timegm(access_token.expires.timetuple())),
+ is_impersonated=access_token.impersonated_by_id is not None,
+ scoped_teams=access_token.scoped_teams or [],
+ scoped_organizations=access_token.scoped_organizations or [],
+ application=access_token.application,
+ )
# Fall back to refresh token (lookup by plaintext token — OAuthRefreshToken has
# no token_checksum field; revoked tokens filtered via revoked__isnull=True)
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 0c4ccf60bbfb..f28e27947fd1 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -19,7 +19,7 @@ from urllib.parse import urlencode
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.test import override_settings
+from django.test import RequestFactory, override_settings
from django.utils import timezone
import jwt
@@ -49,6 +49,7 @@ from posthog.models.oauth import OAuthApplication
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User as UserModel
+from posthog.permissions import get_authenticator_client
from posthog.settings.utils import generate_rsa_private_key_pem
# rsa operations are expensive, keep this at the module-level to avoid slow tests
@@ -1081,6 +1082,18 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
expected_credential_id,
)
+ def test_flag_context_names_the_client_the_token_was_issued_to(self) -> None:
+ authenticator = IDJagAccessTokenAuthentication()
+ request = RequestFactory().get(
+ "/", HTTP_AUTHORIZATION=f"Bearer {self._mint_access_token(client_id='agent_client_id')}"
+ )
+
+ authenticator.authenticate(request)
+
+ self.assertEqual(
+ get_authenticator_client(authenticator), {"credential_type": "id_jag", "client_id": "agent_client_id"}
+ )
+
def test_valid_token_authenticates_user(self) -> None:
token = self._mint_access_token(scope="user:read")
resp = self._call_authenticated(token)
@@ -1169,6 +1182,26 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
+ @parameterized.expand([("valid", 300, True), ("expired", -60, False)])
+ def test_token_can_introspect_itself(self, _name: str, exp_seconds: int, expected_active: bool) -> None:
+ _create_client(_RESOURCE_CLIENT_ID)
+ token = self._mint_access_token(scope="feature_flag:read", exp_seconds=exp_seconds)
+
+ resp = self.client.post(
+ "/oauth/introspect",
+ data={"token": token},
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ body = resp.json()
+ self.assertEqual(body["active"], expected_active)
+ if expected_active:
+ self.assertEqual(body["scope"], "feature_flag:read")
+ self.assertEqual(body["scoped_organizations"], [str(self.organization.id)])
+ self.assertEqual(body["client_id"], _RESOURCE_CLIENT_ID)
+
def test_unknown_user_uuid_rejected(self) -> None:
token = self._mint_access_token(user_uuid=str(uuid.uuid4()), scope="user:read")
resp = self._call_authenticated(token)
diff --git a/posthog/auth.py b/posthog/auth.py
index 3d8638d7cc97..ae44f27eafbb 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -31,6 +31,7 @@ from zxcvbn import zxcvbn
from posthog.clickhouse.query_tagging import AccessMethod, tag_authentication, tag_queries
from posthog.constants import AvailableFeature
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.helpers.two_factor_session import enforce_two_factor
from posthog.helpers.verified_domain_enforcement import enforce_verified_domain
@@ -602,6 +603,15 @@ class JwtAuthentication(ActivityCredentialMixin, authentication.BaseAuthenticati
return cls.keyword
+@frozen
+class VerifiedIdJagAccessToken:
+ user: User
+ organization_id: str
+ client_id: str
+ scopes: list[str]
+ expires_at: int
+
+
class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticates inbound API requests using an access token minted by the
@@ -620,7 +630,7 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
keyword = "Bearer"
activity_credential_type = "id_jag"
- id_jag_claims: dict[str, Any]
+ client_id: str
scopes: list[str]
organization_id: str
@@ -637,7 +647,7 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
return token
@classmethod
- def _is_id_jag_token(cls, token: str) -> bool:
+ def is_id_jag_token(cls, token: str) -> bool:
# Personal/OAuth API key prefixes are reserved for those auth backends.
if token.startswith((PERSONAL_API_KEY_PREFIX, OAUTH_ACCESS_TOKEN_PREFIX, SECRET_API_TOKEN_PREFIX)):
return False
@@ -650,110 +660,122 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
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
-
- verification_keys = get_oidc_verification_keys()
- if not verification_keys:
- raise AuthenticationFailed(detail="ID-JAG access tokens are not configured on this server.")
+ @classmethod
+ def verify_access_token(cls, token: str) -> VerifiedIdJagAccessToken:
+ """Verify the signature and claims and resolve the active member, or raise AuthenticationFailed.
+
+ No request side effects, so token introspection can share it."""
+ verification_keys = get_oidc_verification_keys()
+ if not verification_keys:
+ 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.")
+
+ # The token's `aud` is the resource it was minted for (id_jag._construct_access_token_payload).
+ # Accept SITE_URL plus any advertised resource identifier; `iss` stays SITE_URL (we mint it).
+ # Function-level import keeps the heavier id_jag module off auth.py's foundational import path.
+ from posthog.api.id_jag import get_allowed_resources # noqa: PLC0415
+
+ allowed_resources = get_allowed_resources()
+
+ # Try the active signing key first, then any keys being rotated out. A wrong
+ # key fails the signature check, so we move on; a key that matches but fails
+ # claim validation (expiry, audience, …) raises the real error to report.
+ claims = None
+ for verification_key in verification_keys:
+ try:
+ claims = jwt.decode(
+ token,
+ verification_key,
+ algorithms=["RS256"],
+ audience=allowed_resources,
+ issuer=site_url,
+ leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,
+ options={
+ "require": ["iss", "sub", "user_uuid", "aud", "exp", "iat", "client_id", "scope", "org_id"],
+ "verify_signature": True,
+ "verify_exp": True,
+ "verify_aud": True,
+ "verify_iss": True,
+ },
+ )
+ break
+ except jwt.InvalidSignatureError:
+ continue
+ 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.")
- site_url = (settings.SITE_URL or "").rstrip("/")
- if not site_url:
- raise AuthenticationFailed(detail="ID-JAG access tokens are not configured on this server.")
+ if claims is None:
+ raise AuthenticationFailed(detail="ID-JAG access token is invalid.")
- # The token's `aud` is the resource it was minted for (id_jag._construct_access_token_payload).
- # Accept SITE_URL plus any advertised resource identifier; `iss` stays SITE_URL (we mint it).
- # Function-level import keeps the heavier id_jag module off auth.py's foundational import path.
- from posthog.api.id_jag import get_allowed_resources # noqa: PLC0415
+ 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.")
- allowed_resources = get_allowed_resources()
+ # Membership is re-checked on every request, because the user may have left the
+ # organization after the token was issued.
+ membership = (
+ OrganizationMembership.objects.filter(
+ organization_id=organization_id,
+ user__is_active=True,
+ user__uuid=str(claims["user_uuid"]),
+ )
+ .select_related("user", "organization")
+ .first()
+ )
+ if not membership:
+ raise AuthenticationFailed(
+ detail="No active PostHog user matches the ID-JAG access token subject for this organization."
+ )
- # Try the active signing key first, then any keys being rotated out. A wrong
- # key fails the signature check, so we move on; a key that matches but fails
- # claim validation (expiry, audience, …) raises the real error to report.
- claims = None
- for verification_key in verification_keys:
- try:
- claims = jwt.decode(
- token,
- verification_key,
- algorithms=["RS256"],
- audience=allowed_resources,
- issuer=site_url,
- leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,
- options={
- "require": ["iss", "sub", "user_uuid", "aud", "exp", "iat", "client_id", "scope", "org_id"],
- "verify_signature": True,
- "verify_exp": True,
- "verify_aud": True,
- "verify_iss": True,
- },
- )
- break
- except jwt.InvalidSignatureError:
- continue
- 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.")
-
- if claims is None:
- raise AuthenticationFailed(detail="ID-JAG access token is invalid.")
+ user = membership.user
+ organization = membership.organization
- 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.")
-
- # Membership is re-checked on every request, because the user may have left the
- # organization after the token was issued.
- membership = (
- OrganizationMembership.objects.filter(
- organization_id=organization_id,
- user__is_active=True,
- user__uuid=str(claims["user_uuid"]),
- )
- .select_related("user", "organization")
- .first()
- )
- if not membership:
- raise AuthenticationFailed(
- detail="No active PostHog user matches the ID-JAG access token subject for this organization."
- )
+ if not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):
+ raise AuthenticationFailed(detail="ID-JAG (XAA) is not enabled for this organization.")
- user = membership.user
- organization = membership.organization
+ return VerifiedIdJagAccessToken(
+ user=user,
+ organization_id=organization_id,
+ client_id=str(claims["client_id"]),
+ scopes=str(claims["scope"]).split(),
+ expires_at=int(claims["exp"]),
+ )
- if not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):
- raise AuthenticationFailed(detail="ID-JAG (XAA) is not enabled for this organization.")
+ 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
- refuse_blocked_account(request, user, call_site="id_jag_token", impersonated=False)
- self.id_jag_claims = claims
- self.scopes = str(claims.get("scope") or "").split()
- self.organization_id = organization_id
+ verified = self.verify_access_token(token)
+ refuse_blocked_account(request, verified.user, call_site="id_jag_token", impersonated=False)
+ self.client_id = verified.client_id
+ self.scopes = verified.scopes
+ self.organization_id = verified.organization_id
tag_authentication(
- user_id=user.pk,
- team_id=user.current_team_id,
+ user_id=verified.user.pk,
+ team_id=verified.user.current_team_id,
access_method=AccessMethod.ID_JAG,
)
- self.record_activity_actor(user, str(claims["client_id"]))
+ self.record_activity_actor(verified.user, verified.client_id)
record_agent_intent(request)
- return user, None
+ return verified.user, None
def authenticate_header(self, request) -> str:
return self.keyword
diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.ts
index 4a3fd791bb53..36027ee081e7 100644
--- a/services/mcp/src/hono/dispatcher.ts
+++ b/services/mcp/src/hono/dispatcher.ts
@@ -91,6 +91,10 @@ const SERVER_CAPABILITIES = {
tools: { listChanged: false },
resources: { listChanged: false },
prompts: { listChanged: false },
+ extensions: {
+ // Tokens the authorization server issues for an enterprise IdP's ID-JAG are accepted here.
+ 'io.modelcontextprotocol/enterprise-managed-authorization': {},
+ },
} as const
function isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
index 29cf4a2385fc..58bb283a7054 100644
--- a/services/mcp/tests/integration/mcp-protocol-suite.ts
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -1785,7 +1785,10 @@ export function defineStatelessProtocolTests(
// conforming modern client would select one via `_meta` and be
// served a dialect we can't speak statelessly.
expect(result.supportedVersions).toEqual([STATELESS_VERSION])
- expect(result.capabilities).toMatchObject({ tools: { listChanged: false } })
+ expect(result.capabilities).toMatchObject({
+ tools: { listChanged: false },
+ extensions: { 'io.modelcontextprotocol/enterprise-managed-authorization': {} },
+ })
// DiscoverResult requires top-level serverInfo (not just result _meta).
expect(result.serverInfo).toMatchObject({ name: 'PostHog' })
expect(typeof result.instructions).toBe('string')