: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): reject symmetric keys in a client's jwks (#110193)
Matt Brookerbde3392958d8
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.pyindex 0c64218b7bed..5e11220222d3 100644--- a/posthog/api/oauth/client_assertion.py+++ b/posthog/api/oauth/client_assertion.py@@ -21,6 +21,8 @@ from django.core.cache import cacheimport jwtimport structlog+from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKeyfrom jwt import PyJWK, PyJWKSetfrom posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError, fetch_client_json_document@@ -42,6 +44,7 @@ CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:# 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@@ -201,6 +204,8 @@ def _fetch_jwks_document(jwks_uri: str) -> dict:keys = parsed.get("keys")if isinstance(keys, list) and len(keys) > JWKS_MAX_KEYS:raise ClientAssertionError(f"JWKS must not contain more than {JWKS_MAX_KEYS} keys")+ if isinstance(keys, list) and any(isinstance(key, dict) and key.get("kty") == "oct" for key in keys):+ raise ClientAssertionError('JWKS contains a symmetric key (kty "oct"). Publish only RSA or EC public keys.')try:PyJWKSet.from_dict(parsed)@@ -278,13 +283,17 @@ 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(+ key.key, (RSAPublicKey, EllipticCurvePublicKey)+ ):+ raise ClientAssertionError("Client signing key must be an RSA or EC public key")client_identifier = app.client_idtry:claims = jwt.decode(assertion,key=key,- algorithms=ALLOWED_ASSERTION_ALGORITHMS,+ algorithms=[key.algorithm_name],audience=audiences if audiences is not None else expected_assertion_audiences(AGENTIC_TOKEN_ENDPOINT_PATH),issuer=client_identifier,leeway=ASSERTION_CLOCK_SKEW_SECONDS,diff --git a/posthog/api/oauth/test_client_assertion.py b/posthog/api/oauth/test_client_assertion.pyindex 21c9123e29b2..7dd3bd77d631 100644--- a/posthog/api/oauth/test_client_assertion.py+++ b/posthog/api/oauth/test_client_assertion.py@@ -1,5 +1,8 @@+import hmacimport jsonimport time+import hashlib+import secretsfrom typing import castfrom posthog.test.base import BaseTest@@ -9,7 +12,8 @@ from django.core.cache import cachefrom django.test import override_settingsimport jwt-from cryptography.hazmat.primitives.asymmetric import rsa+from cryptography.hazmat.primitives.asymmetric import ec, rsa+from jwt.utils import base64url_encodefrom parameterized import parameterizedfrom rest_framework.parsers import JSONParserfrom rest_framework.request import Request@@ -18,6 +22,7 @@ from rest_framework.test import APIRequestFactoryfrom posthog.api.oauth.cimd import CIMDFetchErrorfrom posthog.api.oauth.client_assertion import (CLIENT_ASSERTION_TYPE_JWT_BEARER,+ JWKS_CACHE_PREFIX,MAX_ASSERTION_LIFETIME_SECONDS,ClientAssertionError,ResolvedClientAssertion,@@ -31,6 +36,8 @@ CLIENT_ID = "https://partner.example.com/.well-known/oauth-client-metadata.json"JWKS_URI = "https://partner.example.com/.well-known/jwks.json"AUDIENCE = "https://us.posthog.com/api/agentic/oauth/token"KID = "partner-key-1"+HMAC_KID = "partner-hmac-key"+HMAC_SECRET = secrets.token_bytes(32)def _rsa_key():@@ -54,6 +61,18 @@ def _jwks_for(private_key, kid: str = KID) -> dict:return {"keys": [jwk]}+def _jwks_with_symmetric_key() -> dict:+ symmetric_jwk = {"kty": "oct", "kid": HMAC_KID, "k": base64url_encode(HMAC_SECRET).decode()}+ return {"keys": [*_jwks_for(KEY)["keys"], symmetric_jwk]}+++def _hmac_signed(claims: dict, header_alg: str) -> str:+ header = {"alg": header_alg, "kid": HMAC_KID, "typ": "JWT"}+ signing_input = b".".join(base64url_encode(json.dumps(part).encode()) for part in (header, claims))+ signature = hmac.new(HMAC_SECRET, signing_input, hashlib.sha256).digest()+ return f"{signing_input.decode()}.{base64url_encode(signature).decode()}"++@override_settings(SITE_URL="https://us.posthog.com")class TestClientAssertion(BaseTest):def setUp(self):@@ -135,6 +154,24 @@ class TestClientAssertion(BaseTest):with self.assertRaises(ClientAssertionError):self._verify(assertion)+ @parameterized.expand([("header_rs256", "RS256"), ("header_hs256", "HS256")])+ def test_symmetric_jwks_key_never_verifies(self, _name, header_alg):+ # Seeded straight into the cache so the check at verification runs without the loader's.+ cache.set(f"{JWKS_CACHE_PREFIX}{JWKS_URI}", _jwks_with_symmetric_key())+ with (+ patch("posthog.api.oauth.client_assertion.fetch_client_json_document", side_effect=AssertionError),+ self.assertRaisesMessage(ClientAssertionError, "must be an RSA or EC public key"),+ ):+ verify_client_assertion(self.app, _hmac_signed(self._claims(), header_alg))++ def test_private_jwks_key_never_verifies(self):+ private_key = ec.generate_private_key(ec.SECP256R1())+ jwk = json.loads(jwt.algorithms.ECAlgorithm.to_jwk(private_key))+ jwk.update({"kid": KID, "alg": "ES256"})+ self.jwks = {"keys": [jwk]}+ with self.assertRaisesMessage(ClientAssertionError, "must be an RSA or EC public key"):+ self._verify(self._assertion(key=private_key, algorithm="ES256"))+def test_unsigned_assertion_is_rejected(self):# nosemgrep: python.jwt.security.jwt-none-alg.jwt-python-none-alg (forging an alg=none token is the point: this asserts verify_client_assertion refuses it)assertion = jwt.encode(self._claims(), key="", algorithm="none")@@ -243,11 +280,20 @@ class TestClientAssertion(BaseTest):# A client with a broken jwks_uri must not turn each request into an outbound fetch.fetch.assert_called_once()- def test_jwks_with_too_many_keys_is_rejected(self):- # The cap is on key count, so the same key material under distinct kids exercises it.- many = {"keys": [_jwks_for(KEY, kid=f"k{i}")["keys"][0] for i in range(11)]}- with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(many, None)):- with self.assertRaises(ClientAssertionError):+ @parameterized.expand(+ [+ # The cap is on key count, so the same key material under distinct kids exercises it.+ (+ "too_many_keys",+ {"keys": [_jwks_for(KEY, kid=f"k{i}")["keys"][0] for i in range(11)]},+ "must not contain more than",+ ),+ ("symmetric_key", _jwks_with_symmetric_key(), "symmetric key"),+ ]+ )+ def test_unacceptable_jwks_is_rejected(self, _name, jwks, expected_message):+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(jwks, None)):+ with self.assertRaisesMessage(ClientAssertionError, expected_message):load_jwks(JWKS_URI)@parameterized.expand(