: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(livestream): support JWT secret fallbacks for key rotation (#62768)
Felipe Rosa de Almeida4780bd825eac
diff --git a/bin/start-go-service b/bin/start-go-serviceindex c4066c33e578..8d75ec9609f1 100755--- a/bin/start-go-service+++ b/bin/start-go-service@@ -57,9 +57,6 @@ case "$GO_SVC" in# MMDB path, relative to livestream directory where air runsexport LIVESTREAM_MMDB_PATH=../share/GeoLite2-City.mmdb- # Postgres settings- export LIVESTREAM_POSTGRES_URL=postgres://posthog:posthog@localhost:5432/posthog-# Redis (needed for real-time notifications SSE endpoint)export LIVESTREAM_REDIS_URL="redis://localhost:6379"diff --git a/livestream/auth/jwt.go b/livestream/auth/jwt.goindex 222642a185a1..912072b57e9f 100644--- a/livestream/auth/jwt.go+++ b/livestream/auth/jwt.go@@ -73,6 +73,23 @@ func GetAuthClaims(header http.Header) (teamID int, token string, err error) {return c.TeamID, c.Token, nil}+// verificationKeys returns the active signing secret plus any fallback secrets still+// accepted for verification. Mirrors Django's JWT_SIGNING_KEY_FALLBACKS so tokens+// signed with a previous key keep working mid-rotation until they expire.+// Fallbacks come from jwt.secret_fallbacks — a YAML list or a comma-separated string+// (the env var LIVESTREAM_JWT_SECRET_FALLBACKS form).+func verificationKeys() jwt.VerificationKeySet {+ keys := []jwt.VerificationKey{[]byte(viper.GetString("jwt.secret"))}+ for _, entry := range viper.GetStringSlice("jwt.secret_fallbacks") {+ for _, fallback := range strings.Split(entry, ",") {+ if fallback = strings.TrimSpace(fallback); fallback != "" {+ keys = append(keys, []byte(fallback))+ }+ }+ }+ return jwt.VerificationKeySet{Keys: keys}+}+func decodeAuthToken(authHeader string) (jwt.MapClaims, error) {// split the tokenparts := strings.Split(authHeader, " ")@@ -92,8 +109,7 @@ func decodeAuthToken(authHeader string) (jwt.MapClaims, error) {if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])}- // Here you should specify the secret used to sign your JWTs.- return []byte(viper.GetString("jwt.secret")), nil+ return verificationKeys(), nil})if err != nil {diff --git a/livestream/auth/jwt_test.go b/livestream/auth/jwt_test.goindex 0b53b062fc48..87180237ede3 100644--- a/livestream/auth/jwt_test.go+++ b/livestream/auth/jwt_test.go@@ -100,6 +100,53 @@ func TestParseAuthClaims(t *testing.T) {}}+func TestDecodeAuthTokenWithFallbackSecrets(t *testing.T) {+ viper.Set("jwt.secret", "current-secret")+ t.Cleanup(func() {+ viper.Set("jwt.secret", "test-secret")+ viper.Set("jwt.secret_fallbacks", nil)+ })++ tests := []struct {+ name string+ fallbacks any+ signingKey string+ expectError bool+ }{+ {name: "current secret with no fallbacks", fallbacks: nil, signingKey: "current-secret"},+ {name: "old secret with no fallbacks", fallbacks: nil, signingKey: "old-secret-1", expectError: true},+ {name: "current secret with fallbacks set", fallbacks: "old-secret-1,old-secret-2", signingKey: "current-secret"},+ {name: "first fallback, env-style comma string", fallbacks: "old-secret-1,old-secret-2", signingKey: "old-secret-1"},+ {name: "second fallback, env-style comma string", fallbacks: "old-secret-1,old-secret-2", signingKey: "old-secret-2"},+ {name: "fallback from yaml-style list", fallbacks: []string{"old-secret-1", "old-secret-2"}, signingKey: "old-secret-2"},+ {name: "whitespace around commas is trimmed", fallbacks: "old-secret-1, old-secret-2", signingKey: "old-secret-2"},+ {name: "unknown secret with fallbacks set", fallbacks: "old-secret-1,old-secret-2", signingKey: "wrong-secret", expectError: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ viper.Set("jwt.secret_fallbacks", tt.fallbacks)++ claims, err := decodeAuthToken("Bearer " + createTokenSignedWith(tt.signingKey))+ if tt.expectError {+ assert.ErrorContains(t, err, "signature is invalid")+ } else {+ require.NoError(t, err)+ assert.Equal(t, ExpectedScope, claims["aud"])+ }+ })+ }+}++func createTokenSignedWith(secret string) string {+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "aud": ExpectedScope,+ "exp": time.Now().Add(time.Hour).Unix(),+ })+ tokenString, _ := token.SignedString([]byte(secret))+ return tokenString+}+func createValidToken(audience string, claims jwt.MapClaims) string {newClaims := jwt.MapClaims{"aud": audience,diff --git a/livestream/configs/configs.example.yml b/livestream/configs/configs.example.ymlindex 8738a9f69fcc..a958ee5abbcc 100644--- a/livestream/configs/configs.example.yml+++ b/livestream/configs/configs.example.yml@@ -21,9 +21,10 @@ consumers:mmdb:path: 'mmdb.db'jwt:- token: '<randomly generated secret key>'-postgres:- url: 'postgres://postgres:postgres@localhost:5432/postgres'+ secret: '<randomly generated secret key>'+ # Previous secrets still accepted for verification during key rotation+ secret_fallbacks:+ - '<previous secret key>'cors_allow_origins:- "https://example.com"- "https://sub.example.com"diff --git a/livestream/configs/configs.go b/livestream/configs/configs.goindex f0d31dcbb235..b19a78fd8e20 100644--- a/livestream/configs/configs.go+++ b/livestream/configs/configs.go@@ -12,12 +12,11 @@ type MMDBConfig struct {Path string}-type PostgresConfig struct {- URL string-}-type JWTConfig struct {Secret string+ // Previous secrets still accepted for verification (never used for signing),+ // so tokens signed before a key rotation keep working until they expire.+ SecretFallbacks []string `mapstructure:"secret_fallbacks"`}type SessionRecordingConfig struct {@@ -62,7 +61,6 @@ type Config struct {Consumers ConsumersConfig `mapstructure:"consumers"`Parallelism int `mapstructure:"parallelism"`CORSAllowOrigins []string `mapstructure:"cors_allow_origins"`- Postgres PostgresConfigJWT JWTConfigSessionRecording SessionRecordingConfig `mapstructure:"session_recording"`Redis RedisConfig@@ -129,11 +127,9 @@ func InitConfigs(filename, configPath string) {_ = viper.BindEnv("consumers.notification.heartbeat_interval_ms") // LIVESTREAM_CONSUMERS_NOTIFICATION_HEARTBEAT_INTERVAL_MS_ = viper.BindEnv("consumers.notification.max_poll_interval_ms") // LIVESTREAM_CONSUMERS_NOTIFICATION_MAX_POLL_INTERVAL_MS- // Postgres settings- _ = viper.BindEnv("postgres.url") // LIVESTREAM_POSTGRES_URL-// JWT settings- _ = viper.BindEnv("jwt.secret") // LIVESTREAM_JWT_SECRET+ _ = viper.BindEnv("jwt.secret") // LIVESTREAM_JWT_SECRET+ _ = viper.BindEnv("jwt.secret_fallbacks") // LIVESTREAM_JWT_SECRET_FALLBACKS (comma-separated)// Session recording settings_ = viper.BindEnv("session_recording.max_lru_entries") // LIVESTREAM_SESSION_RECORDING_MAX_LRU_ENTRIESdiff --git a/livestream/configs/configs_test.go b/livestream/configs/configs_test.goindex 38c0e34c5d79..4f5f2be2971c 100644--- a/livestream/configs/configs_test.go+++ b/livestream/configs/configs_test.go@@ -20,7 +20,6 @@ func TestLoadConfig(t *testing.T) {setup: func() {// Values already set in setupTestConfig_ = os.Setenv("LIVESTREAM_JWT_SECRET", "token")- _ = os.Setenv("LIVESTREAM_POSTGRES_URL", "pg url")},want: &Config{Debug: true,@@ -49,11 +48,9 @@ func TestLoadConfig(t *testing.T) {GroupID: "livestream-dev-notifications",},},- Postgres: PostgresConfig{- URL: "pg url",- },JWT: JWTConfig{- Secret: "token",+ Secret: "token",+ SecretFallbacks: []string{"<previous secret key>"},},SessionRecording: SessionRecordingConfig{MaxLRUEntries: 2_000_000_000,@@ -79,7 +76,6 @@ func TestLoadConfig(t *testing.T) {}assert.NoError(t, err)assert.Equal(t, tt.want, got)- assert.Equal(t, tt.want.Postgres.URL, viper.GetString("postgres.url"))assert.Equal(t, tt.want.JWT.Secret, viper.GetString("jwt.secret"))})}diff --git a/livestream/docker-compose.yml b/livestream/docker-compose.ymlindex 9b74babb1a7d..952ae4e0a3bd 100644--- a/livestream/docker-compose.yml+++ b/livestream/docker-compose.yml@@ -1,20 +1,6 @@version: '3.8'services:- postgres:- image: postgres:16-alpine- restart: always- ports:- - '127.0.0.1:5432:5432'- environment:- POSTGRES_USER: postgres- POSTGRES_PASSWORD: postgres- POSTGRES_DB: liveevents- healthcheck:- test: ['CMD-SHELL', 'pg_isready -U postgres']- interval: 5s- timeout: 5s-redis:image: redis:7.2restart: always