: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
feat(oauth): support inactive OIDC signing keys for seamless key rotation (#60895)
Felipe Rosa de Almeida0081661f3b5a
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.pyindex 06ba921bfa07..192250a21917 100644--- a/posthog/api/id_jag.py+++ b/posthog/api/id_jag.py@@ -20,6 +20,7 @@ from django.views.decorators.csrf import csrf_exemptimport jwtimport requestsimport structlog+from oauth2_provider.utils import jwk_from_pemfrom rest_framework import statusfrom rest_framework.exceptions import ParseError, UnsupportedMediaTypefrom rest_framework.parsers import FormParser, JSONParser@@ -430,11 +431,14 @@ def _get_signing_key() -> str:def _construct_access_token(payload: dict[str, Any]) -> str:+ signing_key = _get_signing_key()+ # `kid` matches the thumbprint published in `/.well-known/jwks.json`, so a+ # resource server can pick the right key once a rotation publishes more than one.return jwt.encode(payload,- _get_signing_key(),+ signing_key,algorithm="RS256",- headers={"typ": ACCESS_TOKEN_TYPE},+ headers={"typ": ACCESS_TOKEN_TYPE, "kid": jwk_from_pem(signing_key).thumbprint()},)diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 1d5a8f20c7c0..605fdd1ccc68 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -1,5 +1,7 @@+import osimport base64import hashlib+import importlibfrom datetime import timedeltafrom types import SimpleNamespacefrom typing import Optional, cast@@ -12,12 +14,13 @@ from unittest.mock import patchfrom django.conf import settingsfrom django.db import OperationalError-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom django.utils import timezoneimport jwtfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa+from oauth2_provider.utils import jwk_from_pemfrom parameterized import parameterizedfrom rest_framework import status@@ -49,6 +52,26 @@ def generate_rsa_key() -> str:return pem.decode("utf-8")+def jwks_entry_to_public_key(key_data: dict):+ # Rebuild an RSA public key from a JWKS entry's modulus (n) and exponent (e).+ public_numbers = rsa.RSAPublicNumbers(+ e=int.from_bytes(base64.urlsafe_b64decode(key_data["e"] + "=="), "big"),+ n=int.from_bytes(base64.urlsafe_b64decode(key_data["n"] + "=="), "big"),+ )+ return public_numbers.public_key()+++def public_pem(public_key) -> str:+ return public_key.public_bytes(+ encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo+ ).decode("utf-8")+++def private_pem_to_public_pem(private_key_pem: str) -> str:+ private_key = serialization.load_pem_private_key(private_key_pem.encode(), password=None)+ return public_pem(private_key.public_key())++@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER,@@ -877,23 +900,81 @@ class TestOAuthAPI(APIBaseTest):jwks = response.json()self.assertIn("keys", jwks)- jwks = response.json()+ self.assertEqual(public_pem(jwks_entry_to_public_key(jwks["keys"][0])), self.public_key)++ def test_jwks_endpoint_publishes_active_and_inactive_keys(self):+ inactive_key_1 = generate_rsa_key()+ inactive_key_2 = generate_rsa_key()++ with override_settings(+ OAUTH2_PROVIDER={+ **settings.OAUTH2_PROVIDER,+ "OIDC_RSA_PRIVATE_KEYS_INACTIVE": [inactive_key_1, inactive_key_2],+ }+ ):+ response = self.client.get("/.well-known/jwks.json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ keys = response.json()["keys"]++ # Active key plus both inactive keys, each published under a distinct kid+ self.assertEqual(len(keys), 3)+ self.assertEqual(len({key["kid"] for key in keys}), 3)++ published_public_pems = {public_pem(jwks_entry_to_public_key(key)) for key in keys}+ expected_public_pems = {+ private_pem_to_public_pem(pem) for pem in (self.private_key, inactive_key_1, inactive_key_2)+ }+ self.assertEqual(published_public_pems, expected_public_pems)++ def test_jwks_endpoint_publishes_only_active_key_when_no_inactive_keys(self):+ with override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEYS_INACTIVE": []}):+ response = self.client.get("/.well-known/jwks.json")- key_data = jwks["keys"][0]- public_numbers = rsa.RSAPublicNumbers(- e=int.from_bytes(base64.urlsafe_b64decode(key_data["e"] + "=="), "big"),- n=int.from_bytes(base64.urlsafe_b64decode(key_data["n"] + "=="), "big"),+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ keys = response.json()["keys"]+ self.assertEqual(len(keys), 1)+ self.assertEqual(public_pem(jwks_entry_to_public_key(keys[0])), self.public_key)++ def test_token_signed_with_inactive_key_still_verifies_via_jwks(self):+ # Simulates a rotation: a token signed by the previous active key keeps verifying+ # because that key is still published as an inactive key in the JWKS.+ previous_key = generate_rsa_key()+ previous_kid = jwk_from_pem(previous_key).thumbprint()++ token = jwt.encode(+ {"sub": "user-123", "aud": "test_confidential_client_id"},+ previous_key,+ algorithm="RS256",+ headers={"kid": previous_kid},)- public_key = public_numbers.public_key()+ with override_settings(+ OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEYS_INACTIVE": [previous_key]}+ ):+ response = self.client.get("/.well-known/jwks.json")- public_key_pem_bytes = public_key.public_bytes(- encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ matching_entry = next(key for key in response.json()["keys"] if key["kid"] == previous_kid)++ decoded = jwt.decode(+ token,+ jwks_entry_to_public_key(matching_entry),+ algorithms=["RS256"],+ audience="test_confidential_client_id",)+ self.assertEqual(decoded["sub"], "user-123")- public_key_pem_str = public_key_pem_bytes.decode("utf-8")+ def test_jwks_endpoint_errors_when_an_inactive_key_is_empty(self):+ # An empty PEM raises in the JWKS view — this is why settings filters empties out+ # before they ever reach OIDC_RSA_PRIVATE_KEYS_INACTIVE.+ with override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEYS_INACTIVE": [""]}):+ with self.assertRaises(ValueError):+ self.client.get("/.well-known/jwks.json")- self.assertEqual(public_key_pem_str, self.public_key)+ def test_configured_inactive_keys_never_contain_empty_strings(self):+ inactive_keys = cast(list[str], settings.OAUTH2_PROVIDER["OIDC_RSA_PRIVATE_KEYS_INACTIVE"])+ self.assertNotIn("", inactive_keys)def test_id_token_not_returned_without_openid_scope(self):data_without_openid = {@@ -3359,3 +3440,44 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):response = self.client.get("/.well-known/oauth-authorization-server")metadata = response.json()self.assertNotIn("posthog_region", metadata)+++class TestOIDCInactiveKeysSetting(SimpleTestCase):+ """OIDC_RSA_PRIVATE_KEYS_INACTIVE is assembled from two env vars so multi-line PEMs+ don't need delimiter parsing. Only keys that are actually set may be included — an+ empty entry would break the JWKS endpoint (see test_jwks_endpoint_errors_when_an_inactive_key_is_empty).++ Reloading posthog.settings.web only rebinds names in that module; django.conf.settings+ is populated from the posthog.settings package and is unaffected, so this stays isolated.+ """++ @parameterized.expand(+ [+ ("both_unset", None, None, []),+ ("both_blank", "", "", []),+ ("only_first_set", "key-1", None, ["key-1"]),+ ("only_second_set", None, "key-2", ["key-2"]),+ ("first_blank_second_set", "", "key-2", ["key-2"]),+ ("both_set", "key-1", "key-2", ["key-1", "key-2"]),+ ]+ )+ def test_inactive_keys_built_from_env_vars(self, _name, env_1, env_2, expected):+ env_vars = {+ "OIDC_RSA_PRIVATE_KEY_INACTIVE_1": env_1,+ "OIDC_RSA_PRIVATE_KEY_INACTIVE_2": env_2,+ }+ overrides = {var: value for var, value in env_vars.items() if value is not None}++ web_settings = importlib.import_module("posthog.settings.web")+ try:+ with patch.dict(os.environ, overrides, clear=False):+ for var, value in env_vars.items():+ if value is None:+ os.environ.pop(var, None)+ importlib.reload(web_settings)+ self.assertEqual(web_settings.OIDC_RSA_PRIVATE_KEYS_INACTIVE, expected)+ self.assertNotIn("", web_settings.OIDC_RSA_PRIVATE_KEYS_INACTIVE)+ finally:+ # Restore module attributes to the real environment (patch.dict has already+ # restored os.environ by this point, so this reload sees the original vars).+ importlib.reload(web_settings)diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex dbeec13abd21..af2fc8e03797 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -23,6 +23,7 @@ from django.utils import timezoneimport jwtfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa+from oauth2_provider.utils import jwk_from_pemfrom rest_framework import statusfrom posthog.api.id_jag import (@@ -174,6 +175,8 @@ class TestIdJagTokenEndpoint(APIBaseTest):header = jwt.get_unverified_header(body["access_token"])self.assertEqual(header["typ"], ACCESS_TOKEN_TYPE)self.assertEqual(header["alg"], "RS256")+ # kid matches the JWKS thumbprint so resource servers can select the key during rotation+ self.assertEqual(header["kid"], jwk_from_pem(_AS_PRIVATE_KEY_PEM).thumbprint())def test_email_claim_is_preferred_over_sub_for_user_lookup(self) -> None:# IdPs are not required to put an email in `sub` — it may be an opaque@@ -834,6 +837,27 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):resp = self._call_authenticated(token)self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)+ def test_token_signed_with_inactive_key_still_authenticates(self) -> None:+ # Mid-rotation: a token minted under the previous active key keeps working once+ # that key is demoted to inactive and a freshly generated key takes over signing.+ token = self._mint_access_token(scope="user:read", signing_pem=_AS_PRIVATE_KEY_PEM)+ with override_settings(+ OIDC_RSA_PRIVATE_KEY=_generate_rsa_pem(),+ OIDC_RSA_PRIVATE_KEYS_INACTIVE=[_AS_PRIVATE_KEY_PEM],+ ):+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertEqual(resp.json()["email"], self.user.email)++ def test_token_signed_with_neither_active_nor_inactive_key_rejected(self) -> None:+ token = self._mint_access_token(scope="user:read", signing_pem=_generate_rsa_pem())+ with override_settings(+ OIDC_RSA_PRIVATE_KEY=_AS_PRIVATE_KEY_PEM,+ OIDC_RSA_PRIVATE_KEYS_INACTIVE=[_generate_rsa_pem()],+ ):+ resp = self._call_authenticated(token)+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)+def test_missing_required_claim_rejected(self) -> None:# Hand-craft without `scope`now = int(time.time())diff --git a/posthog/auth.py b/posthog/auth.pyindex 0082e2c03658..4ea58d512232 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -31,7 +31,7 @@ from zxcvbn import zxcvbnfrom posthog.clickhouse.query_tagging import tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.helpers.two_factor_session import enforce_two_factor-from posthog.jwt import PosthogJwtAudience, decode_jwt, get_oidc_public_key+from posthog.jwt import PosthogJwtAudience, decode_jwt, get_oidc_verification_keysfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrandfrom posthog.models.personal_api_key import (LEGACY_PERSONAL_API_KEY_SALT,@@ -515,49 +515,52 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):if not self._is_id_jag_token(token):return None- public_key = get_oidc_public_key()- if public_key is None:+ verification_keys = get_oidc_verification_keys()+ if not verification_keys:raise AuthenticationFailed(detail="ID-JAG access tokens are not configured on this server.")site_url = (settings.SITE_URL or "").rstrip("/")if not site_url:raise AuthenticationFailed(detail="ID-JAG access tokens are not configured on this server.")- try:- claims = jwt.decode(- token,- public_key,- algorithms=["RS256"],- audience=site_url,- issuer=site_url,- leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,- options={- "require": [- "iss",- "sub",- "email",- "aud",- "exp",- "iat",- "client_id",- "scope",- "org_id",- ],- "verify_signature": True,- "verify_exp": True,- "verify_aud": True,- "verify_iss": True,- },- )- except jwt.ExpiredSignatureError:- raise AuthenticationFailed(detail="ID-JAG access token has expired.")- except jwt.InvalidAudienceError:- raise AuthenticationFailed(detail="ID-JAG access token audience does not match this resource server.")- except jwt.InvalidIssuerError:- raise AuthenticationFailed(detail="ID-JAG access token has an unexpected issuer.")- except jwt.MissingRequiredClaimError as e:- raise AuthenticationFailed(detail=f"ID-JAG access token is missing required claim: {e.claim}.")- except jwt.PyJWTError:+ # Try the active signing key first, then any keys being rotated out. A wrong+ # key fails the signature check, so we move on; a key that matches but fails+ # claim validation (expiry, audience, …) raises the real error to report.+ claims = None+ for verification_key in verification_keys:+ try:+ claims = jwt.decode(+ token,+ verification_key,+ algorithms=["RS256"],+ audience=site_url,+ issuer=site_url,+ leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,+ options={+ "require": ["iss", "sub", "email", "aud", "exp", "iat", "client_id", "scope", "org_id"],+ "verify_signature": True,+ "verify_exp": True,+ "verify_aud": True,+ "verify_iss": True,+ },+ )+ break+ except jwt.InvalidSignatureError:+ continue+ except jwt.ExpiredSignatureError:+ raise AuthenticationFailed(detail="ID-JAG access token has expired.")+ except jwt.InvalidAudienceError:+ raise AuthenticationFailed(+ detail="ID-JAG access token audience does not match this resource server."+ )+ except jwt.InvalidIssuerError:+ raise AuthenticationFailed(detail="ID-JAG access token has an unexpected issuer.")+ except jwt.MissingRequiredClaimError as e:+ raise AuthenticationFailed(detail=f"ID-JAG access token is missing required claim: {e.claim}.")+ except jwt.PyJWTError:+ raise AuthenticationFailed(detail="ID-JAG access token is invalid.")++ if claims is None:raise AuthenticationFailed(detail="ID-JAG access token is invalid.")sub_parts = self._parse_sub(str(claims.get("sub", "")))diff --git a/posthog/jwt.py b/posthog/jwt.pyindex 817ad78696c4..eff16b26d696 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -61,15 +61,14 @@ def decode_jwt(token: str, audience: PosthogJwtAudience) -> dict[str, Any]:raise last_error or jwt.InvalidSignatureError("Signature verification failed")-def get_oidc_public_key() -> Any:- """Derive the verification key from the configured OIDC RSA private key.-- We don't memoize because the PEM is parsed once per request and parsing- is cheap (~ tens of microseconds); caching would risk staleness on- in-process key rotation.+def get_oidc_verification_keys() -> list[Any]:+ """Every public key that may have signed a still-valid OIDC/ID-JAG token: the+ active signing key plus any keys mid-rotation (the inactive keys also published+ in the JWKS). A token minted under a key being rotated out keeps verifying until+ it expires, instead of breaking the moment the active key is swapped."""- pem = getattr(settings, "OIDC_RSA_PRIVATE_KEY", None)- if not pem:- return None- private_key = serialization.load_pem_private_key(pem.encode(), password=None)- return private_key.public_key()+ pems = [+ getattr(settings, "OIDC_RSA_PRIVATE_KEY", None),+ *(getattr(settings, "OIDC_RSA_PRIVATE_KEYS_INACTIVE", None) or []),+ ]+ return [serialization.load_pem_private_key(pem.encode(), password=None).public_key() for pem in pems if pem]diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 34e1bf320907..476f240b5111 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -741,12 +741,19 @@ ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS = get_list(get_from_env("ERROR_TRACKOIDC_RSA_PRIVATE_KEY = os.getenv("OIDC_RSA_PRIVATE_KEY", "").replace("\\n", "\n")+OIDC_RSA_PRIVATE_KEY_INACTIVE_1 = os.getenv("OIDC_RSA_PRIVATE_KEY_INACTIVE_1", "").replace("\\n", "\n")+OIDC_RSA_PRIVATE_KEY_INACTIVE_2 = os.getenv("OIDC_RSA_PRIVATE_KEY_INACTIVE_2", "").replace("\\n", "\n")+OIDC_RSA_PRIVATE_KEYS_INACTIVE = [+ key for key in (OIDC_RSA_PRIVATE_KEY_INACTIVE_1, OIDC_RSA_PRIVATE_KEY_INACTIVE_2) if key+]+OAUTH_EXPIRED_TOKEN_RETENTION_PERIOD = 60 * 60 * 24 * 30 # 30 daysOAUTH2_PROVIDER = {"OIDC_ENABLED": True,"PKCE_REQUIRED": True, # We require PKCE for all OAuth flows - including confidential clients"OIDC_RSA_PRIVATE_KEY": OIDC_RSA_PRIVATE_KEY,+ "OIDC_RSA_PRIVATE_KEYS_INACTIVE": OIDC_RSA_PRIVATE_KEYS_INACTIVE,"SCOPES": {"openid": "OpenID Connect scope","profile": "Access to user's profile",