Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(oauth): serve conformant OIDC discovery and ID tokens (#99353)

Rafael Audibert86fac583652a
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7f78cc627c6c..2859deccbf87 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -5450,6 +5450,10 @@ importers:
version: 4.98.0(@cloudflare/[email protected])
services/oauth-proxy:
+ dependencies:
+ jose:
+ specifier: ^6.2.3
+ version: 6.2.3
devDependencies:
'@cloudflare/workers-types':
specifier: ^4.20260120.0
diff --git a/posthog/api/oauth/claims.py b/posthog/api/oauth/claims.py
new file mode 100644
index 000000000000..c5c9f8a081c8
--- /dev/null
+++ b/posthog/api/oauth/claims.py
@@ -0,0 +1,32 @@
+"""The OIDC claims this server asserts about a user.
+
+Kept apart from the validator that produces the values and the discovery documents that advertise
+the names, so neither imports the other.
+"""
+
+from collections.abc import Callable
+from typing import Protocol
+
+from posthog.models.user import User
+
+
+class ClaimRequest(Protocol):
+ """The part of the oauthlib request a claim callable reads."""
+
+ user: User
+
+
+# Claim name to a callable taking the oauthlib request. django-oauth-toolkit reads this through
+# `OAuthValidator.get_additional_claims` for both `claims_supported` and the claim values, and
+# filters it by granted scope through `OAuth2Validator.oidc_claim_scope`.
+OIDC_CLAIMS: dict[str, Callable[[ClaimRequest], str | bool]] = {
+ # Overrides django-oauth-toolkit's primary-key default. Changing `sub` would re-identify
+ # every user at every relying party.
+ "sub": lambda request: str(request.user.uuid),
+ "given_name": lambda request: request.user.first_name,
+ "family_name": lambda request: request.user.last_name,
+ "email": lambda request: request.user.email,
+ # A null `is_email_verified` means the account predates email verification, not that the
+ # address was checked, so only an explicit True can be reported as verified.
+ "email_verified": lambda request: request.user.is_email_verified is True,
+}
diff --git a/posthog/api/oauth/metadata.py b/posthog/api/oauth/metadata.py
new file mode 100644
index 000000000000..c59948029463
--- /dev/null
+++ b/posthog/api/oauth/metadata.py
@@ -0,0 +1,137 @@
+"""Discovery documents for the OAuth authorization server.
+
+Both documents describe one server, and a client reads whichever one its stack supports,
+so they are built here rather than separately.
+"""
+
+from posthog.api import id_jag
+from posthog.api.oauth.claims import OIDC_CLAIMS
+from posthog.dataclasses import frozen
+from posthog.models.oauth import TokenEndpointAuthMethod
+from posthog.scopes import get_oauth_scopes_supported, get_scope_descriptions
+
+type Document = dict[str, object]
+
+SUPPORTED_GRANT_TYPES = [
+ "authorization_code",
+ "refresh_token",
+ id_jag.JWT_BEARER_GRANT_TYPE,
+]
+
+# Every method a client can register under must appear here, or a client reads this
+# document, picks a method we do not accept, and fails the token exchange.
+SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS = [
+ TokenEndpointAuthMethod.NONE.value,
+ TokenEndpointAuthMethod.CLIENT_SECRET_POST.value,
+ TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value,
+]
+
+SERVICE_DOCUMENTATION = "https://posthog.com/docs/api"
+
+
+def _shared_metadata(base_url: str) -> Document:
+ return {
+ "issuer": base_url,
+ "authorization_endpoint": f"{base_url}/oauth/authorize/",
+ "token_endpoint": f"{base_url}/oauth/token/",
+ "userinfo_endpoint": f"{base_url}/oauth/userinfo/",
+ "revocation_endpoint": f"{base_url}/oauth/revoke/",
+ "introspection_endpoint": f"{base_url}/oauth/introspect/",
+ "registration_endpoint": f"{base_url}/oauth/register/",
+ "jwks_uri": f"{base_url}/.well-known/jwks.json",
+ # Excludes the scopes an OAuth client cannot obtain self-serve, including `*`.
+ "scopes_supported": get_oauth_scopes_supported(),
+ # Only the authorization code flow is implemented.
+ "response_types_supported": ["code"],
+ "response_modes_supported": ["query"],
+ "grant_types_supported": SUPPORTED_GRANT_TYPES,
+ "token_endpoint_auth_methods_supported": SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS,
+ # The `enforce_supported_code_challenge_method` constraint rejects `plain`.
+ "code_challenge_methods_supported": ["S256"],
+ "service_documentation": SERVICE_DOCUMENTATION,
+ }
+
+
+def openid_provider_metadata(base_url: str) -> Document:
+ """OpenID Provider Metadata (OpenID Connect Discovery 1.0)."""
+ return {
+ **_shared_metadata(base_url),
+ "subject_types_supported": ["public"],
+ # The `enforce_rs256_algorithm` constraint on `OAuthApplication` rules out HS256.
+ "id_token_signing_alg_values_supported": ["RS256"],
+ "claims_supported": sorted(OIDC_CLAIMS),
+ }
+
+
+def authorization_server_metadata(base_url: str, region_info: Document | None = None) -> Document:
+ """OAuth 2.0 Authorization Server Metadata (RFC 8414)."""
+ return {
+ **_shared_metadata(base_url),
+ "authorization_grant_profiles_supported": [id_jag.ID_JAG_GRANT_PROFILE],
+ # Client ID Metadata Document (draft-ietf-oauth-client-id-metadata-document-00)
+ "client_id_metadata_document_supported": True,
+ # auth.md agent registration profile (https://workos.com/auth-md).
+ # Only flows that actually exist are advertised: ID-JAG identity
+ # assertions at the identity endpoint. The user-claimed device flow
+ # (claim_endpoint) and revocation receiver (events_endpoint) are not
+ # built yet, so they are deliberately omitted rather than advertised.
+ "agent_auth": {
+ "skill": f"{base_url}/auth.md",
+ "identity_endpoint": f"{base_url}/oauth/token/",
+ "identity_types_supported": ["identity_assertion"],
+ "identity_assertion": {
+ "assertion_types_supported": ["urn:ietf:params:oauth:token-type:id-jag"],
+ },
+ },
+ **(region_info or {}),
+ }
+
+
+def protected_resource_metadata(base_url: str) -> Document:
+ """OAuth 2.0 Protected Resource Metadata (RFC 9728).
+
+ Reached through the `WWW-Authenticate: Bearer resource_metadata=...` header on 401
+ responses (see posthog/exceptions.py).
+ """
+ return {
+ # Required by RFC 9728
+ "resource": base_url,
+ # The same PostHog instance is its own authorization server
+ "authorization_servers": [base_url],
+ "scopes_supported": get_oauth_scopes_supported(),
+ "bearer_methods_supported": ["header"],
+ "resource_documentation": SERVICE_DOCUMENTATION,
+ }
+
+
+# Identity and token-management scopes have no entry in get_scope_descriptions(),
+# which only covers obj:action scopes. Every bare scope in
+# `get_oauth_scopes_supported()` needs a line here, or the manifest prints the
+# scope name where its description belongs.
+_IDENTITY_SCOPE_DESCRIPTIONS = {
+ "openid": "Sign in and read your user identifier",
+ "profile": "Read your basic profile",
+ "email": "Read your email address",
+ "introspection": "Check whether a token you hold is still valid",
+}
+
+
+@frozen
+class ManifestScope:
+ """One advertised scope as the auth.md manifest lists it."""
+
+ name: str
+ description: str
+
+
+def client_manifest_scopes() -> list[ManifestScope]:
+ descriptions = get_scope_descriptions()
+ return [
+ ManifestScope(
+ name=scope,
+ description=descriptions[scope]
+ if scope in descriptions
+ else _IDENTITY_SCOPE_DESCRIPTIONS.get(scope, scope),
+ )
+ for scope in get_oauth_scopes_supported()
+ ]
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 2c8513e4cf45..91a0fd27d24a 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -30,6 +30,7 @@ from rest_framework import status
from posthog.api.oauth import OAuthAuthorizationSerializer
from posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODS
from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER
+from posthog.api.oauth.metadata import authorization_server_metadata, openid_provider_metadata
from posthog.api.oauth.views import OAuthTokenView, OAuthValidator, _token_error_code
from posthog.helpers.oauth_pending_connection import (
PENDING_OAUTH_CONNECTION_COOKIE,
@@ -48,6 +49,7 @@ from posthog.models.oauth import (
from posthog.models.team.team import Team
from posthog.scopes import get_oauth_scopes_supported
from posthog.settings.utils import generate_rsa_private_key_pem
+from posthog.utils import absolute_uri
def jwks_entry_to_public_key(key_data: dict):
@@ -1298,7 +1300,7 @@ class TestOAuthAPI(APIBaseTest):
# Verify the response matches the decoded token
self.assertEqual(userinfo_data["sub"], str(self.user.uuid))
self.assertEqual(userinfo_data["email"], self.user.email)
- self.assertEqual(userinfo_data["email_verified"], self.user.is_email_verified or False)
+ self.assertEqual(userinfo_data["email_verified"], self.user.is_email_verified is True)
self.assertEqual(userinfo_data["given_name"], self.user.first_name)
self.assertEqual(userinfo_data["family_name"], self.user.last_name)
@@ -5545,6 +5547,53 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
self.assertNotIn("events_endpoint", metadata["agent_auth"])
+class TestOpenIDProviderMetadata(SimpleTestCase):
+ """Tests for the OpenID Provider Metadata document (OIDC Discovery 1.0)."""
+
+ def test_advertises_the_claims_the_userinfo_endpoint_returns(self):
+ # Adding a request argument back to `get_additional_claims` silently narrows this to `sub`.
+ metadata = openid_provider_metadata("https://us.posthog.com")
+
+ self.assertEqual(metadata["claims_supported"], ["email", "email_verified", "family_name", "given_name", "sub"])
+
+ def test_does_not_advertise_scopes_an_oauth_client_cannot_obtain(self):
+ scopes = openid_provider_metadata("https://us.posthog.com")["scopes_supported"]
+ assert isinstance(scopes, list)
+
+ self.assertNotIn("*", scopes)
+ self.assertNotIn("llm_gateway:read", scopes)
+ self.assertIn("openid", scopes)
+ self.assertIn("email", scopes)
+
+ def test_advertises_only_the_flows_the_server_accepts(self):
+ # Advertising an alternative sends a client into a flow the DB constraints reject.
+ metadata = openid_provider_metadata("https://us.posthog.com")
+
+ self.assertEqual(metadata["response_types_supported"], ["code"])
+ self.assertEqual(metadata["code_challenge_methods_supported"], ["S256"])
+ self.assertEqual(metadata["id_token_signing_alg_values_supported"], ["RS256"])
+
+ def test_agrees_with_the_authorization_server_document(self):
+ oidc = openid_provider_metadata("https://us.posthog.com")
+ authorization_server = authorization_server_metadata("https://us.posthog.com")
+
+ shared = set(oidc) & set(authorization_server)
+ self.assertIn("scopes_supported", shared)
+ for field in shared:
+ self.assertEqual(oidc[field], authorization_server[field], f"{field} differs between the two documents")
+
+
+class TestOpenIDProviderMetadataEndpoint(APIBaseTest):
+ def test_discovery_document_is_served_without_authentication(self):
+ self.client.logout()
+
+ response = self.client.get("/.well-known/openid-configuration")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["issuer"], openid_provider_metadata(absolute_uri().rstrip("/"))["issuer"])
+ self.assertEqual(response["Access-Control-Allow-Origin"], "*")
+
+
class TestOAuthClientManifest(APIBaseTest):
"""Tests for the auth.md agent-registration manifest."""
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index d15178b6d401..9e33684413f9 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -27,7 +27,6 @@ from oauth2_provider.oauth2_validators import OAuth2Validator
from oauth2_provider.settings import oauth2_settings
from oauth2_provider.views import (
ClientProtectedScopedResourceView,
- ConnectDiscoveryInfoView,
JwksInfoView,
RevokeTokenView,
TokenView,
@@ -39,6 +38,7 @@ from oauthlib.oauth2 import InvalidClientIdError, InvalidGrantError
from redis.exceptions import RedisError
from rest_framework import serializers, status
from rest_framework.authentication import SessionAuthentication
+from rest_framework.exceptions import NotFound
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
@@ -52,6 +52,7 @@ from posthog.api.oauth.cimd import (
get_or_create_cimd_application,
is_cimd_client_id,
)
+from posthog.api.oauth.claims import OIDC_CLAIMS
from posthog.api.oauth.client_assertion import (
ClientAssertionError,
ResolvedClientAssertion,
@@ -61,6 +62,13 @@ from posthog.api.oauth.client_assertion import (
)
from posthog.api.oauth.client_auth import verify_client_secret
from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context
+from posthog.api.oauth.metadata import (
+ Document,
+ authorization_server_metadata,
+ client_manifest_scopes,
+ openid_provider_metadata,
+ protected_resource_metadata,
+)
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
from posthog.helpers.oauth_pending_connection import (
PendingOAuthConnection,
@@ -74,7 +82,6 @@ from posthog.models.oauth import (
OAuthApplicationAccessLevel,
OAuthGrant,
OAuthRefreshToken,
- TokenEndpointAuthMethod,
lock_oauth_connection,
revoke_oauth_session,
revoke_oauth_token_family,
@@ -84,8 +91,6 @@ from posthog.scopes import (
clamp_scopes_to_ceiling,
downgrade_scopes_to_read_only,
effective_ceiling,
- get_oauth_scopes_supported,
- get_scope_descriptions,
grantable_ceiling,
narrow_scopes_to_ceiling,
resolve_ceiling,
@@ -1024,14 +1029,11 @@ class OAuthValidator(OAuth2Validator):
return
return super().revoke_token(token, token_type_hint, request, *args, **kwargs)
- def get_additional_claims(self, request):
- return {
- "given_name": request.user.first_name,
- "family_name": request.user.last_name,
- "email": request.user.email,
- "email_verified": request.user.is_email_verified or False,
- "sub": str(request.user.uuid),
- }
+ def get_additional_claims(self):
+ """Takes no request argument because django-oauth-toolkit derives `claims_supported`
+ only from a request-agnostic override (`_get_additional_claims_is_request_agnostic`).
+ """
+ return dict(OIDC_CLAIMS)
def _sessions_revoked_at(self, application_id: uuid.UUID) -> datetime | None:
return OAuthApplication.objects.filter(pk=application_id).values_list("sessions_revoked_at", flat=True).first()
@@ -2408,10 +2410,6 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
return self.get_token_response(request, token)
-class OAuthConnectDiscoveryInfoView(ConnectDiscoveryInfoView):
- pass
-
-
class OAuthJwksInfoView(JwksInfoView):
pass
@@ -2434,6 +2432,23 @@ class _PublicMetadataView(APIView):
def base_url(self) -> str:
return absolute_uri().rstrip("/")
+ def document(self, metadata: Document) -> JsonResponse:
+ response = JsonResponse(metadata)
+ response["Access-Control-Allow-Origin"] = "*"
+ return response
+
+
+class OAuthConnectDiscoveryInfoView(_PublicMetadataView):
+ """
+ OpenID Provider Metadata (OpenID Connect Discovery 1.0).
+ """
+
+ def get(self, request, *args, **kwargs):
+ if not oauth2_settings.OIDC_ENABLED:
+ raise NotFound()
+
+ return self.document(openid_provider_metadata(self.base_url()))
+
class OAuthAuthorizationServerMetadataView(_PublicMetadataView):
"""
@@ -2447,103 +2462,14 @@ class OAuthAuthorizationServerMetadataView(_PublicMetadataView):
"""
def get(self, request, *args, **kwargs):
- base_url = self.base_url()
-
- all_scopes = get_oauth_scopes_supported()
-
- metadata = {
- # Required by RFC 8414
- "issuer": base_url,
- "authorization_endpoint": f"{base_url}/oauth/authorize/",
- "token_endpoint": f"{base_url}/oauth/token/",
- # Other endpoints
- "revocation_endpoint": f"{base_url}/oauth/revoke/",
- "introspection_endpoint": f"{base_url}/oauth/introspect/",
- "userinfo_endpoint": f"{base_url}/oauth/userinfo/",
- "jwks_uri": f"{base_url}/.well-known/jwks.json",
- # Dynamic Client Registration (RFC 7591)
- "registration_endpoint": f"{base_url}/oauth/register/",
- # Supported features
- "scopes_supported": all_scopes,
- "response_types_supported": ["code"],
- "response_modes_supported": ["query"],
- "grant_types_supported": [
- "authorization_code",
- "refresh_token",
- id_jag.JWT_BEARER_GRANT_TYPE,
- ],
- "authorization_grant_profiles_supported": [id_jag.ID_JAG_GRANT_PROFILE],
- # Every method a client can register under (including CIMD's private_key_jwt) must
- # appear here, or a client reads this document, picks a method we do not accept, and
- # fails the token exchange.
- "token_endpoint_auth_methods_supported": [
- TokenEndpointAuthMethod.NONE.value,
- TokenEndpointAuthMethod.CLIENT_SECRET_POST.value,
- TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value,
- ],
- "code_challenge_methods_supported": ["S256"],
- # Service documentation
- "service_documentation": "https://posthog.com/docs/api",
- # Client ID Metadata Document (draft-ietf-oauth-client-id-metadata-document-00)
- "client_id_metadata_document_supported": True,
- # auth.md agent registration profile (https://workos.com/auth-md).
- # Only flows that actually exist are advertised: ID-JAG identity
- # assertions at the identity endpoint. The user-claimed device flow
- # (claim_endpoint) and revocation receiver (events_endpoint) are not
- # built yet, so they are deliberately omitted rather than advertised.
- "agent_auth": {
- "skill": f"{base_url}/auth.md",
- "identity_endpoint": f"{base_url}/oauth/token/",
- "identity_types_supported": ["identity_assertion"],
- "identity_assertion": {
- "assertion_types_supported": ["urn:ietf:params:oauth:token-type:id-jag"],
- },
- },
- }
-
- if region_info := get_region_info():
- metadata.update(region_info)
-
- return JsonResponse(metadata)
+ return self.document(authorization_server_metadata(self.base_url(), get_region_info()))
class OAuthProtectedResourceMetadataView(_PublicMetadataView):
- """
- OAuth 2.0 Protected Resource Metadata (RFC 9728).
-
- PostHog already points agents at this document via the
- `WWW-Authenticate: Bearer resource_metadata=...` header on 401 responses
- (see posthog/exceptions.py). This serves the document it promises, letting
- a client that hit a 401 discover which authorization server issues tokens
- for this API, which scopes exist, and how to present the token.
- """
+ """OAuth 2.0 Protected Resource Metadata (RFC 9728)."""
def get(self, request, *args, **kwargs):
- base_url = self.base_url()
-
- metadata = {
- # Required by RFC 9728
- "resource": base_url,
- # The same PostHog instance is its own authorization server
- "authorization_servers": [base_url],
- "scopes_supported": get_oauth_scopes_supported(),
- "bearer_methods_supported": ["header"],
- "resource_documentation": "https://posthog.com/docs/api",
- }
-
- return JsonResponse(metadata)
-
-
-# Identity and token-management scopes have no entry in get_scope_descriptions(),
-# which only covers obj:action scopes. Every bare scope in
-# `get_oauth_scopes_supported()` needs a line here, or the manifest prints the
-# scope name where its description belongs.
-_IDENTITY_SCOPE_DESCRIPTIONS = {
- "openid": "Sign in and read your user identifier",
- "profile": "Read your basic profile",
- "email": "Read your email address",
- "introspection": "Check whether a token you hold is still valid",
-}
+ return self.document(protected_resource_metadata(self.base_url()))
class OAuthClientManifestView(_PublicMetadataView):
@@ -2556,17 +2482,9 @@ class OAuthClientManifestView(_PublicMetadataView):
"""
def get(self, request, *args, **kwargs):
- base_url = self.base_url()
-
- descriptions = get_scope_descriptions()
- scopes = [
- (scope, descriptions[scope] if scope in descriptions else _IDENTITY_SCOPE_DESCRIPTIONS.get(scope, scope))
- for scope in get_oauth_scopes_supported()
- ]
-
return render(
request,
"auth_md.md",
- {"base_url": base_url, "scopes": scopes},
+ {"base_url": self.base_url(), "scopes": client_manifest_scopes()},
content_type="text/markdown; charset=utf-8",
)
diff --git a/posthog/templates/auth_md.md b/posthog/templates/auth_md.md
index c25964f77496..147f629e1743 100644
--- a/posthog/templates/auth_md.md
+++ b/posthog/templates/auth_md.md
@@ -25,7 +25,7 @@ The user-claimed device flow (`service_auth`, `anonymous`) is not supported yet.
## Scopes
-{% for scope, description in scopes %}- `{{ scope }}`: {{ description }}
+{% for scope in scopes %}- `{{ scope.name }}`: {{ scope.description }}
{% endfor %}
## Changing scopes
diff --git a/services/oauth-proxy/README.md b/services/oauth-proxy/README.md
index ec9273d7567d..0ecf434224d9 100644
--- a/services/oauth-proxy/README.md
+++ b/services/oauth-proxy/README.md
@@ -7,14 +7,16 @@ Without it, every integration would have to ship two sets of OAuth URLs and ask
The PostHog MCP server and PostHog Desktop both point at this worker, and new integrations should too.
The worker is stateless apart from a KV namespace (`AUTH_KV`) that remembers which region a flow picked and the client registrations it created in each region.
-It never issues or validates tokens itself; the regional PostHog instances still do all of that.
+Access tokens are issued and validated only by the regional PostHog instances.
+The one exception is the OpenID Connect ID token: the worker verifies the regional one and signs it again under its own issuer, because the claims a relying party checks (`iss` and `aud`) have to name this proxy and the client's own `client_id`. See [ID tokens](#id-tokens).
## Routes
| Method | Path | Description |
| ------ | ----------------------------------------- | ---------------------------------------------------------------------------------- |
| `GET` | `/.well-known/oauth-authorization-server` | RFC 8414 metadata, fetched from US and rewritten to point at the proxy (10m cache) |
-| `GET` | `/.well-known/jwks.json` | Proxied to US (keys are identical across regions) |
+| `GET` | `/.well-known/openid-configuration` | OIDC discovery, fetched from US and rewritten the same way (10m cache) |
+| `GET` | `/.well-known/jwks.json` | This proxy's signing keys, plus the regional keys |
| `POST` | `/oauth/register`, `/register` | RFC 7591 dynamic registration, run against both regions at once |
| `GET` | `/oauth/authorize`, `/authorize` | Region picker page, then redirect to the regional authorize endpoint |
| `GET` | `/oauth/callback` | Receives the regional callback and forwards it to the client's `redirect_uri` |
@@ -54,6 +56,46 @@ Clients registered directly against a region keep their own `redirect_uri` and f
- `refresh_token` grants fall back to trying each region with the correctly rewritten `client_id`, then re-store the winner so later refreshes take the fast path.
- When both regions reject a request, the 4xx is forwarded in preference to the 5xx: a 4xx carries the OAuth error code the client acts on, while a 5xx only means one region was unhealthy.
+## ID tokens
+
+A regional server signs an ID token with its own issuer (`https://us.posthog.com` or `https://eu.posthog.com`) and with the regional `client_id` as the audience.
+A client that discovered this proxy knows neither value: it reads `https://oauth.posthog.com` as the issuer, and it holds the proxy `client_id`, which is the US one.
+Both claims fail the checks a conformant OpenID relying party runs, and the audience is wrong for every EU user.
+
+So `/oauth/token` verifies the regional ID token against that region's published keys, then signs the same claims again with this worker's key, under the proxy issuer and the client's own `client_id`.
+`iat` and `exp` are copied rather than recomputed, so re-issuing can neither extend a token nor invent an authentication event.
+Responses with no `id_token` pass through untouched, which covers the ID-JAG exchange and every client that did not request the `openid` scope.
+
+The `client_id` a token request posts is not authenticated, so the proxy only signs it as the audience when the regional token was issued to a client id that belongs to it: the same id, or one side of its stored mapping.
+Anything else is refused with a 500 rather than re-addressed, because the region authenticated a different client than the one the request named.
+`/oauth/token` also rejects a body that repeats `client_id`, `grant_type`, `code`, `refresh_token`, `redirect_uri`, `code_verifier`, or `client_secret`.
+The proxy reads the first value of a repeated parameter and Django reads the last, so a repeat is a way to make the two disagree about which client is exchanging the grant.
+
+`/.well-known/jwks.json` publishes this worker's keys next to the regional ones.
+The regional keys stay because the regional servers also sign the ID-JAG access tokens (`at+jwt`) that clients receive through this proxy.
+Key ids differ, so a verifier selects the right key on its own.
+
+### Signing keys
+
+| Secret | Role |
+| ----------------------------- | ------------------------------------------------------ |
+| `OIDC_SIGNING_KEY` | PKCS#8 PEM. Signs every ID token the proxy issues. |
+| `OIDC_SIGNING_KEY_INACTIVE_1` | PKCS#8 PEM. Published in JWKS, never used for signing. |
+
+Generate a key with:
+
+```sh
+openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -outform PEM -out oidc-signing-key.pem
+```
+
+Pipe it into `wrangler secret put OIDC_SIGNING_KEY`, or paste the file's contents into the Cloudflare dashboard as a secret on the `oauth-proxy` worker.
+The worker also accepts a PEM whose newlines are written as `\n`, matching how the Django `OIDC_RSA_PRIVATE_KEY` setting is stored.
+Delete the local file once the secret is set.
+
+To rotate, move the current key to `OIDC_SIGNING_KEY_INACTIVE_1`, set the new one as `OIDC_SIGNING_KEY`, and drop the old one after the longest ID token lifetime has passed.
+
+Without `OIDC_SIGNING_KEY` the worker serves the regional ID token unchanged and logs `id_token: passthrough_no_signing_key`, so deploying the code before the secret exists degrades to today's behavior instead of failing token exchanges.
+
## KV keys
| Key | TTL | Value |
@@ -91,3 +133,4 @@ pnpm --filter @posthog/auth-proxy deploy
This needs Cloudflare credentials for the PostHog account.
The worker name, KV binding, and observability settings live in `wrangler.jsonc`.
+Secrets are not in that file. wrangler has no declaration for a `secret put` secret, so `wrangler.jsonc` only names them in a comment and the typed contract lives on `Env` in `src/index.ts`.
diff --git a/services/oauth-proxy/package.json b/services/oauth-proxy/package.json
index fb2fa816632f..4cef72433000 100644
--- a/services/oauth-proxy/package.json
+++ b/services/oauth-proxy/package.json
@@ -19,6 +19,9 @@
"test:watch": "vitest watch",
"typecheck": "tsgo --noEmit"
},
+ "dependencies": {
+ "jose": "^6.2.3"
+ },
"devDependencies": {
"@cloudflare/workers-types": "^4.20260120.0",
"typescript": "catalog:",
diff --git a/services/oauth-proxy/src/handlers/metadata.ts b/services/oauth-proxy/src/handlers/metadata.ts
index ae4fbd9ca4c0..2224818c05b7 100644
--- a/services/oauth-proxy/src/handlers/metadata.ts
+++ b/services/oauth-proxy/src/handlers/metadata.ts
@@ -1,56 +1,82 @@
+import { POSTHOG_US_BASE_URL, proxyOrigin } from '@/lib/constants'
+
/**
- * OAuth 2.0 Authorization Server Metadata (RFC 8414)
- *
- * Returns metadata pointing to oauth.posthog.com endpoints.
- * MCP clients and other OAuth integrations use this to discover where to register,
- * authorize, and exchange tokens.
- *
- * We always cache the information exposed by the authoritative source - us.posthog.com
- * and simply alter the endpoint-related fields to point to oauth.posthog.com.
- *
- * The actual underlying metadata is defined in posthog/api/oauth/views.py#OAuthAuthorizationServerMetadataView.get()
+ * Discovery documents, fetched from the authoritative source (us.posthog.com) and rewritten so
+ * every endpoint they name points at this proxy. Both are built in posthog/api/oauth/metadata.py.
*/
-interface WellKnownOAuthAuthorizationServerMetadata {
- issuer: string
- authorization_endpoint: string
- token_endpoint: string
- revocation_endpoint: string
- introspection_endpoint: string
- userinfo_endpoint: string
- jwks_uri: string
- registration_endpoint: string
- scopes_supported: string[]
- 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
- client_id_metadata_document_supported: boolean
+const CACHE_TTL_MS = 600 * 1000
+
+const MANIFEST_PATH = '/auth.md'
+
+// `posthog_base_url` names the region a token came from rather than an endpoint to call, so it
+// keeps its regional value while every other regional URL is rewritten.
+const REGIONAL_VALUE_FIELDS = ['posthog_base_url']
+
+type Metadata = Record<string, unknown>
+
+interface CachedDocument {
+ body: string
+ cachedUntil: number
}
-let authoritativeMetadataCache: WellKnownOAuthAuthorizationServerMetadata | null = null
-let cachedUntil: Date | null = null
+const cache = new Map<string, CachedDocument>()
-// We do not have to worry about local development since the proxy is not used when developing the MCP locally.
-async function fetchAuthoritativeMetadata(): Promise<WellKnownOAuthAuthorizationServerMetadata> {
- const response = await fetch('https://us.posthog.com/.well-known/oauth-authorization-server')
+async function fetchAuthoritativeMetadata(path: string): Promise<Metadata> {
+ const response = await fetch(`${POSTHOG_US_BASE_URL}${path}`)
if (!response.ok) {
- throw new Error(`Failed to fetch authoritative metadata: ${response.statusText}`)
+ throw new Error(`Failed to fetch ${path}: ${response.statusText}`)
}
- return response.json() as Promise<WellKnownOAuthAuthorizationServerMetadata>
+ return response.json() as Promise<Metadata>
}
-export async function handleMetadata(request: Request): Promise<Response> {
- if (!authoritativeMetadataCache || !cachedUntil || cachedUntil < new Date()) {
+/**
+ * Walk a document and point every `us.posthog.com` URL in it at this proxy, at whatever depth the
+ * field sits (`agent_auth.skill` is nested two levels down).
+ *
+ * Matching on the URL rather than on a list of field names means an endpoint added to
+ * posthog/api/oauth/metadata.py is rewritten here without a matching change.
+ */
+function rewriteEndpoints(value: unknown, origin: string): unknown {
+ if (typeof value === 'string') {
+ return value.startsWith(POSTHOG_US_BASE_URL) ? `${origin}${value.slice(POSTHOG_US_BASE_URL.length)}` : value
+ }
+
+ if (Array.isArray(value)) {
+ return value.map((item) => rewriteEndpoints(item, origin))
+ }
+
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value as Metadata).map(([field, nested]) => [
+ field,
+ REGIONAL_VALUE_FIELDS.includes(field) ? nested : rewriteEndpoints(nested, origin),
+ ])
+ )
+ }
+
+ return value
+}
+
+async function serveDocument(request: Request, path: string): Promise<Response> {
+ const origin = proxyOrigin(request)
+ const cacheKey = `${path}|${origin}`
+ const cached = cache.get(cacheKey)
+
+ if (!cached || cached.cachedUntil <= Date.now()) {
try {
- authoritativeMetadataCache = await fetchAuthoritativeMetadata()
- cachedUntil = new Date(Date.now() + 600 * 1000) // cache for 10 minutes (600 seconds)
+ const metadata = await fetchAuthoritativeMetadata(path)
+ const body = JSON.stringify(rewriteEndpoints(metadata, origin))
+ cache.set(cacheKey, { body, cachedUntil: Date.now() + CACHE_TTL_MS })
} catch (error) {
- console.error('Failed to fetch metadata:', error)
+ console.error(
+ JSON.stringify({
+ handler: 'metadata',
+ path,
+ error: error instanceof Error ? error.message : 'unknown error',
+ })
+ )
return new Response(
JSON.stringify({
error: 'server_error',
@@ -61,26 +87,58 @@ export async function handleMetadata(request: Request): Promise<Response> {
}
}
- const url = new URL(request.url)
- const baseUrl = `${url.protocol}//${url.host}`
-
- // Alter the endpoint-related fields to point to the oauth.posthog.com base domain.
- const metadata: WellKnownOAuthAuthorizationServerMetadata = {
- ...authoritativeMetadataCache,
- issuer: baseUrl,
- authorization_endpoint: `${baseUrl}/oauth/authorize/`,
- token_endpoint: `${baseUrl}/oauth/token/`,
- revocation_endpoint: `${baseUrl}/oauth/revoke/`,
- introspection_endpoint: `${baseUrl}/oauth/introspect/`,
- userinfo_endpoint: `${baseUrl}/oauth/userinfo/`,
- jwks_uri: `${baseUrl}/.well-known/jwks.json`,
- registration_endpoint: `${baseUrl}/oauth/register/`,
+ return new Response(cache.get(cacheKey)!.body, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Cache-Control': 'public, max-age=3600',
+ 'Access-Control-Allow-Origin': '*',
+ },
+ })
+}
+
+export async function handleMetadata(request: Request): Promise<Response> {
+ return serveDocument(request, '/.well-known/oauth-authorization-server')
+}
+
+export async function handleOpenIdConfiguration(request: Request): Promise<Response> {
+ return serveDocument(request, '/.well-known/openid-configuration')
+}
+
+/**
+ * The auth.md agent manifest, which the authorization server metadata points at through
+ * `agent_auth.skill`. Markdown rather than JSON, so the rewrite is a plain substitution: every URL
+ * in the document is built from the serving instance's base URL.
+ */
+export async function handleClientManifest(request: Request): Promise<Response> {
+ const origin = proxyOrigin(request)
+ const cacheKey = `${MANIFEST_PATH}|${origin}`
+ const cached = cache.get(cacheKey)
+
+ if (!cached || cached.cachedUntil <= Date.now()) {
+ try {
+ const response = await fetch(`${POSTHOG_US_BASE_URL}${MANIFEST_PATH}`)
+ if (!response.ok) {
+ throw new Error(`Failed to fetch ${MANIFEST_PATH}: ${response.statusText}`)
+ }
+
+ const body = (await response.text()).split(POSTHOG_US_BASE_URL).join(origin)
+ cache.set(cacheKey, { body, cachedUntil: Date.now() + CACHE_TTL_MS })
+ } catch (error) {
+ console.error(
+ JSON.stringify({
+ handler: 'manifest',
+ error: error instanceof Error ? error.message : 'unknown error',
+ })
+ )
+ return new Response('Unable to fetch the client manifest', { status: 502 })
+ }
}
- return new Response(JSON.stringify(metadata), {
+ return new Response(cache.get(cacheKey)!.body, {
headers: {
- 'Content-Type': 'application/json',
+ 'Content-Type': 'text/markdown; charset=utf-8',
'Cache-Control': 'public, max-age=3600',
+ 'Access-Control-Allow-Origin': '*',
},
})
}
diff --git a/services/oauth-proxy/src/handlers/passthrough.ts b/services/oauth-proxy/src/handlers/passthrough.ts
index faa95fbb7272..87fdee0838fe 100644
--- a/services/oauth-proxy/src/handlers/passthrough.ts
+++ b/services/oauth-proxy/src/handlers/passthrough.ts
@@ -1,4 +1,5 @@
-import { POSTHOG_EU_BASE_URL, POSTHOG_US_BASE_URL } from '@/lib/constants'
+import { POSTHOG_EU_BASE_URL, POSTHOG_US_BASE_URL, type Region } from '@/lib/constants'
+import { type SigningKeyEnv, proxyJwks } from '@/lib/idtoken'
import { getClientMapping, getRegionSelection } from '@/lib/kv'
import { proxyPostWithClientId, proxyToRegion, tryBothRegions } from '@/lib/proxy'
import { errorResponse } from '@/lib/validation'
@@ -7,6 +8,11 @@ import { errorResponse } from '@/lib/validation'
* Passthrough handlers for OAuth endpoints that simply need to reach the correct region.
*/
+// Every relying party fetches this on its first ID token verification. Signing keys rotate in months.
+const JWKS_CACHE_TTL_MS = 600 * 1000
+
+let cachedJwks: { body: string; cachedUntil: number } | null = null
+
/**
* Revoke token — route to the correct region based on client_id, fallback to try-both.
*/
@@ -63,10 +69,83 @@ export async function handleUserInfo(request: Request): Promise<Response> {
}
/**
- * JWKS — proxy to US (keys should be the same across regions).
+ * JWKS — this proxy's signing keys, plus the regional ones.
+ *
+ * The regional keys stay published because the regional servers also sign the ID-JAG access
+ * tokens (`at+jwt`) clients receive through this proxy. Key ids differ, so a verifier selects
+ * the right key on its own.
*/
-export async function handleJwks(request: Request): Promise<Response> {
- return proxyToRegion(request, 'us', '/.well-known/jwks.json')
+export async function handleJwks(request: Request, _kv: KVNamespace, env: SigningKeyEnv): Promise<Response> {
+ const cached = cachedJwks && cachedJwks.cachedUntil > Date.now() ? cachedJwks.body : null
+ if (cached) {
+ return jwksResponse(cached)
+ }
+
+ const [proxyKeys, ...regional] = await Promise.all([
+ proxyJwks(env),
+ regionalKeys(request, 'us'),
+ regionalKeys(request, 'eu'),
+ ])
+
+ // A relying party verifying an ID token this worker issued needs no regional key, so failing
+ // the whole document would break that verification for as long as both regions are down.
+ if (proxyKeys.length === 0 && regional.every((keys) => keys.length === 0)) {
+ return new Response(JSON.stringify({ error: 'server_error' }), {
+ status: 502,
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
+ })
+ }
+
+ const body = JSON.stringify({ keys: dedupeByKid([...proxyKeys, ...regional.flat()]) })
+
+ // A document missing a region's keys leaves tokens from that region unverifiable, so it is
+ // served once but never held: the next request retries the region that failed.
+ const complete = regional.every((keys) => keys.length > 0)
+ if (complete) {
+ cachedJwks = { body, cachedUntil: Date.now() + JWKS_CACHE_TTL_MS }
+ }
+
+ return jwksResponse(body, complete)
+}
+
+/** A region that is unreachable contributes nothing rather than failing the whole document. */
+async function regionalKeys(request: Request, region: Region): Promise<unknown[]> {
+ try {
+ const response = await proxyToRegion(request, region, '/.well-known/jwks.json')
+ if (response.ok) {
+ const body = (await response.json()) as { keys?: unknown }
+ // A non-array `keys` passes the emptiness check in `handleJwks` on its own length,
+ // which would publish and cache it as a key.
+ return Array.isArray(body.keys) ? body.keys : []
+ }
+ console.error(JSON.stringify({ handler: 'jwks', region, status: response.status }))
+ } catch {
+ console.error(JSON.stringify({ handler: 'jwks', region, error: 'unreachable' }))
+ }
+
+ return []
+}
+
+function dedupeByKid(keys: unknown[]): unknown[] {
+ const seen = new Set<string>()
+ return keys.filter((key) => {
+ const kid = (key as { kid?: string }).kid
+ if (!kid || seen.has(kid)) {
+ return !kid
+ }
+ seen.add(kid)
+ return true
+ })
+}
+
+function jwksResponse(body: string, complete = true): Response {
+ return new Response(body, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Cache-Control': complete ? `public, max-age=${JWKS_CACHE_TTL_MS / 1000}` : 'no-store',
+ 'Access-Control-Allow-Origin': '*',
+ },
+ })
}
async function routeByClientId(request: Request, kv: KVNamespace, path: string): Promise<Response> {
diff --git a/services/oauth-proxy/src/handlers/token.ts b/services/oauth-proxy/src/handlers/token.ts
index bf5f5a1b379f..b100bf9cbb40 100644
--- a/services/oauth-proxy/src/handlers/token.ts
+++ b/services/oauth-proxy/src/handlers/token.ts
@@ -1,4 +1,5 @@
-import type { Region } from '@/lib/constants'
+import { type Region, proxyOrigin } from '@/lib/constants'
+import { type SigningKeyEnv } from '@/lib/idtoken'
import {
getCallbackRedirectUri,
getClientMapping,
@@ -7,7 +8,23 @@ import {
resolveMappingRewrite,
} from '@/lib/kv'
import { preferClientError, proxyPostWithClientId, tryBothRegions } from '@/lib/proxy'
-import { errorResponse } from '@/lib/validation'
+import { reissueIdTokenInResponse } from '@/lib/token-response'
+import { duplicateParamError, errorResponse, findDuplicateParam } from '@/lib/validation'
+
+/** RFC 7523, which PostHog serves as the ID-JAG identity assertion exchange. */
+const JWT_BEARER_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
+
+// The proxy reads a form body with `.get()`, which returns the first value, while Django's
+// QueryDict returns the last. A repeat lets the two authenticate different clients.
+const SINGLE_VALUE_TOKEN_PARAMS = [
+ 'client_id',
+ 'client_secret',
+ 'grant_type',
+ 'code',
+ 'code_verifier',
+ 'refresh_token',
+ 'redirect_uri',
+] as const
/**
* OAuth Token Exchange — proxy to the correct region.
@@ -17,7 +34,7 @@ import { errorResponse } from '@/lib/validation'
* For refresh_token grants, we fall back to try-both since the client may not
* have gone through our authorize flow.
*/
-export async function handleToken(request: Request, kv: KVNamespace): Promise<Response> {
+export async function handleToken(request: Request, kv: KVNamespace, env: SigningKeyEnv): Promise<Response> {
const body = await request.text()
const contentType = request.headers.get('content-type') || ''
@@ -37,10 +54,46 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Re
}
} else {
const formParams = new URLSearchParams(body)
+ const duplicate = findDuplicateParam(formParams, SINGLE_VALUE_TOKEN_PARAMS)
+ if (duplicate) {
+ return errorResponse(duplicateParamError(duplicate), { 'Cache-Control': 'no-store' })
+ }
clientId = formParams.get('client_id')
grantType = formParams.get('grant_type')
}
+ const response = await routeToken(request, kv, body, clientId, grantType)
+
+ if (grantType === JWT_BEARER_GRANT_TYPE) {
+ // An ID-JAG exchange returns an access token and no ID token, so it has nothing to re-issue.
+ return response
+ }
+
+ return reissueIdTokenInResponse(response, {
+ issuer: proxyOrigin(request),
+ audience: clientId,
+ permittedUpstreamAudiences: response.ok && clientId ? await permittedUpstreamAudiences(kv, clientId) : [],
+ env,
+ })
+}
+
+/** A client registered through the proxy is known to each region under its own id. */
+async function permittedUpstreamAudiences(kv: KVNamespace, clientId: string): Promise<string[]> {
+ const mapping = await getClientMapping(kv, clientId)
+ if (!mapping) {
+ return [clientId]
+ }
+
+ return [clientId, mapping.us_client_id, mapping.eu_client_id].filter((id) => Boolean(id))
+}
+
+async function routeToken(
+ request: Request,
+ kv: KVNamespace,
+ body: string,
+ clientId: string | null,
+ grantType: string | null
+): Promise<Response> {
const clientIdPrefix = clientId?.slice(0, 8) ?? 'none'
const rebuild = (): Request =>
@@ -50,6 +103,24 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Re
body,
})
+ // The regional server checks the assertion's `client_id` claim against the posted one
+ // (posthog/api/id_jag.py), so rewriting it to the regional id fails on EU. This grant needs
+ // no rewrite: the assertion is the credential and no OAuth application is looked up.
+ if (grantType === JWT_BEARER_GRANT_TYPE) {
+ const { response, region } = await tryBothRegions(rebuild(), '/oauth/token/')
+ console.info(
+ JSON.stringify({
+ handler: 'token',
+ grant_type: grantType,
+ client_id_prefix: clientIdPrefix,
+ region_source: 'try_both_no_rewrite',
+ resolved_region: region,
+ status: response.status,
+ })
+ )
+ return response
+ }
+
// Look up region by client_id (stored during the authorize step)
if (clientId) {
const region = await getRegionSelection(kv, clientId)
diff --git a/services/oauth-proxy/src/index.ts b/services/oauth-proxy/src/index.ts
index 1216b31a4a4d..eeed9198f835 100644
--- a/services/oauth-proxy/src/index.ts
+++ b/services/oauth-proxy/src/index.ts
@@ -9,17 +9,18 @@
*/
import { handleAuthorize } from '@/handlers/authorize'
import { handleCallback } from '@/handlers/callback'
-import { handleMetadata } from '@/handlers/metadata'
+import { handleClientManifest, handleMetadata, handleOpenIdConfiguration } from '@/handlers/metadata'
import { handleIntrospect, handleJwks, handleRevoke, handleUserInfo } from '@/handlers/passthrough'
import { handleRegister } from '@/handlers/register'
import { handleToken } from '@/handlers/token'
+import type { SigningKeyEnv } from '@/lib/idtoken'
import { type Validator, errorResponse, noDuplicateParams, runValidators } from '@/lib/validation'
-export interface Env {
+export interface Env extends SigningKeyEnv {
AUTH_KV: KVNamespace
}
-type Handler = (request: Request, kv: KVNamespace) => Response | Promise<Response>
+type Handler = (request: Request, kv: KVNamespace, env: Env) => Response | Promise<Response>
interface Route {
paths: string[]
@@ -37,6 +38,14 @@ const routes: Route[] = [
paths: ['/.well-known/oauth-authorization-server'],
handler: handleMetadata,
},
+ {
+ paths: ['/.well-known/openid-configuration'],
+ handler: handleOpenIdConfiguration,
+ },
+ {
+ paths: ['/auth.md'],
+ handler: handleClientManifest,
+ },
{
paths: ['/.well-known/jwks.json'],
handler: handleJwks,
@@ -107,7 +116,7 @@ export default {
return errorResponse(validationError)
}
}
- return await route.handler(request, env.AUTH_KV)
+ return await route.handler(request, env.AUTH_KV, env)
}
}
diff --git a/services/oauth-proxy/src/lib/constants.ts b/services/oauth-proxy/src/lib/constants.ts
index fda74b92b27b..d0744775d0e9 100644
--- a/services/oauth-proxy/src/lib/constants.ts
+++ b/services/oauth-proxy/src/lib/constants.ts
@@ -15,3 +15,12 @@ export function toRegion(value: string | undefined | null): Region {
export function baseUrlForRegion(region: Region): string {
return REGION_BASE_URLS[region]
}
+
+export function regionForBaseUrl(baseUrl: string): Region | null {
+ const match = Object.entries(REGION_BASE_URLS).find(([, url]) => url === baseUrl)
+ return match ? (match[0] as Region) : null
+}
+
+export function proxyOrigin(request: Request): string {
+ return new URL(request.url).origin
+}
diff --git a/services/oauth-proxy/src/lib/idtoken.ts b/services/oauth-proxy/src/lib/idtoken.ts
new file mode 100644
index 000000000000..d1d7d0830a3b
--- /dev/null
+++ b/services/oauth-proxy/src/lib/idtoken.ts
@@ -0,0 +1,153 @@
+import { type JWK, SignJWT, calculateJwkThumbprint, createRemoteJWKSet, exportJWK, importPKCS8, jwtVerify } from 'jose'
+
+import { type Region, baseUrlForRegion } from './constants'
+
+/**
+ * ID token re-issuance.
+ *
+ * A regional server signs an ID token with its own issuer and with the regional `client_id` as
+ * the audience. A client that discovered this proxy knows neither value, so both claims fail the
+ * checks a conformant OpenID relying party runs. See the README section on ID tokens.
+ */
+
+export interface SigningKeyEnv {
+ /** PKCS#8 PEM that signs the ID tokens this proxy issues. See the README for rotation. */
+ OIDC_SIGNING_KEY?: string
+ /** Published in JWKS but never used for signing, so a rotation can retire a key without
+ * invalidating the tokens it already signed. Mirrors `OIDC_RSA_PRIVATE_KEY_INACTIVE_*`. */
+ OIDC_SIGNING_KEY_INACTIVE_1?: string
+ OIDC_SIGNING_KEY_INACTIVE_2?: string
+}
+
+interface ProxyKey {
+ privateKey: CryptoKey
+ publicJwk: JWK
+ kid: string
+}
+
+export class IdTokenReissueError extends Error {}
+
+const SIGNING_ALGORITHM = 'RS256'
+
+type KeySlot = 'active' | 'inactive_1' | 'inactive_2'
+
+const keyCache = new Map<KeySlot, Promise<ProxyKey>>()
+
+const regionalJwks = new Map<Region, ReturnType<typeof createRemoteJWKSet>>()
+
+/** Cloudflare's secret editor stores a PEM as a single line, so accept the escaped form too. */
+function normalizePem(raw: string): string {
+ return raw.replace(/\\n/g, '\n').trim()
+}
+
+async function loadKey(slot: KeySlot, pem: string): Promise<ProxyKey> {
+ const cached = keyCache.get(slot)
+ if (cached) {
+ return cached
+ }
+
+ const normalized = normalizePem(pem)
+
+ const loading = (async (): Promise<ProxyKey> => {
+ // Exportable because the public half of this key has to be derived for the JWKS document.
+ const privateKey = await importPKCS8(normalized, SIGNING_ALGORITHM, { extractable: true })
+ const fullJwk = await exportJWK(privateKey)
+ const publicJwk: JWK = { kty: fullJwk.kty, n: fullJwk.n, e: fullJwk.e }
+ const kid = await calculateJwkThumbprint(publicJwk)
+ return { privateKey, publicJwk, kid }
+ })()
+
+ keyCache.set(slot, loading)
+ return loading
+}
+
+async function activeSigningKey(env: SigningKeyEnv): Promise<ProxyKey> {
+ if (!env.OIDC_SIGNING_KEY) {
+ throw new IdTokenReissueError('No signing key is configured')
+ }
+
+ return loadKey('active', env.OIDC_SIGNING_KEY)
+}
+
+export async function proxyJwks(env: SigningKeyEnv): Promise<JWK[]> {
+ const pems: [KeySlot, string | undefined][] = [
+ ['active', env.OIDC_SIGNING_KEY],
+ ['inactive_1', env.OIDC_SIGNING_KEY_INACTIVE_1],
+ ['inactive_2', env.OIDC_SIGNING_KEY_INACTIVE_2],
+ ]
+ const keys = await Promise.all(pems.filter(([, pem]) => pem).map(([slot, pem]) => loadKey(slot, pem as string)))
+
+ return keys.map((key) => ({ ...key.publicJwk, alg: SIGNING_ALGORITHM, use: 'sig', kid: key.kid }))
+}
+
+function jwksForRegion(region: Region): ReturnType<typeof createRemoteJWKSet> {
+ const cached = regionalJwks.get(region)
+ if (cached) {
+ return cached
+ }
+
+ const jwks = createRemoteJWKSet(new URL('/.well-known/jwks.json', baseUrlForRegion(region)))
+ regionalJwks.set(region, jwks)
+ return jwks
+}
+
+/**
+ * `requested` is the `client_id` the caller posted, which nothing has authenticated. Signing it
+ * over a grant the region authenticated for a different client would address that user's identity
+ * claims to a client the grant was never issued to.
+ */
+function resolveAudience(requested: string | null, upstream: unknown, permittedUpstream: string[]): string {
+ if (typeof upstream !== 'string') {
+ throw new IdTokenReissueError('Regional ID token has no single audience')
+ }
+
+ if (requested === null) {
+ return upstream
+ }
+
+ if (!permittedUpstream.includes(upstream)) {
+ throw new IdTokenReissueError('Regional ID token was issued to a different client')
+ }
+
+ return requested
+}
+
+/** Verification runs first so the proxy never signs claims it has not checked. */
+export async function reissueIdToken(
+ idToken: string,
+ options: {
+ region: Region
+ issuer: string
+ audience: string | null
+ permittedUpstreamAudiences: string[]
+ env: SigningKeyEnv
+ }
+): Promise<string> {
+ const active = await activeSigningKey(options.env)
+
+ let payload: Record<string, unknown>
+ try {
+ const verified = await jwtVerify(idToken, jwksForRegion(options.region))
+ payload = verified.payload as Record<string, unknown>
+ } catch (error) {
+ throw new IdTokenReissueError(
+ `Regional ID token failed verification: ${error instanceof Error ? error.message : 'unknown error'}`
+ )
+ }
+
+ const { iss: _iss, aud: upstreamAudience, jti: _jti, iat, exp, ...claims } = payload
+ if (typeof iat !== 'number' || typeof exp !== 'number') {
+ throw new IdTokenReissueError('Regional ID token is missing iat or exp')
+ }
+
+ const audience = resolveAudience(options.audience, upstreamAudience, options.permittedUpstreamAudiences)
+
+ return new SignJWT(claims)
+ .setProtectedHeader({ alg: SIGNING_ALGORITHM, kid: active.kid })
+ .setIssuer(options.issuer)
+ .setAudience(audience)
+ .setIssuedAt(iat)
+ .setExpirationTime(exp)
+ .setJti(crypto.randomUUID())
+ .sign(active.privateKey)
+}
diff --git a/services/oauth-proxy/src/lib/token-response.ts b/services/oauth-proxy/src/lib/token-response.ts
new file mode 100644
index 000000000000..752346749e45
--- /dev/null
+++ b/services/oauth-proxy/src/lib/token-response.ts
@@ -0,0 +1,84 @@
+import { decodeJwt } from 'jose'
+
+import { type Region, regionForBaseUrl } from './constants'
+import { IdTokenReissueError, type SigningKeyEnv, reissueIdToken } from './idtoken'
+
+/** Replace the regional ID token in a token response with one this proxy issued. */
+export async function reissueIdTokenInResponse(
+ response: Response,
+ options: { issuer: string; audience: string | null; permittedUpstreamAudiences: string[]; env: SigningKeyEnv }
+): Promise<Response> {
+ if (!response.ok) {
+ return response
+ }
+
+ if (!options.env.OIDC_SIGNING_KEY) {
+ // Deploying this worker before the signing key exists must not break token exchanges.
+ console.error(JSON.stringify({ handler: 'token', id_token: 'passthrough_no_signing_key' }))
+ return response
+ }
+
+ const raw = await response.text()
+ let payload: Record<string, unknown>
+ try {
+ payload = JSON.parse(raw) as Record<string, unknown>
+ } catch {
+ return rebuildResponse(response, raw)
+ }
+
+ const idToken = payload.id_token
+ if (typeof idToken !== 'string') {
+ return rebuildResponse(response, raw)
+ }
+
+ const region = regionOfIssuer(idToken)
+ if (!region) {
+ return serverError('Could not determine which region issued the ID token')
+ }
+
+ try {
+ const reissued = await reissueIdToken(idToken, {
+ region,
+ issuer: options.issuer,
+ audience: options.audience,
+ permittedUpstreamAudiences: options.permittedUpstreamAudiences,
+ env: options.env,
+ })
+ return rebuildResponse(response, JSON.stringify({ ...payload, id_token: reissued }))
+ } catch (error) {
+ // Serving the regional token instead would quietly restore the issuer mismatch.
+ console.error(
+ JSON.stringify({
+ handler: 'token',
+ id_token: 'reissue_failed',
+ region,
+ error: error instanceof IdTokenReissueError ? error.message : (error as Error)?.constructor?.name,
+ })
+ )
+ return serverError('Unable to issue an ID token')
+ }
+}
+
+/** The unverified claim only selects a key set; the signature is still verified against it. */
+function regionOfIssuer(idToken: string): Region | null {
+ try {
+ return regionForBaseUrl(decodeJwt(idToken).iss ?? '')
+ } catch {
+ return null
+ }
+}
+
+function rebuildResponse(response: Response, body: string): Response {
+ const headers = new Headers(response.headers)
+ // The body was re-serialized, so any upstream length no longer describes it.
+ headers.delete('content-length')
+
+ return new Response(body, { status: response.status, statusText: response.statusText, headers })
+}
+
+function serverError(description: string): Response {
+ return new Response(JSON.stringify({ error: 'server_error', error_description: description }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
+ })
+}
diff --git a/services/oauth-proxy/src/lib/validation.ts b/services/oauth-proxy/src/lib/validation.ts
index 139d808f062c..a9c0a103d06b 100644
--- a/services/oauth-proxy/src/lib/validation.ts
+++ b/services/oauth-proxy/src/lib/validation.ts
@@ -38,20 +38,29 @@ export function runValidators(validators: Validator[], request: Request, url: UR
}
/**
- * Rejects a request that repeats any of the named query params.
- *
- * OAuth request parameters MUST NOT be included more than once (RFC 6749 §3.1).
+ * OAuth request parameters MUST NOT be included more than once (RFC 6749 §3.1). A handler that
+ * parses a form body checks that itself, because a `Validator` cannot read the body.
*/
+export function findDuplicateParam(params: URLSearchParams, names: readonly string[]): string | null {
+ for (const name of names) {
+ if (params.getAll(name).length > 1) {
+ return name
+ }
+ }
+ return null
+}
+
+export function duplicateParamError(param: string): ValidationError {
+ return {
+ error: 'invalid_request',
+ error_description: `Duplicate ${param} parameter is not allowed`,
+ }
+}
+
+/** Rejects a request that repeats any of the named query params. */
export function noDuplicateParams(...params: string[]): Validator {
return (_request, url) => {
- for (const param of params) {
- if (url.searchParams.getAll(param).length > 1) {
- return {
- error: 'invalid_request',
- error_description: `Duplicate ${param} parameter is not allowed`,
- }
- }
- }
- return null
+ const duplicate = findDuplicateParam(url.searchParams, params)
+ return duplicate ? duplicateParamError(duplicate) : null
}
}
diff --git a/services/oauth-proxy/tests/idtoken.test.ts b/services/oauth-proxy/tests/idtoken.test.ts
new file mode 100644
index 000000000000..739db3e40068
--- /dev/null
+++ b/services/oauth-proxy/tests/idtoken.test.ts
@@ -0,0 +1,270 @@
+import { SignJWT, type JWK, decodeJwt, exportJWK, exportPKCS8, generateKeyPair, importJWK, jwtVerify } from 'jose'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { handleJwks } from '@/handlers/passthrough'
+import { IdTokenReissueError, reissueIdToken } from '@/lib/idtoken'
+
+import { createMockKV } from './helpers'
+
+// Relative to now, so the fixture keeps describing a live token however long this test lives.
+const ISSUED_AT = Math.floor(Date.now() / 1000)
+const EXPIRES_AT = ISSUED_AT + 3600
+
+const REGIONAL_CLIENT_ID = 'us_regional_client_id'
+
+interface RegionalKey {
+ privateKey: CryptoKey
+ publicJwk: JWK
+}
+
+async function createRegionalKey(): Promise<RegionalKey> {
+ const { privateKey, publicKey } = await generateKeyPair('RS256', { extractable: true })
+ return { privateKey, publicJwk: await exportJWK(publicKey) }
+}
+
+async function createProxyKeyPem(): Promise<string> {
+ const { privateKey } = await generateKeyPair('RS256', { extractable: true })
+ return exportPKCS8(privateKey)
+}
+
+async function signRegionalIdToken(
+ key: RegionalKey,
+ claims: Record<string, unknown> = {},
+ issuer = 'https://us.posthog.com'
+): Promise<string> {
+ return new SignJWT({
+ email: '[email protected]',
+ email_verified: true,
+ nonce: 'nonce-from-the-client',
+ at_hash: 'at-hash-of-the-access-token',
+ ...claims,
+ })
+ .setProtectedHeader({ alg: 'RS256' })
+ .setIssuer(issuer)
+ .setSubject('018f0000-0000-7000-8000-000000000000')
+ .setAudience(REGIONAL_CLIENT_ID)
+ .setIssuedAt(ISSUED_AT)
+ .setExpirationTime(EXPIRES_AT)
+ .sign(key.privateKey)
+}
+
+function stubRegionalJwks(key: RegionalKey): void {
+ // A fresh Response per call: the JWKS handler reads both regions, and a body can be read once.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() =>
+ Promise.resolve(
+ new Response(JSON.stringify({ keys: [key.publicJwk] }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ )
+ )
+ )
+}
+
+describe('ID token re-issuance', () => {
+ let regionalKey: RegionalKey
+ let signingKey: string
+
+ // One key set per file: `reissueIdToken` caches the remote JWKS per region, as a worker
+ // isolate does, so a fresh key per test would be rejected by the cached set.
+ beforeAll(async () => {
+ regionalKey = await createRegionalKey()
+ signingKey = await createProxyKeyPem()
+ })
+
+ beforeEach(() => {
+ stubRegionalJwks(regionalKey)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('replaces the regional issuer and audience while preserving the identity claims', async () => {
+ const idToken = await signRegionalIdToken(regionalKey)
+
+ const reissued = await reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: 'proxy_client_id',
+ permittedUpstreamAudiences: [REGIONAL_CLIENT_ID],
+ env: { OIDC_SIGNING_KEY: signingKey },
+ })
+
+ const claims = decodeJwt(reissued)
+ expect(claims.iss).toBe('https://oauth.posthog.com')
+ expect(claims.aud).toBe('proxy_client_id')
+ expect(claims.sub).toBe('018f0000-0000-7000-8000-000000000000')
+ expect(claims.email).toBe('[email protected]')
+ expect(claims.email_verified).toBe(true)
+ expect(claims.nonce).toBe('nonce-from-the-client')
+ expect(claims.at_hash).toBe('at-hash-of-the-access-token')
+ })
+
+ it('copies the lifetime of the regional token rather than extending it', async () => {
+ const idToken = await signRegionalIdToken(regionalKey)
+
+ const reissued = await reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: 'proxy_client_id',
+ permittedUpstreamAudiences: [REGIONAL_CLIENT_ID],
+ env: { OIDC_SIGNING_KEY: signingKey },
+ })
+
+ const claims = decodeJwt(reissued)
+ expect(claims.iat).toBe(ISSUED_AT)
+ expect(claims.exp).toBe(EXPIRES_AT)
+ })
+
+ it('signs with a key published in the proxy JWKS', async () => {
+ const idToken = await signRegionalIdToken(regionalKey)
+ const reissued = await reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: 'proxy_client_id',
+ permittedUpstreamAudiences: [REGIONAL_CLIENT_ID],
+ env: { OIDC_SIGNING_KEY: signingKey },
+ })
+
+ const response = await handleJwks(
+ new Request('https://oauth.posthog.com/.well-known/jwks.json'),
+ createMockKV(),
+ {
+ OIDC_SIGNING_KEY: signingKey,
+ }
+ )
+ const { keys } = (await response.json()) as { keys: JWK[] }
+ const header = JSON.parse(atob(reissued.split('.')[0]!)) as { kid: string }
+ const signingJwk = keys.find((key) => key.kid === header.kid)
+
+ expect(signingJwk).not.toBeUndefined()
+ await expect(jwtVerify(reissued, await importJWK(signingJwk!, 'RS256'))).resolves.toBeDefined()
+ })
+
+ it('keeps publishing the regional keys, which sign ID-JAG access tokens', async () => {
+ const response = await handleJwks(
+ new Request('https://oauth.posthog.com/.well-known/jwks.json'),
+ createMockKV(),
+ {
+ OIDC_SIGNING_KEY: signingKey,
+ }
+ )
+
+ const { keys } = (await response.json()) as { keys: JWK[] }
+ expect(keys.some((key) => key.n === regionalKey.publicJwk.n)).toBe(true)
+ })
+
+ it('refuses to sign without a configured key', async () => {
+ const idToken = await signRegionalIdToken(regionalKey)
+
+ await expect(
+ reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: 'proxy_client_id',
+ permittedUpstreamAudiences: [REGIONAL_CLIENT_ID],
+ env: {},
+ })
+ ).rejects.toBeInstanceOf(IdTokenReissueError)
+ })
+
+ it('refuses to sign a token the region did not sign', async () => {
+ const impostorKey = await createRegionalKey()
+ const idToken = await signRegionalIdToken(impostorKey)
+
+ await expect(
+ reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: 'proxy_client_id',
+ permittedUpstreamAudiences: [REGIONAL_CLIENT_ID],
+ env: { OIDC_SIGNING_KEY: signingKey },
+ })
+ ).rejects.toBeInstanceOf(IdTokenReissueError)
+ })
+
+ it('refuses to address a token to a client the region did not issue it to', async () => {
+ // Signing the posted client_id over another client's grant forges an identity for it.
+ const idToken = await signRegionalIdToken(regionalKey)
+
+ await expect(
+ reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: 'victim_client_id',
+ permittedUpstreamAudiences: ['victim_client_id'],
+ env: { OIDC_SIGNING_KEY: signingKey },
+ })
+ ).rejects.toBeInstanceOf(IdTokenReissueError)
+ })
+
+ it('keeps the regional audience when the request named no client', async () => {
+ // A request can authenticate without naming a client in the body, through a client
+ // assertion or the Authorization header, leaving the regional audience as the only one.
+ const idToken = await signRegionalIdToken(regionalKey)
+
+ const reissued = await reissueIdToken(idToken, {
+ region: 'us',
+ issuer: 'https://oauth.posthog.com',
+ audience: null,
+ permittedUpstreamAudiences: [],
+ env: { OIDC_SIGNING_KEY: signingKey },
+ })
+
+ expect(decodeJwt(reissued).aud).toBe(REGIONAL_CLIENT_ID)
+ })
+
+ it('still publishes the proxy keys when neither region answers', async () => {
+ // A relying party verifying an ID token this worker issued needs no regional key, so an
+ // outage of both regions must not take proxy-issued tokens down with it.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => Promise.resolve(new Response('nope', { status: 500 })))
+ )
+
+ vi.resetModules()
+ const { handleJwks: freshHandleJwks } = await import('@/handlers/passthrough')
+
+ const response = await freshHandleJwks(
+ new Request('https://oauth.posthog.com/.well-known/jwks.json'),
+ createMockKV(),
+ { OIDC_SIGNING_KEY: signingKey }
+ )
+ const { keys } = (await response.json()) as { keys: JWK[] }
+
+ expect(response.status).toBe(200)
+ expect(response.headers.get('cache-control')).toBe('no-store')
+ expect(keys).toHaveLength(1)
+ })
+
+ it('does not cache a JWKS document that is missing a region', async () => {
+ // Caching a partial document leaves tokens from the failed region unverifiable for the
+ // whole TTL, long after it recovers.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((url: string) =>
+ Promise.resolve(
+ url.includes('eu.posthog.com')
+ ? new Response('nope', { status: 500 })
+ : new Response(JSON.stringify({ keys: [regionalKey.publicJwk] }), { status: 200 })
+ )
+ )
+ )
+
+ // A fresh module instance, because the JWKS cache is module state an earlier test fills.
+ vi.resetModules()
+ const { handleJwks: freshHandleJwks } = await import('@/handlers/passthrough')
+
+ const response = await freshHandleJwks(
+ new Request('https://oauth.posthog.com/.well-known/jwks.json'),
+ createMockKV(),
+ { OIDC_SIGNING_KEY: signingKey }
+ )
+
+ expect(response.status).toBe(200)
+ expect(response.headers.get('cache-control')).toBe('no-store')
+ })
+})
diff --git a/services/oauth-proxy/tests/metadata.test.ts b/services/oauth-proxy/tests/metadata.test.ts
index 43fee4d76c3b..b6a07d6be0c3 100644
--- a/services/oauth-proxy/tests/metadata.test.ts
+++ b/services/oauth-proxy/tests/metadata.test.ts
@@ -18,6 +18,26 @@ const AUTHORITATIVE_METADATA = {
code_challenge_methods_supported: ['S256'],
service_documentation: 'https://posthog.com/docs/model-context-protocol',
client_id_metadata_document_supported: true,
+ agent_auth: {
+ skill: 'https://us.posthog.com/auth.md',
+ identity_endpoint: 'https://us.posthog.com/oauth/token/',
+ identity_types_supported: ['identity_assertion'],
+ },
+ posthog_region: 'us',
+ posthog_base_url: 'https://us.posthog.com',
+}
+
+const AUTHORITATIVE_OPENID_CONFIGURATION = {
+ issuer: 'https://us.posthog.com',
+ authorization_endpoint: 'https://us.posthog.com/oauth/authorize/',
+ token_endpoint: 'https://us.posthog.com/oauth/token/',
+ userinfo_endpoint: 'https://us.posthog.com/oauth/userinfo/',
+ jwks_uri: 'https://us.posthog.com/.well-known/jwks.json',
+ registration_endpoint: 'https://us.posthog.com/oauth/register/',
+ scopes_supported: ['openid', 'profile', 'email'],
+ claims_supported: ['email', 'email_verified', 'family_name', 'given_name', 'sub'],
+ subject_types_supported: ['public'],
+ id_token_signing_alg_values_supported: ['RS256'],
}
describe('handleMetadata', () => {
@@ -70,6 +90,28 @@ describe('handleMetadata', () => {
expect(data.client_id_metadata_document_supported).toBe(true)
})
+ it('rewrites the agent_auth endpoints onto the proxy', async () => {
+ // Left pointing at US, an EU user's ID-JAG assertion goes to the wrong region.
+ const { handleMetadata } = await import('@/handlers/metadata')
+ const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
+
+ const response = await handleMetadata(request)
+ const data = (await response.json()) as { agent_auth: Record<string, unknown> }
+
+ expect(data.agent_auth.skill).toBe('https://oauth.posthog.com/auth.md')
+ expect(data.agent_auth.identity_endpoint).toBe('https://oauth.posthog.com/oauth/token/')
+ })
+
+ it('keeps posthog_base_url pointing at the region that issues the tokens', async () => {
+ const { handleMetadata } = await import('@/handlers/metadata')
+ const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
+
+ const response = await handleMetadata(request)
+ const data = (await response.json()) as Record<string, unknown>
+
+ expect(data.posthog_base_url).toBe('https://us.posthog.com')
+ })
+
it('caches the authoritative metadata', async () => {
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
@@ -144,3 +186,76 @@ describe('handleMetadata', () => {
vi.useRealTimers()
})
})
+
+describe('handleOpenIdConfiguration', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(AUTHORITATIVE_OPENID_CONFIGURATION),
+ })
+ )
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('serves the OIDC discovery document a relying party needs to sign users in', async () => {
+ // Without it the proxy is not a discoverable OpenID provider.
+ const { handleOpenIdConfiguration } = await import('@/handlers/metadata')
+ const request = new Request('https://oauth.posthog.com/.well-known/openid-configuration')
+
+ const response = await handleOpenIdConfiguration(request)
+ const data = (await response.json()) as Record<string, unknown>
+
+ expect(response.status).toBe(200)
+ expect(data.issuer).toBe('https://oauth.posthog.com')
+ expect(data.userinfo_endpoint).toBe('https://oauth.posthog.com/oauth/userinfo/')
+ expect(data.jwks_uri).toBe('https://oauth.posthog.com/.well-known/jwks.json')
+ expect(data.claims_supported).toEqual(AUTHORITATIVE_OPENID_CONFIGURATION.claims_supported)
+ })
+
+ it('is readable cross-origin', async () => {
+ const { handleOpenIdConfiguration } = await import('@/handlers/metadata')
+ const request = new Request('https://oauth.posthog.com/.well-known/openid-configuration')
+
+ const response = await handleOpenIdConfiguration(request)
+
+ expect(response.headers.get('access-control-allow-origin')).toBe('*')
+ })
+})
+
+describe('handleClientManifest', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response('Authorize at https://us.posthog.com/oauth/authorize/ with scope `openid`.', {
+ status: 200,
+ })
+ )
+ )
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('serves the manifest the metadata advertises, with its URLs on the proxy', async () => {
+ // `agent_auth.skill` points agents at this path on the proxy, which had no route for it.
+ const { handleClientManifest } = await import('@/handlers/metadata')
+ const request = new Request('https://oauth.posthog.com/auth.md')
+
+ const response = await handleClientManifest(request)
+
+ expect(response.status).toBe(200)
+ expect(response.headers.get('content-type')).toContain('text/markdown')
+ expect(await response.text()).toBe(
+ 'Authorize at https://oauth.posthog.com/oauth/authorize/ with scope `openid`.'
+ )
+ })
+})
diff --git a/services/oauth-proxy/tests/token.test.ts b/services/oauth-proxy/tests/token.test.ts
index 5cf38d77fe91..0e4f03880fe6 100644
--- a/services/oauth-proxy/tests/token.test.ts
+++ b/services/oauth-proxy/tests/token.test.ts
@@ -1,3 +1,4 @@
+import { SignJWT, decodeJwt, exportJWK, exportPKCS8, generateKeyPair } from 'jose'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { handleToken } from '@/handlers/token'
@@ -47,7 +48,7 @@ describe('handleToken', () => {
body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_123',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
@@ -92,7 +93,7 @@ describe('handleToken', () => {
body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_456&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
expect(response.status).toBe(200)
const fetchCall = vi.mocked(fetch).mock.calls[0]!
@@ -142,7 +143,7 @@ describe('handleToken', () => {
body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_789&client_secret=us_secret_abc&redirect_uri=https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
expect(response.status).toBe(200)
const fetchCall = vi.mocked(fetch).mock.calls[0]!
@@ -161,7 +162,7 @@ describe('handleToken', () => {
body: 'grant_type=authorization_code&code=test_code&client_id=unknown_client',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(400)
@@ -175,13 +176,31 @@ describe('handleToken', () => {
body: '{invalid json',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
expect(response.status).toBe(400)
const data = (await response.json()) as Record<string, unknown>
expect(data.error).toBe('invalid_request')
expect(data.error_description).toBe('Malformed JSON body')
})
+ it('rejects a token request that repeats a parameter the regional server reads differently', async () => {
+ vi.stubGlobal('fetch', vi.fn())
+
+ const request = new Request('https://oauth.posthog.com/oauth/token/', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: 'grant_type=authorization_code&code=test_code&client_id=victim_client&client_id=attacker_client',
+ })
+
+ const response = await handleToken(request, mockKV, {})
+ const data = (await response.json()) as Record<string, unknown>
+
+ expect(response.status).toBe(400)
+ expect(data.error).toBe('invalid_request')
+ expect(data.error_description).toBe('Duplicate client_id parameter is not allowed')
+ expect(vi.mocked(fetch)).not.toHaveBeenCalled()
+ })
+
it('falls back to try-both for refresh_token grants without mapping', async () => {
mockKVGetValue(mockKV, null)
@@ -212,7 +231,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_test&client_id=unknown_client',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(data.access_token).toBe('pha_eu_refreshed')
@@ -268,7 +287,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_eu_token&client_id=proxy_client_mapped&client_secret=us_secret',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
@@ -324,7 +343,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_us_token&client_id=proxy_client_us',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
@@ -393,7 +412,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_expired&client_id=proxy_client_bad',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
expect(response.status).toBe(expectedStatus)
expect(await response.text()).toBe(expectedBody)
@@ -460,7 +479,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_dead&client_id=unknown_client',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
expect(response.status).toBe(expectedStatus)
expect(await response.text()).toBe(expectedBody)
@@ -490,7 +509,7 @@ describe('handleToken', () => {
body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_authcode',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
// Should return error, not attempt mapping-based routing
@@ -543,7 +562,7 @@ describe('handleToken', () => {
}),
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
@@ -587,7 +606,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_token&client_id=proxy_client_us_only',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
@@ -631,7 +650,7 @@ describe('handleToken', () => {
body: 'grant_type=refresh_token&refresh_token=rt_token&client_id=proxy_client_eu_only',
})
- const response = await handleToken(request, mockKV)
+ const response = await handleToken(request, mockKV, {})
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
@@ -644,4 +663,141 @@ describe('handleToken', () => {
expect(euBody.get('client_id')).toBe('eu_only_id')
expect(vi.mocked(mockKV.put)).toHaveBeenCalledWith(`region:${clientHash}`, 'eu', { expirationTtl: 3600 })
})
+
+ it('does not rewrite the client_id for an ID-JAG assertion exchange', async () => {
+ // Rewriting it to the regional id makes every EU exchange fail with invalid_grant.
+ const clientHash = await hashKey('proxy_client_id_jag')
+ mockKVGet(mockKV, (key: string, type?: unknown) => {
+ if (key === `region:${clientHash}`) {
+ return Promise.resolve('eu')
+ }
+ if (key === 'client:proxy_client_id_jag' && type === 'json') {
+ return Promise.resolve({
+ us_client_id: 'proxy_client_id_jag',
+ eu_client_id: 'eu_real_id',
+ created_at: Date.now(),
+ })
+ }
+ return Promise.resolve(null)
+ })
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ access_token: 'id_jag_access_token', token_type: 'bearer' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ )
+ )
+
+ const request = new Request('https://oauth.posthog.com/oauth/token/', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=an.id.jag&client_id=proxy_client_id_jag',
+ })
+
+ const response = await handleToken(request, mockKV, {})
+
+ expect(response.status).toBe(200)
+ for (const call of vi.mocked(fetch).mock.calls) {
+ const forwarded = new URLSearchParams(String((call[1] as RequestInit).body))
+ expect(forwarded.get('client_id')).toBe('proxy_client_id_jag')
+ }
+ })
+
+ it('serves the upstream id_token unchanged when no signing key is configured', async () => {
+ // The worker can be deployed before the secret exists.
+ const clientHash = await hashKey('proxy_client_oidc')
+ mockKVGet(mockKV, (key: string) => {
+ if (key === `region:${clientHash}`) {
+ return Promise.resolve('us')
+ }
+ return Promise.resolve(null)
+ })
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ access_token: 'pha_test_token', id_token: 'regional.id.token' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ )
+ )
+
+ const request = new Request('https://oauth.posthog.com/oauth/token/', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_oidc',
+ })
+
+ const response = await handleToken(request, mockKV, {})
+ const data = (await response.json()) as Record<string, unknown>
+
+ expect(response.status).toBe(200)
+ expect(data.id_token).toBe('regional.id.token')
+ })
+
+ it('addresses the re-issued id_token to the proxy client_id the region knows regionally', async () => {
+ // A client registered through the proxy holds an id neither region issues tokens to.
+ const clientHash = await hashKey('proxy_client_mapped')
+ mockKVGet(mockKV, (key: string, type?: unknown) => {
+ if (key === `region:${clientHash}`) {
+ return Promise.resolve('eu')
+ }
+ if (key === 'client:proxy_client_mapped' && type === 'json') {
+ return Promise.resolve({
+ us_client_id: 'proxy_client_mapped',
+ eu_client_id: 'eu_real_id',
+ created_at: Date.now(),
+ })
+ }
+ return Promise.resolve(null)
+ })
+
+ const regional = await generateKeyPair('RS256', { extractable: true })
+ const regionalJwk = await exportJWK(regional.publicKey)
+ const proxyKey = await generateKeyPair('RS256', { extractable: true })
+ const issuedAt = Math.floor(Date.now() / 1000)
+ const regionalIdToken = await new SignJWT({ email: '[email protected]' })
+ .setProtectedHeader({ alg: 'RS256' })
+ .setIssuer('https://eu.posthog.com')
+ .setSubject('018f0000-0000-7000-8000-000000000000')
+ .setAudience('eu_real_id')
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(issuedAt + 3600)
+ .sign(regional.privateKey)
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((url: string) =>
+ Promise.resolve(
+ String(url).includes('/.well-known/jwks.json')
+ ? new Response(JSON.stringify({ keys: [regionalJwk] }), { status: 200 })
+ : new Response(JSON.stringify({ access_token: 'pha_token', id_token: regionalIdToken }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ )
+ )
+ )
+
+ const request = new Request('https://oauth.posthog.com/oauth/token/', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_mapped',
+ })
+
+ const response = await handleToken(request, mockKV, {
+ OIDC_SIGNING_KEY: await exportPKCS8(proxyKey.privateKey),
+ })
+ const data = (await response.json()) as Record<string, unknown>
+
+ expect(response.status).toBe(200)
+ const claims = decodeJwt(data.id_token as string)
+ expect(claims.iss).toBe('https://oauth.posthog.com')
+ expect(claims.aud).toBe('proxy_client_mapped')
+ expect(claims.sub).toBe('018f0000-0000-7000-8000-000000000000')
+ })
})
diff --git a/services/oauth-proxy/wrangler.jsonc b/services/oauth-proxy/wrangler.jsonc
index fc61373319fd..85a325235499 100644
--- a/services/oauth-proxy/wrangler.jsonc
+++ b/services/oauth-proxy/wrangler.jsonc
@@ -1,32 +1,31 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
- "name": "auth-proxy",
+ "name": "oauth-proxy",
+ // Secrets are set with `wrangler secret put` and cannot be declared here. The worker reads
+ // OIDC_SIGNING_KEY, OIDC_SIGNING_KEY_INACTIVE_1 and OIDC_SIGNING_KEY_INACTIVE_2; see the
+ // README section on ID tokens and the `Env` interface in src/index.ts.
"main": "src/index.ts",
"compatibility_date": "2025-03-10",
- "compatibility_flags": [
- "nodejs_compat"
- ],
+ "compatibility_flags": ["nodejs_compat"],
"observability": {
"enabled": true,
"logs": {
"enabled": true,
"head_sampling_rate": 1.0,
- "persist": true
- }
+ "persist": true,
+ },
},
"rules": [
{
"type": "Text",
- "globs": [
- "src/static/**/*.html"
- ],
- "fallthrough": true
- }
+ "globs": ["src/static/**/*.html"],
+ "fallthrough": true,
+ },
],
"kv_namespaces": [
{
"binding": "AUTH_KV",
- "id": "3ac9a85816994f3ea94f98364de4732a"
- }
- ]
+ "id": "3ac9a85816994f3ea94f98364de4732a",
+ },
+ ],
}