:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(oauth): require jti and cap lifetime on id-jag assertions (#113012)
Rafael Audibert8b03a48572f1
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.pyindex 71614228687d..c9cc60e2b3bf 100644--- a/posthog/api/id_jag.py+++ b/posthog/api/id_jag.py@@ -24,6 +24,7 @@ from rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.dataclasses import frozenfrom posthog.helpers.email_utils import EmailLookupHandler+from posthog.jwt import ASYMMETRIC_SIGNING_ALGORITHMSfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.user import Userfrom posthog.scopes import get_oauth_scopes_supported@@ -322,11 +323,11 @@ def _verify_and_extract_id_jag_token(assertion: str) -> _VerifiedIdJag:jwt.decode(assertion,signing_key.key,- algorithms=["RS256", "RS384", "RS512"],+ algorithms=ASYMMETRIC_SIGNING_ALGORITHMS,audience=allowed_audiences,leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,options={- "require": ["iss", "sub", "aud", "exp", "iat", "client_id"],+ "require": ["iss", "sub", "aud", "exp", "iat", "client_id", "jti"],"verify_signature": True,"verify_exp": True,"verify_nbf": True,@@ -382,19 +383,24 @@ def _verify_and_extract_id_jag_token(assertion: str) -> _VerifiedIdJag:if idp_config.id_jag_allowed_clients and client_id not in idp_config.id_jag_allowed_clients:raise InvalidClientError(f"client_id {client_id!r} is not allowed for this domain")+ expires_at = claims.get("exp")+ issued_at = claims.get("iat")+ # PyJWT validates timestamps after int() coercion but returns the original claim values,+ # so a numeric-string exp or iat would make the arithmetic below raise a TypeError.+ if not isinstance(expires_at, (int, float)) or not isinstance(issued_at, (int, float)):+ raise InvalidGrantError("ID-JAG exp and iat must be numeric")+ # The cap bounds how long a captured ID-JAG stays usable, and how long its jti stays in the cache.+ if expires_at - issued_at > settings.ID_JAG_MAX_ASSERTION_LIFETIME_SECONDS:+ raise InvalidGrantError(f"ID-JAG lifetime exceeds {settings.ID_JAG_MAX_ASSERTION_LIFETIME_SECONDS} seconds")+# prevent replayed tokens from being used again- jti = claims.get("jti")- if jti:- cache_key = f"id_jag:jti:{expected_issuer}:{jti}"- exp = int(claims.get("exp") or 0)- now = int(datetime.now(tz=UTC).timestamp())- ttl = max(1, exp - now + settings.ID_JAG_CLOCK_SKEW_SECONDS)- # `cache.add` is SETNX semantics: returns True only if the key was- # newly created. A False return means we've already seen this jti.- if not cache.add(cache_key, "1", ttl):- raise InvalidGrantError("ID-JAG assertion has already been used (jti replay)")- else:- logger.info("id_jag_assertion_missing_jti", issuer=expected_issuer)+ cache_key = f"id_jag:jti:{expected_issuer}:{claims['jti']}"+ now = int(datetime.now(tz=UTC).timestamp())+ ttl = max(1, int(expires_at) - now + settings.ID_JAG_CLOCK_SKEW_SECONDS)+ # `cache.add` is SETNX semantics: returns True only if the key was+ # newly created. A False return means we've already seen this jti.+ if not cache.add(cache_key, "1", ttl):+ raise InvalidGrantError("ID-JAG assertion has already been used (jti replay)")# Some IdPs let a user set an arbitrary `email` with `email_verified: false`if claims.get("email") is not None and claims.get("email_verified") is False:diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.pyindex 5e11220222d3..d3b3345f175f 100644--- a/posthog/api/oauth/client_assertion.py+++ b/posthog/api/oauth/client_assertion.py@@ -27,6 +27,7 @@ from jwt import PyJWK, PyJWKSetfrom posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError, fetch_client_json_documentfrom posthog.dataclasses import frozen+from posthog.jwt import ASYMMETRIC_SIGNING_ALGORITHMSfrom posthog.models.oauth import OAuthApplicationlogger = structlog.get_logger(__name__)@@ -41,11 +42,6 @@ class ResolvedClientAssertion:CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"-# Asymmetric signatures only. Allowing an HMAC family here would be a key-confusion hole:-# the "public" key we fetch is attacker-publishable, so an HS256 assertion signed with that-# same value as the shared secret would verify. "none" is excluded for the same reason.-# The selected key's own algorithm is held to this list too, because PyJWT verifies with it.-ALLOWED_ASSERTION_ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"]# An assertion is a single-use credential presented immediately, so it needs no real# lifetime. Capping it bounds how long a captured assertion is replayable if the jti cache@@ -283,7 +279,8 @@ def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences:raise ClientAssertionError("This client is not registered for private_key_jwt authentication")key = _select_key_allowing_rotation(app.jwks_uri, assertion)- if key.algorithm_name not in ALLOWED_ASSERTION_ALGORITHMS or not isinstance(+ # The selected key's own algorithm is held to the list too, because PyJWT verifies with it.+ if key.algorithm_name not in ASYMMETRIC_SIGNING_ALGORITHMS or not isinstance(key.key, (RSAPublicKey, EllipticCurvePublicKey)):raise ClientAssertionError("Client signing key must be an RSA or EC public key")diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex ff0d8ab56b38..72d9e3a45eea 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -22,6 +22,7 @@ from django.utils import timezoneimport jwtfrom cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom oauth2_provider.utils import jwk_from_pemfrom parameterized import parameterizedfrom rest_framework import status@@ -47,6 +48,11 @@ from posthog.settings.utils import generate_rsa_private_key_pem# rsa operations are expensive, keep this at the module-level to avoid slow tests_IDP_PRIVATE_KEY_PEM = generate_rsa_private_key_pem()+_IDP_EC_PRIVATE_KEY_PEM = (+ ec.generate_private_key(ec.SECP256R1())+ .private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())+ .decode()+)_AS_PRIVATE_KEY_PEM = generate_rsa_private_key_pem()_IDP_ISSUER = "https://idp.example.com"@@ -76,7 +82,9 @@ def _make_id_jag(exp_seconds: int = 300,typ_header: str = ID_JAG_TOKEN_TYPE,extra_claims: dict[str, Any] | None = None,+ omit_claims: tuple[str, ...] = (),signing_pem: str | None = None,+ algorithm: str = "RS256",) -> str:"""Forge a synthetic IdP-issued ID-JAG for the test suite."""@@ -95,11 +103,13 @@ def _make_id_jag(}if extra_claims:payload.update(extra_claims)+ for claim in omit_claims:+ payload.pop(claim)return jwt.encode(payload,signing_pem or _IDP_PRIVATE_KEY_PEM,- algorithm="RS256",- headers={"typ": typ_header, "alg": "RS256"},+ algorithm=algorithm,+ headers={"typ": typ_header, "alg": algorithm},)@@ -138,10 +148,10 @@ class TestIdJagTokenEndpoint(APIBaseTest):# Stub the JWKS fetch so PyJWKClient resolves to our test public key# without hitting the network. `get_signing_key_from_jwt` is the only# surface area we use.- signing_key = MagicMock()- signing_key.key = _public_key_for(_IDP_PRIVATE_KEY_PEM)+ self.idp_signing_key = MagicMock()+ self.idp_signing_key.key = _public_key_for(_IDP_PRIVATE_KEY_PEM)mock_jwks_client = MagicMock()- mock_jwks_client.get_signing_key_from_jwt.return_value = signing_key+ mock_jwks_client.get_signing_key_from_jwt.return_value = self.idp_signing_keyself._jwks_patch = patch("posthog.api.id_jag._get_jwks_client", return_value=mock_jwks_client)self._jwks_patch.start()@@ -150,8 +160,16 @@ class TestIdJagTokenEndpoint(APIBaseTest):def _post_token(self, body: dict[str, Any]) -> Any:return self.client.post("/oauth/token", data=body, content_type="application/json")- def test_issues_access_token_for_valid_id_jag(self) -> None:- assertion = _make_id_jag()+ @parameterized.expand(+ [+ ("RS256", _IDP_PRIVATE_KEY_PEM),+ ("PS256", _IDP_PRIVATE_KEY_PEM),+ ("ES256", _IDP_EC_PRIVATE_KEY_PEM),+ ]+ )+ def test_issues_access_token_for_valid_id_jag(self, idp_algorithm: str, idp_signing_pem: str) -> None:+ self.idp_signing_key.key = _public_key_for(idp_signing_pem)+ assertion = _make_id_jag(signing_pem=idp_signing_pem, algorithm=idp_algorithm)resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})self.assertEqual(resp.status_code, status.HTTP_200_OK)@@ -540,25 +558,28 @@ class TestIdJagTokenEndpoint(APIBaseTest):self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(resp.json()["error"], "invalid_grant")- def test_rejects_missing_required_claims(self) -> None:- assertion = jwt.encode(- {- "iss": _IDP_ISSUER,- "sub": "[email protected]",- "aud": _AUTH_SERVER_URL,- # client_id intentionally missing- "resource": _RESOURCE_URL,- "scope": "feature_flag:read",- "iat": int(time.time()),- "exp": int(time.time()) + 300,- },- _IDP_PRIVATE_KEY_PEM,- algorithm="RS256",- headers={"typ": ID_JAG_TOKEN_TYPE},- )+ @parameterized.expand([("client_id",), ("jti",)])+ def test_rejects_missing_required_claims(self, missing_claim: str) -> None:+ assertion = _make_id_jag(omit_claims=(missing_claim,))resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(resp.json()["error"], "invalid_grant")+ self.assertIn(missing_claim, resp.json()["error_description"])++ @parameterized.expand(+ [+ ("at_cap", {}, 600, status.HTTP_200_OK),+ ("over_cap", {}, 601, status.HTTP_400_BAD_REQUEST),+ ("numeric_string_exp", {"exp": str(int(time.time()) + 300)}, 300, status.HTTP_400_BAD_REQUEST),+ ]+ )+ @override_settings(ID_JAG_MAX_ASSERTION_LIFETIME_SECONDS=600)+ def test_assertion_lifetime_is_capped(+ self, _name: str, extra_claims: dict[str, Any], exp_seconds: int, expected_status: int+ ) -> None:+ assertion = _make_id_jag(exp_seconds=exp_seconds, extra_claims=extra_claims)+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})+ self.assertEqual(resp.status_code, expected_status, resp.json())def test_rejects_request_client_id_mismatch(self) -> None:assertion = _make_id_jag(client_id="client_abc-at-posthog")diff --git a/posthog/jwt.py b/posthog/jwt.pyindex 17028b8528ea..2e8ad5e5716e 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -8,6 +8,11 @@ from django.conf import settingsimport jwtfrom cryptography.hazmat.primitives import serialization+# For JWTs a third party signs with keys it publishes. Asymmetric signatures only: an HMAC+# family would let anyone holding the published key sign with it as a shared secret, and+# "none" carries no signature at all.+ASYMMETRIC_SIGNING_ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"]+JWT_ALGORITHM = "HS256"diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 5405bd6ad16a..4262a9437faa 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1265,6 +1265,10 @@ OAUTH2_PROVIDER_GRANT_MODEL = "posthog.OAuthGrant"ID_JAG_ACCESS_TOKEN_TTL_SECONDS: int = get_from_env("ID_JAG_ACCESS_TOKEN_TTL_SECONDS", 60 * 60 * 2, type_cast=int)ID_JAG_CLOCK_SKEW_SECONDS: int = get_from_env("ID_JAG_CLOCK_SKEW_SECONDS", 30, type_cast=int)+# IdPs issue ID-JAGs for immediate use (5 minutes is typical); the cap leaves headroom above that.+ID_JAG_MAX_ASSERTION_LIFETIME_SECONDS: int = get_from_env(+ "ID_JAG_MAX_ASSERTION_LIFETIME_SECONDS", 60 * 10, 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 —