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.

feat(jwt): sign JWTs with dedicated key and support fallbacks (#61282)

Felipe Rosa de Almeida923268e63735
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 53b14d46c6ba..851f0bd55d3f 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1,7 +1,6 @@
import re
import json
import math
-import hashlib
import secrets
from datetime import timedelta
from functools import cached_property
@@ -31,7 +30,7 @@ from posthog.constants import AvailableFeature
from posthog.decorators import disallow_if_impersonated
from posthog.event_usage import report_user_action
from posthog.geoip import get_geoip_properties
-from posthog.jwt import PosthogJwtAudience, encode_jwt
+from posthog.jwt import PosthogJwtAudience, encode_jwt, signing_key_fingerprint
from posthog.models import ProductIntent, Team, TeamMarketingAnalyticsConfig, TeamRevenueAnalyticsConfig, User
from posthog.models.activity_logging.activity_log import (
ActivityLog,
@@ -551,13 +550,13 @@ LIVE_EVENTS_TOKEN_TTL_SECONDS = 24 * 60 * 60
def _live_events_token_cache_key(team: Team, user_id: int | None) -> str:
"""Build the cache key for the live-events JWT.
- Includes a short fingerprint of `settings.SECRET_KEY` so that rotating the
- signing secret automatically partitions the cache namespace - cached tokens
- signed with the old key become unreachable rather than served until TTL.
+ Includes a short fingerprint of `settings.JWT_SIGNING_KEY` so that rotating the
+ signing key automatically partitions the cache namespace - cached tokens signed
+ with the old key become unreachable rather than served until TTL.
Hashing also defends the cache key against future api-token formats that
might contain the `:` separator we use between components.
"""
- signing_fingerprint = hashlib.sha256(settings.SECRET_KEY.encode()).hexdigest()[:16]
+ signing_fingerprint = signing_key_fingerprint(settings.JWT_SIGNING_KEY)
return f"live_events_token:{signing_fingerprint}:{team.id}:{user_id}:{team.api_token}:{team.organization_id}"
@@ -567,8 +566,8 @@ def get_or_mint_live_events_token(team: Team, user_id: int | None) -> str:
The JWT itself is valid for 7 days. The cache TTL is 24h, so any token returned
from cache still has at least 6 days of remaining validity. The cache key includes
every field that ends up in the claims so api-token rotations or organization
- moves automatically force a fresh mint, plus a SECRET_KEY fingerprint so signing-
- key rotation auto-partitions the cache namespace (no manual flush needed).
+ moves automatically force a fresh mint, plus a JWT_SIGNING_KEY fingerprint so
+ signing-key rotation auto-partitions the cache namespace (no manual flush needed).
"""
cache_key = _live_events_token_cache_key(team, user_id)
cached = get_safe_cache(cache_key)
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 0961810e8bd0..dbeec13abd21 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -935,7 +935,7 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
`/api/projects/@current/`) get a default authenticator chain that
includes `JwtAuthentication` ahead of other token-based backends.
- `JwtAuthentication.decode_jwt` hard-codes HS256+SECRET_KEY and raises
+ `JwtAuthentication.decode_jwt` hard-codes HS256 + the JWT signing key and raises
`AuthenticationFailed` (→ 401) on any non-`jwt.DecodeError` exception,
including the `InvalidAlgorithmError` that fires for an RS256 ID-JAG
access token. If `IDJagAccessTokenAuthentication` doesn't run first,
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 4fce2b39fb4a..645df6daf7bc 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -3483,17 +3483,17 @@ class TestGetOrMintLiveEventsToken(APIBaseTest):
token_after = get_or_mint_live_events_token(self.team, second_user_id)
assert token_before != token_after
- def test_secret_key_rotation_partitions_the_cache_namespace(self) -> None:
- # SECRET_KEY rotation must invalidate cached tokens automatically — otherwise
+ def test_signing_key_rotation_partitions_the_cache_namespace(self) -> None:
+ # JWT signing-key rotation must invalidate cached tokens automatically — otherwise
# the livestream service would reject the cached old-key signatures for up
- # to the cache TTL. We embed a fingerprint of SECRET_KEY in the cache key so
+ # to the cache TTL. We embed a fingerprint of JWT_SIGNING_KEY in the cache key so
# the namespace partitions cleanly on rotation.
from posthog.api.team import get_or_mint_live_events_token
- token_old_secret = get_or_mint_live_events_token(self.team, self.user.id)
- with override_settings(SECRET_KEY="completely-different-rotated-secret"):
- token_new_secret = get_or_mint_live_events_token(self.team, self.user.id)
- assert token_old_secret != token_new_secret
+ token_old_key = get_or_mint_live_events_token(self.team, self.user.id)
+ with override_settings(JWT_SIGNING_KEY="completely-different-rotated-secret"):
+ token_new_key = get_or_mint_live_events_token(self.team, self.user.id)
+ assert token_old_key != token_new_key
# Sensitive Team/Project settings the frontend gates behind
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 96a640d45aab..817ad78696c4 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -1,3 +1,4 @@
+import hashlib
from datetime import UTC, datetime, timedelta
from enum import Enum
from typing import Any
@@ -7,6 +8,8 @@ from django.conf import settings
import jwt
from cryptography.hazmat.primitives import serialization
+JWT_ALGORITHM = "HS256"
+
class PosthogJwtAudience(Enum):
UNSUBSCRIBE = "posthog:unsubscribe"
@@ -17,6 +20,18 @@ class PosthogJwtAudience(Enum):
SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"
+def signing_key_fingerprint(key: str) -> str:
+ return hashlib.sha256(key.encode()).hexdigest()[:16]
+
+
+def _signing_key() -> str:
+ return settings.JWT_SIGNING_KEY
+
+
+def _verification_keys() -> list[str]:
+ return [_signing_key(), *settings.JWT_SIGNING_KEY_FALLBACKS]
+
+
def encode_jwt(payload: dict, expiry_delta: timedelta, audience: PosthogJwtAudience) -> str:
"""
Create a JWT ensuring that the correct audience and signing token is used
@@ -24,23 +39,26 @@ def encode_jwt(payload: dict, expiry_delta: timedelta, audience: PosthogJwtAudie
if not isinstance(audience, PosthogJwtAudience):
raise Exception("Audience must be in the list of PostHog-supported audiences")
- encoded_jwt = jwt.encode(
+ return jwt.encode(
{
**payload,
"exp": datetime.now(tz=UTC) + expiry_delta,
"aud": audience.value,
},
- settings.SECRET_KEY,
- algorithm="HS256",
+ _signing_key(),
+ algorithm=JWT_ALGORITHM,
)
- return encoded_jwt
-
def decode_jwt(token: str, audience: PosthogJwtAudience) -> dict[str, Any]:
- info = jwt.decode(token, settings.SECRET_KEY, audience=audience.value, algorithms=["HS256"])
+ last_error: jwt.InvalidSignatureError | None = None
+ for key in _verification_keys():
+ try:
+ return jwt.decode(token, key, audience=audience.value, algorithms=[JWT_ALGORITHM])
+ except jwt.InvalidSignatureError as error:
+ last_error = error
- return info
+ raise last_error or jwt.InvalidSignatureError("Signature verification failed")
def get_oidc_public_key() -> Any:
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index 3acc9e77d2bc..5371cf03f682 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -29,7 +29,7 @@ from products.exports.backend.models.subscription import (
from products.product_analytics.backend.models.insight import Insight
[email protected](settings, "SECRET_KEY", "not-so-secret")
[email protected](settings, "JWT_SIGNING_KEY", "not-so-secret")
@freeze_time("2022-01-01")
class TestSubscription(BaseTest):
def _create_insight_subscription(self, **kwargs):
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index be2cc7ee12bb..dbeff32583b4 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -65,6 +65,24 @@ DEFAULT_SECRET_KEY = "<randomly generated secret key>"
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY: str = os.getenv("SECRET_KEY", DEFAULT_SECRET_KEY)
+SECRET_KEY_FALLBACKS: list[str] = get_list(os.getenv("SECRET_KEY_FALLBACKS", ""))
+
+# Dedicated key for signing PostHog-issued JWTs (posthog.jwt), so JWT signing can move off
+# SECRET_KEY. Defaults to SECRET_KEY, so deployments keep working until they provision a
+# separate key; once set, add the old key to JWT_SIGNING_KEY_FALLBACKS so tokens already in
+# flight keep validating until they expire. An empty value coalesces back to SECRET_KEY —
+# signing with an empty key is never a valid intent.
+JWT_SIGNING_KEY: str = os.getenv("JWT_SIGNING_KEY", "") or SECRET_KEY
+# Previous JWT signing keys still trusted for verifying tokens in flight, newest first.
+# Defaults to SECRET_KEY_FALLBACKS only when *unset*; an explicit empty value (e.g.
+# JWT_SIGNING_KEY_FALLBACKS="") clears it, so operators can stop trusting old JWT keys
+# without disturbing SECRET_KEY_FALLBACKS (which Django also uses for session/CSRF rotation).
+JWT_SIGNING_KEY_FALLBACKS: list[str] = (
+ get_list(os.environ["JWT_SIGNING_KEY_FALLBACKS"])
+ if "JWT_SIGNING_KEY_FALLBACKS" in os.environ
+ else (SECRET_KEY_FALLBACKS if JWT_SIGNING_KEY == SECRET_KEY else [])
+)
+
if not DEBUG and not TEST and not STATIC_COLLECTION and SECRET_KEY == DEFAULT_SECRET_KEY:
logger.critical(
diff --git a/posthog/test/test_jwt.py b/posthog/test/test_jwt.py
new file mode 100644
index 000000000000..08faeb4995a8
--- /dev/null
+++ b/posthog/test/test_jwt.py
@@ -0,0 +1,142 @@
+from datetime import UTC, datetime, timedelta
+
+from django.conf import settings
+from django.test import SimpleTestCase, override_settings
+
+import jwt
+from parameterized import parameterized
+
+from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, signing_key_fingerprint
+
+PRIMARY = "primary-signing-key"
+ROTATED = "rotated-new-signing-key"
+UNKNOWN = "never-configured-signing-key"
+AUD = PosthogJwtAudience.EXPORTED_ASSET
+
+
+def _raw_token(
+ key: str,
+ *,
+ audience: PosthogJwtAudience = AUD,
+ kid: str | None = None,
+ expiry: timedelta = timedelta(minutes=5),
+ claims: dict | None = None,
+) -> str:
+ payload = {**(claims or {}), "exp": datetime.now(tz=UTC) + expiry, "aud": audience.value}
+ headers = {"kid": kid} if kid is not None else None
+ return jwt.encode(payload, key, algorithm="HS256", headers=headers)
+
+
+@override_settings(JWT_SIGNING_KEY=PRIMARY, JWT_SIGNING_KEY_FALLBACKS=[])
+class TestJwt(SimpleTestCase):
+ def test_encode_does_not_tag_token_with_a_key_id(self):
+ # Tokens stay untagged so the header leaks nothing about which key signed them.
+ token = encode_jwt({"id": 7}, timedelta(minutes=5), AUD)
+ assert "kid" not in jwt.get_unverified_header(token)
+
+ @parameterized.expand(
+ [
+ ("no rotation", PRIMARY, []),
+ ("primary demoted to fallback after rotation", ROTATED, [PRIMARY]),
+ ]
+ )
+ def test_encoded_token_verifies_through_rotation(self, _name: str, signing_key: str, fallbacks: list[str]):
+ # Signed under the class-level PRIMARY key, then verified under the rotated settings.
+ token = encode_jwt({"id": 7}, timedelta(minutes=5), AUD)
+ with override_settings(JWT_SIGNING_KEY=signing_key, JWT_SIGNING_KEY_FALLBACKS=fallbacks):
+ assert decode_jwt(token, AUD)["id"] == 7
+
+ @parameterized.expand(
+ [
+ # name, active_signing_key, fallbacks, key_token_was_signed_with, expect_ok
+ ("current signing key", PRIMARY, [], PRIMARY, True),
+ ("fallback key after rotation", ROTATED, [PRIMARY], PRIMARY, True),
+ ("old key dropped from fallbacks", ROTATED, [], PRIMARY, False),
+ ("unknown key", PRIMARY, [], UNKNOWN, False),
+ ]
+ )
+ def test_decode_outcome_by_key_state(
+ self,
+ _name: str,
+ active_key: str,
+ fallbacks: list[str],
+ signing_key: str,
+ expect_ok: bool,
+ ):
+ token = _raw_token(signing_key, claims={"id": 7})
+ with override_settings(JWT_SIGNING_KEY=active_key, JWT_SIGNING_KEY_FALLBACKS=fallbacks):
+ if expect_ok:
+ assert decode_jwt(token, AUD)["id"] == 7
+ else:
+ with self.assertRaises(jwt.InvalidSignatureError):
+ decode_jwt(token, AUD)
+
+ @parameterized.expand(
+ [
+ # A stray/forged kid must not influence verification — only the signature matters.
+ ("trusted signature, forged kid", PRIMARY, True),
+ ("untrusted signature, forged kid", UNKNOWN, False),
+ ]
+ )
+ def test_decode_ignores_stray_kid_header(self, _name: str, signing_key: str, expect_ok: bool):
+ token = _raw_token(signing_key, kid="some-forged-kid", claims={"id": 7})
+ if expect_ok:
+ assert decode_jwt(token, AUD)["id"] == 7
+ else:
+ with self.assertRaises(jwt.InvalidSignatureError):
+ decode_jwt(token, AUD)
+
+ @parameterized.expand(
+ [
+ ("expired", lambda: encode_jwt({"id": 7}, timedelta(seconds=-1), AUD), jwt.ExpiredSignatureError),
+ (
+ "wrong audience",
+ lambda: encode_jwt({"id": 7}, timedelta(minutes=5), PosthogJwtAudience.UNSUBSCRIBE),
+ jwt.InvalidAudienceError,
+ ),
+ ("malformed garbage", lambda: "not-a-jwt", jwt.DecodeError),
+ ("malformed empty", lambda: "", jwt.DecodeError),
+ ("malformed two segments", lambda: "a.b", jwt.DecodeError),
+ ("malformed bad base64", lambda: "a.b.c", jwt.DecodeError),
+ ]
+ )
+ def test_non_signature_errors_propagate(self, _name: str, token_factory, expected: type[Exception]):
+ # The multi-key loop only swallows InvalidSignatureError; every other failure surfaces as-is.
+ with self.assertRaises(expected):
+ decode_jwt(token_factory(), AUD)
+
+ @parameterized.expand(
+ [
+ ("expired", lambda: _raw_token(PRIMARY, expiry=timedelta(seconds=-1)), jwt.ExpiredSignatureError),
+ (
+ "wrong audience",
+ lambda: _raw_token(PRIMARY, audience=PosthogJwtAudience.UNSUBSCRIBE),
+ jwt.InvalidAudienceError,
+ ),
+ ]
+ )
+ @override_settings(JWT_SIGNING_KEY=ROTATED, JWT_SIGNING_KEY_FALLBACKS=[PRIMARY])
+ def test_claim_errors_from_fallback_key_are_not_masked(self, _name: str, token_factory, expected: type[Exception]):
+ # A token signed by the fallback key (PRIMARY) fails the InvalidSignatureError check against
+ # the active key (ROTATED) first; the loop must keep going and surface the claim error raised
+ # once PRIMARY matches the signature — not the earlier mismatch.
+ with self.assertRaises(expected):
+ decode_jwt(token_factory(), AUD)
+
+ @parameterized.expand([("audience value", AUD.value), ("none", None), ("int", 5)])
+ def test_encode_rejects_non_audience(self, _name: str, bad_audience):
+ with self.assertRaises(Exception):
+ encode_jwt({"id": 7}, timedelta(minutes=5), bad_audience)
+
+ def test_signing_key_fingerprint_is_stable_and_key_specific(self):
+ assert signing_key_fingerprint(PRIMARY) == signing_key_fingerprint(PRIMARY)
+ assert signing_key_fingerprint(PRIMARY) != signing_key_fingerprint(ROTATED)
+ assert len(signing_key_fingerprint(PRIMARY)) == 16
+
+
+class TestJwtSigningKeyDefaults(SimpleTestCase):
+ def test_signing_key_settings_default_to_secret_key(self):
+ # With no JWT_SIGNING_KEY* env set (the test environment), JWT signing transparently
+ # reuses SECRET_KEY and its fallbacks, so nothing breaks until a key is provisioned.
+ assert settings.JWT_SIGNING_KEY == settings.SECRET_KEY
+ assert settings.JWT_SIGNING_KEY_FALLBACKS == settings.SECRET_KEY_FALLBACKS