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(oauth): support MCP enterprise-managed authorization (ID-JAG) (#64747)

Rafael Audibert6702746a1d2d
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx
index 38012c337cf6..7da9b76cd738 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/ConfigureIdJagModal.tsx
@@ -71,6 +71,11 @@ export function ConfigureIdJagModal(): JSX.Element {
a draft.
</LemonBanner>
)}
+ <LemonBanner type="info">
+ Configure your IdP to grant <code>user:read</code> plus the scopes each integration needs (for
+ project-scoped APIs, also <code>organization:read</code> and <code>project:read</code>). Tokens
+ issued without the required scopes are rejected with an insufficient-scope error.
+ </LemonBanner>
</LemonModal.Content>
<LemonModal.Footer>
<LemonButton loading={isIdJagConfigSubmitting} type="primary" htmlType="submit">
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index 33e2533a3196..afe6ae421059 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -37,6 +37,9 @@ 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"
+# draft-ietf-oauth-identity-assertion-authz-grant §7.2 — advertised in metadata for ID-JAG discovery.
+ID_JAG_GRANT_PROFILE = "urn:ietf:params:oauth:grant-profile:id-jag"
+
GENERIC_ID_JAG_REJECTION = "ID-JAG could not be verified"
@@ -123,6 +126,24 @@ def _get_site_url() -> str:
return site_url
+def _id_jag_allowlist(extra: list[str] | None) -> list[str]:
+ """SITE_URL plus the trailing-slash-normalized `extra` values."""
+ return [_get_site_url(), *[v.rstrip("/") for v in (extra or []) if v]]
+
+
+def _get_allowed_audiences() -> list[str]:
+ """Accepted ID-JAG `aud` values — the authorization-server issuer the client discovered.
+ Always includes SITE_URL; Cloud adds the OAuth proxy via ID_JAG_ALLOWED_AUDIENCES."""
+ return _id_jag_allowlist(settings.ID_JAG_ALLOWED_AUDIENCES)
+
+
+def get_allowed_resources() -> list[str]:
+ """Accepted ID-JAG `resource` values — the resource identifier the client discovered.
+ Always includes SITE_URL; Cloud adds extra resource servers via ID_JAG_ALLOWED_RESOURCES.
+ Also used by the resource server (posthog.auth) to validate the minted token's `aud`."""
+ return _id_jag_allowlist(settings.ID_JAG_ALLOWED_RESOURCES)
+
+
def _get_jwks_client(issuer: str, jwks_url: str | None = None) -> jwt.PyJWKClient:
"""Resolve a `PyJWKClient` for the given IdP issuer.
@@ -268,7 +289,7 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
except jwt.PyJWTError as e:
raise InvalidGrantError(f"ID-JAG signing key resolution failed: {e}")
- expected_audience = _get_site_url()
+ allowed_audiences = _get_allowed_audiences()
try:
claims = cast(
@@ -277,7 +298,7 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
assertion,
signing_key.key,
algorithms=["RS256", "RS384", "RS512"],
- audience=expected_audience,
+ audience=allowed_audiences,
leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,
options={
"require": ["iss", "sub", "aud", "exp", "iat", "client_id"],
@@ -322,8 +343,11 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
resource = claims.get("resource")
if not resource:
raise InvalidGrantError("ID-JAG is missing the resource claim (RFC 8707)")
- if resource.rstrip("/") != expected_audience:
+ resource = resource.rstrip("/")
+ if resource not in get_allowed_resources():
raise InvalidTargetError(f"ID-JAG resource {resource!r} does not match this resource server")
+ # Store the normalized value back so the minted token's `aud` is consistent.
+ claims["resource"] = resource
client_id = claims.get("client_id")
if not client_id:
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 65bfed0dba63..6305a9d5e984 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -3989,6 +3989,15 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
self.assertEqual(metadata["code_challenge_methods_supported"], ["S256"])
self.assertIn("none", metadata["token_endpoint_auth_methods_supported"])
+ def test_metadata_advertises_id_jag_grant_profile(self):
+ response = self.client.get("/.well-known/oauth-authorization-server")
+ metadata = response.json()
+
+ self.assertEqual(
+ metadata["authorization_grant_profiles_supported"],
+ ["urn:ietf:params:oauth:grant-profile:id-jag"],
+ )
+
def test_metadata_includes_scopes(self):
response = self.client.get("/.well-known/oauth-authorization-server")
metadata = response.json()
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index da80e0ba196b..28d1e88fae1b 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -1570,6 +1570,7 @@ class OAuthAuthorizationServerMetadataView(_PublicMetadataView):
"refresh_token",
id_jag.JWT_BEARER_GRANT_TYPE,
],
+ "authorization_grant_profiles_supported": [id_jag.ID_JAG_GRANT_PROFILE],
"token_endpoint_auth_methods_supported": ["none", "client_secret_post"],
"code_challenge_methods_supported": ["S256"],
# Service documentation
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 2f70e5db4050..c8ebb12418cf 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -581,6 +581,47 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(resp.json()["error"], "invalid_target")
+ @override_settings(ID_JAG_ALLOWED_AUDIENCES=["https://oauth.posthog.com"])
+ def test_accepts_aud_matching_configured_allowed_audience(self) -> None:
+ # A spec-compliant client derives `aud` from the advertised auth-server issuer
+ # (the OAuth proxy), not SITE_URL. That value must be accepted when allowlisted.
+ assertion = _make_id_jag(audience="https://oauth.posthog.com")
+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+
+ @override_settings(ID_JAG_ALLOWED_RESOURCES=["https://mcp.posthog.com"])
+ def test_accepts_resource_matching_configured_allowed_resource(self) -> None:
+ # The ID-JAG `resource` is the advertised resource-server identifier, not SITE_URL.
+ # The minted access token is audience-restricted to that resource (EMA §5.1).
+ assertion = _make_id_jag(resource="https://mcp.posthog.com/")
+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ claims = jwt.decode(
+ resp.json()["access_token"],
+ _public_key_for(_AS_PRIVATE_KEY_PEM),
+ algorithms=["RS256"],
+ audience="https://mcp.posthog.com",
+ issuer=_AUTH_SERVER_URL,
+ )
+ self.assertEqual(claims["aud"], "https://mcp.posthog.com")
+
+ @override_settings(ID_JAG_ALLOWED_RESOURCES=["https://mcp.posthog.com"])
+ def test_round_trip_with_allowed_resource_authenticates_on_resource_side(self) -> None:
+ # End-to-end: a token minted for an allowlisted resource must be accepted by the
+ # resource server (IDJagAccessTokenAuthentication), not just issued.
+ assertion = _make_id_jag(
+ resource="https://mcp.posthog.com",
+ 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_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.
diff --git a/posthog/auth.py b/posthog/auth.py
index 2010f39b58e1..566e460cdb54 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -591,6 +591,13 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
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.
@@ -601,7 +608,7 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
token,
verification_key,
algorithms=["RS256"],
- audience=site_url,
+ audience=allowed_resources,
issuer=site_url,
leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,
options={
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 8e2e2d682b2c..72d668caade8 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -931,6 +931,13 @@ ID_JAG_ACCESS_TOKEN_TTL_SECONDS: int = get_from_env("ID_JAG_ACCESS_TOKEN_TTL_SEC
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)
+# Extra accepted ID-JAG `aud` values (the advertised authorization-server issuer) beyond SITE_URL —
+# e.g. the OAuth proxy "https://oauth.posthog.com" on Cloud. SITE_URL is always accepted.
+ID_JAG_ALLOWED_AUDIENCES: list[str] = get_list(get_from_env("ID_JAG_ALLOWED_AUDIENCES", ""))
+# Extra accepted ID-JAG `resource` values (the advertised resource-server identifier) beyond SITE_URL —
+# e.g. "https://mcp.posthog.com,https://mcp.us.posthog.com" on Cloud. SITE_URL is always accepted.
+ID_JAG_ALLOWED_RESOURCES: list[str] = get_list(get_from_env("ID_JAG_ALLOWED_RESOURCES", ""))
+
TOOLBAR_OAUTH_STATE_TTL_SECONDS = 60 * 5
TOOLBAR_OAUTH_EXCHANGE_TIMEOUT_SECONDS = 10
TOOLBAR_OAUTH_APPLICATION_NAME = "PostHog Toolbar"
diff --git a/services/oauth-proxy/src/handlers/metadata.ts b/services/oauth-proxy/src/handlers/metadata.ts
index 6a7665cb4469..ae4fbd9ca4c0 100644
--- a/services/oauth-proxy/src/handlers/metadata.ts
+++ b/services/oauth-proxy/src/handlers/metadata.ts
@@ -24,6 +24,7 @@ interface WellKnownOAuthAuthorizationServerMetadata {
response_types_supported: string[]
response_modes_supported: string[]
grant_types_supported: string[]
+ authorization_grant_profiles_supported: string[]
token_endpoint_auth_methods_supported: string[]
code_challenge_methods_supported: string[]
service_documentation: string
diff --git a/services/oauth-proxy/tests/metadata.test.ts b/services/oauth-proxy/tests/metadata.test.ts
index fc42599f0d10..43fee4d76c3b 100644
--- a/services/oauth-proxy/tests/metadata.test.ts
+++ b/services/oauth-proxy/tests/metadata.test.ts
@@ -12,7 +12,8 @@ const AUTHORITATIVE_METADATA = {
scopes_supported: ['openid', 'profile', 'email'],
response_types_supported: ['code'],
response_modes_supported: ['query'],
- grant_types_supported: ['authorization_code', 'refresh_token'],
+ grant_types_supported: ['authorization_code', 'refresh_token', 'urn:ietf:params:oauth:grant-type:jwt-bearer'],
+ authorization_grant_profiles_supported: ['urn:ietf:params:oauth:grant-profile:id-jag'],
token_endpoint_auth_methods_supported: ['none', 'client_secret_post'],
code_challenge_methods_supported: ['S256'],
service_documentation: 'https://posthog.com/docs/model-context-protocol',
@@ -61,6 +62,9 @@ describe('handleMetadata', () => {
expect(data.scopes_supported).toEqual(AUTHORITATIVE_METADATA.scopes_supported)
expect(data.response_types_supported).toEqual(AUTHORITATIVE_METADATA.response_types_supported)
expect(data.grant_types_supported).toEqual(AUTHORITATIVE_METADATA.grant_types_supported)
+ expect(data.authorization_grant_profiles_supported).toEqual(
+ AUTHORITATIVE_METADATA.authorization_grant_profiles_supported
+ )
expect(data.code_challenge_methods_supported).toContain('S256')
expect(data.service_documentation).toBe(AUTHORITATIVE_METADATA.service_documentation)
expect(data.client_id_metadata_document_supported).toBe(true)