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): accept the proxy issuer as a client assertion audience (#119603)

Adam Bowker0e2c4e88ae50
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 8fa74fcc3671..8d3efacd1bd8 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -57,6 +57,7 @@ UNREADABLE_CLIENT_ASSERTION_MESSAGE = (
# is ever lost, and bounds how far ahead a client may pre-mint.
MAX_ASSERTION_LIFETIME_SECONDS = 300
ASSERTION_CLOCK_SKEW_SECONDS = 30
+MAX_LOGGED_AUDIENCE_LENGTH = 256
JWKS_CACHE_PREFIX = "oauth_client_jwks:"
JWKS_CACHE_TTL_SECONDS = 3600
@@ -121,18 +122,25 @@ def resolve_client_assertion(assertion: str, assertion_type: str, client_id: str
return ResolvedClientAssertion(client_assertion=assertion, client_id=resolved_client_id)
+def _unverified_claims(assertion: str) -> dict[str, object]:
+ """Read the claims without verifying them, only to locate a client or to log diagnostics.
+
+ Never trusted for authentication.
+ """
+ try:
+ # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode
+ return jwt.decode(assertion, options={"verify_signature": False})
+ except jwt.PyJWTError:
+ return {}
+
+
def _unverified_subject(assertion: str) -> str:
"""Read ``sub`` without verifying, only to locate which client to verify against.
Never trusted for authentication: the claim is re-checked against the resolved
application's client_id after the signature verifies.
"""
- try:
- # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode
- claims = jwt.decode(assertion, options={"verify_signature": False})
- except jwt.PyJWTError:
- return ""
- subject = claims.get("sub") or ""
+ subject = _unverified_claims(assertion).get("sub") or ""
return subject if isinstance(subject, str) else ""
@@ -142,9 +150,17 @@ def expected_assertion_audiences(*token_endpoint_paths: str) -> list[str]:
RFC 7523 section 3 lets a client address either the issuer or the endpoint it is calling,
so both are accepted. Callers pass the paths their own endpoint answers on.
+
+ A client that discovered the OAuth proxy addresses the proxy's issuer, and the proxy
+ forwards the assertion unchanged, so the issuers in ID_JAG_ALLOWED_AUDIENCES count too.
"""
- site_url = settings.SITE_URL.rstrip("/")
- return [site_url, *(f"{site_url}{path}" for path in token_endpoint_paths)]
+ issuers = [
+ settings.SITE_URL.rstrip("/"),
+ *(issuer.rstrip("/") for issuer in settings.ID_JAG_ALLOWED_AUDIENCES if issuer),
+ ]
+ return [
+ audience for issuer in issuers for audience in (issuer, *(f"{issuer}{path}" for path in token_endpoint_paths))
+ ]
AGENTIC_TOKEN_ENDPOINT_PATH = "/api/agentic/oauth/token"
@@ -309,7 +325,13 @@ def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences:
except jwt.PyJWTError as e:
# The reason is logged rather than returned: which check failed is useful to us and
# not something an unauthenticated caller needs.
- logger.warning("client_assertion_rejected", app_id=str(app.id), error=str(e), error_type=type(e).__name__)
+ logger.warning(
+ "client_assertion_rejected",
+ app_id=str(app.id),
+ error=str(e),
+ error_type=type(e).__name__,
+ unverified_audience=str(_unverified_claims(assertion).get("aud"))[:MAX_LOGGED_AUDIENCE_LENGTH],
+ )
raise ClientAssertionError("Client assertion is invalid") from e
# RFC 7523 section 3: for client authentication both iss and sub are the client_id.
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index f561fcd2926a..ef6e4ea2f0cb 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -882,13 +882,18 @@ class TestOAuthAPI(APIBaseTest):
)
return app, grant, private_key
- def _signed_assertion_and_jwks(self, app: OAuthApplication, private_key: rsa.RSAPrivateKey) -> tuple[str, dict]:
+ def _signed_assertion_and_jwks(
+ self,
+ app: OAuthApplication,
+ private_key: rsa.RSAPrivateKey,
+ audience: str = "https://us.posthog.com/oauth/token/",
+ ) -> tuple[str, dict]:
now = int(timezone.now().timestamp())
assertion = jwt.encode(
{
"iss": app.client_id,
"sub": app.client_id,
- "aud": "https://us.posthog.com/oauth/token/",
+ "aud": audience,
"jti": "pkjwt-assertion-1",
"iat": now,
"exp": now + 60,
@@ -915,13 +920,22 @@ class TestOAuthAPI(APIBaseTest):
},
)
+ @parameterized.expand(
+ [
+ ("regional_token_endpoint", "https://us.posthog.com/oauth/token/"),
+ # Clients that discover the OAuth proxy address its issuer or token endpoint, and
+ # the proxy forwards the assertion to the region unchanged.
+ ("proxy_issuer", "https://oauth.posthog.com"),
+ ("proxy_token_endpoint", "https://oauth.posthog.com/oauth/token/"),
+ ]
+ )
@time_machine.travel("2025-01-01 00:00:00", tick=False)
- @override_settings(SITE_URL="https://us.posthog.com")
- def test_private_key_jwt_cimd_client_completes_token_exchange(self):
+ @override_settings(SITE_URL="https://us.posthog.com", ID_JAG_ALLOWED_AUDIENCES=["https://oauth.posthog.com"])
+ def test_private_key_jwt_cimd_client_completes_token_exchange(self, _name, audience):
# A private_key_jwt CIMD client is confidential but holds no secret, so the secret
# paths can never authenticate it and only the assertion path can finish an install.
app, grant, private_key = self._create_private_key_jwt_app_and_grant()
- assertion, jwks = self._signed_assertion_and_jwks(app, private_key)
+ assertion, jwks = self._signed_assertion_and_jwks(app, private_key, audience=audience)
with (
patch(
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 21582d4d654f..27cf2dec104c 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1294,6 +1294,7 @@ ID_JAG_JWKS_CACHE_TTL_SECONDS: int = get_from_env("ID_JAG_JWKS_CACHE_TTL_SECONDS
# 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.
+# private_key_jwt client assertions accept these issuers and their token endpoints too.
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.