: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(feature-flags): reject expired personal api keys (#121703)
Alex Lider0a04a7e223a6
diff --git a/posthog/storage/auth_token_cache_verifier.py b/posthog/storage/auth_token_cache_verifier.pyindex 626bd4de190d..e435b5749609 100644--- a/posthog/storage/auth_token_cache_verifier.py+++ b/posthog/storage/auth_token_cache_verifier.py@@ -326,6 +326,7 @@ def _verify_personal_entries("scopes","scoped_teams","scoped_organizations",+ "expires_at","user__id","user__is_active",)@@ -370,6 +371,11 @@ def _verify_personal_entries(_record_stale("personal", result)continue+ if pak.is_expired:+ stale_keys.append(key)+ _record_stale("personal", result)+ continue+# Rust rejects personal entries with key_id: None; clean them up proactivelycached_key_id = data.get("key_id")if cached_key_id is None:diff --git a/posthog/storage/team_access_cache_signal_handlers.py b/posthog/storage/team_access_cache_signal_handlers.pyindex ec566f627351..4b1bd4c51f84 100644--- a/posthog/storage/team_access_cache_signal_handlers.py+++ b/posthog/storage/team_access_cache_signal_handlers.py@@ -205,8 +205,8 @@ def _defer_token_invalidation(secure_value: str) -> None:# PAK fields whose changes affect cached TokenAuthData and require cache invalidation.# secure_value: the token hash itself (cache key)-# scopes, scoped_teams, scoped_organizations: cached in TokenAuthData::Personal-_PAK_CACHE_RELEVANT_FIELDS = frozenset({"secure_value", "scopes", "scoped_teams", "scoped_organizations"})+# scopes, scoped_teams, scoped_organizations, expires_at: cached in TokenAuthData::Personal+_PAK_CACHE_RELEVANT_FIELDS = frozenset({"secure_value", "scopes", "scoped_teams", "scoped_organizations", "expires_at"})def _handle_api_key_saved(diff --git a/posthog/storage/test/test_auth_token_cache_verifier.py b/posthog/storage/test/test_auth_token_cache_verifier.pyindex 52747a97fad9..9f498a815920 100644--- a/posthog/storage/test/test_auth_token_cache_verifier.py+++ b/posthog/storage/test/test_auth_token_cache_verifier.py@@ -1,9 +1,11 @@import jsonimport pickle+from datetime import timedeltafrom unittest.mock import patchfrom django.test import SimpleTestCase, TestCase+from django.utils import timezoneimport redis as redis_libimport zstandard as zstd@@ -202,6 +204,32 @@ class TestAuthTokenCacheVerifier(TestCase):assert not self.redis.exists(key)+ def test_personal_token_for_expired_key_is_removed(self):+ pak = PersonalAPIKey.objects.create(+ user=self.user,+ label="test-pak-expired",+ secure_value=hash_key_value("phx_pak_expired", mode="sha256"),+ scopes=["feature_flag:read"],+ expires_at=timezone.now() - timedelta(minutes=1),+ )++ key = self._set_cache(+ pak.secure_value,+ {+ "type": "personal",+ "user_id": self.user.id,+ "key_id": str(pak.id),+ "org_ids": [str(self.org.id)],+ "scoped_teams": None,+ "scoped_orgs": None,+ "scopes": ["feature_flag:read"],+ },+ )++ verify_and_fix_auth_token_cache(self.redis, batch_size=10)++ assert not self.redis.exists(key)+def test_personal_token_with_changed_org_membership_is_removed(self):pak = PersonalAPIKey.objects.create(user=self.user,diff --git a/posthog/storage/test/test_team_access_cache_signal_handlers.py b/posthog/storage/test/test_team_access_cache_signal_handlers.pyindex 990214d0372d..7b7c009207b9 100644--- a/posthog/storage/test/test_team_access_cache_signal_handlers.py+++ b/posthog/storage/test/test_team_access_cache_signal_handlers.py@@ -618,6 +618,7 @@ class TestPersonalApiKeySavedSignalHandler(TestCase):(["scopes"], True, "scopes only"),(["scoped_teams"], True, "scoped_teams only"),(["scoped_organizations"], True, "scoped_organizations only"),+ (["expires_at"], True, "expires_at only"),(["label", "scopes"], True, "label and scopes"),])diff --git a/rust/feature-flags/src/api/auth.rs b/rust/feature-flags/src/api/auth.rsindex 777a43706111..1463c5a9c97a 100644--- a/rust/feature-flags/src/api/auth.rs+++ b/rust/feature-flags/src/api/auth.rs@@ -48,6 +48,11 @@ pub enum TokenAuthData {/// this field (they resolve as `None` until the entry refreshes).#[serde(default)]current_team_id: Option<i32>,+ /// When the key stops working; `None` means it never expires. Checked on every use,+ /// including cache hits, so an entry cannot outlive the key. `#[serde(default)]` keeps+ /// backwards compatibility with cached entries that predate this field.+ #[serde(default)]+ expires_at: Option<chrono::DateTime<chrono::Utc>>,},#[serde(rename = "project_secret")]ProjectSecret {@@ -424,6 +429,7 @@ async fn load_personal_key_from_pg(pak.scopes,pak.scoped_teams,pak.scoped_organizations,+ pak.expires_at,u.id as user_id,u.current_team_id,ARRAY(@@ -451,6 +457,7 @@ async fn load_personal_key_from_pg(let scopes: Option<Vec<String>> = row.try_get("scopes")?;let org_ids: Vec<String> = row.try_get("org_ids")?;let current_team_id: Option<i32> = row.try_get("current_team_id")?;+ let expires_at: Option<chrono::DateTime<chrono::Utc>> = row.try_get("expires_at")?;Ok(Some(TokenAuthData::Personal {user_id,@@ -460,6 +467,7 @@ async fn load_personal_key_from_pg(scoped_orgs: scoped_organizations,scopes,current_team_id,+ expires_at,}))}None => {@@ -523,8 +531,15 @@ fn validate_personal_key_metadata(data: &TokenAuthData, team: &Team) -> Result<(scoped_teams,scoped_orgs,scopes,+ expires_at,..} => {+ // Same rule as Django's PersonalAPIKey.is_expired: the expiry instant itself is expired+ if expires_at.is_some_and(|expiry| expiry <= chrono::Utc::now()) {+ debug!("Personal API key has expired");+ return Err(FlagError::PersonalApiKeyInvalid);+ }+// Check scoped_teams restrictionif let Some(teams) = scoped_teams {if !teams.is_empty() && !teams.contains(&team.id) {@@ -891,6 +906,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec!["feature_flag:read".to_string()]),current_team_id: None,+ expires_at: None,};let json = serde_json::to_string(&data).unwrap();assert!(json.contains("\"type\":\"personal\""));@@ -976,6 +992,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec!["feature_flag:read".to_string()]),current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -999,6 +1016,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec!["feature_flag:read".to_string()]),current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -1022,11 +1040,47 @@ mod tests {scoped_orgs: None,scopes: None,current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());}+ /// An expired key must fail even when every other check passes, including from a cached+ /// entry that was written before the key expired.+ #[rstest::rstest]+ #[case::expired_a_minute_ago(Some(chrono::Utc::now() - chrono::Duration::minutes(1)), false)]+ #[case::expires_in_a_day(Some(chrono::Utc::now() + chrono::Duration::days(1)), true)]+ #[case::never_expires(None, true)]+ fn test_validate_personal_key_metadata_checks_expiry(+ #[case] expires_at: Option<chrono::DateTime<chrono::Utc>>,+ #[case] expected_ok: bool,+ ) {+ let team = Team {+ id: 1,+ organization_id: Some(+ uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),+ ),+ ..Default::default()+ };++ let data = TokenAuthData::Personal {+ user_id: 42,+ key_id: None,+ org_ids: vec!["550e8400-e29b-41d4-a716-446655440000".to_string()],+ scoped_teams: None,+ scoped_orgs: None,+ scopes: Some(vec!["feature_flag:read".to_string()]),+ current_team_id: None,+ expires_at,+ };++ assert_eq!(+ validate_personal_key_metadata(&data, &team).is_ok(),+ expected_ok+ );+ }+#[test]fn test_validate_personal_key_metadata_allows_unscoped() {let team = Team {@@ -1045,6 +1099,7 @@ mod tests {scoped_orgs: None,scopes: None,current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -1068,6 +1123,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec!["*".to_string()]),current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -1091,6 +1147,7 @@ mod tests {scoped_orgs: Some(vec!["550e8400-e29b-41d4-a716-446655440000".to_string()]),scopes: None,current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -1114,6 +1171,7 @@ mod tests {scoped_orgs: Some(vec!["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string()]),scopes: None,current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -1137,6 +1195,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec!["session_recording:read".to_string()]),current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -1198,6 +1257,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec!["feature_flag:write".to_string()]),current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -1224,6 +1284,7 @@ mod tests {"feature_flag:read".to_string(),]),current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -1249,6 +1310,7 @@ mod tests {scoped_orgs: Some(vec![]), // empty = no restrictionscopes: None, // None = no restrictioncurrent_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -1274,6 +1336,7 @@ mod tests {scoped_orgs: None,scopes: Some(vec![]),current_team_id: None,+ expires_at: None,};assert!(matches!(@@ -1298,6 +1361,7 @@ mod tests {scoped_orgs: None,scopes: None,current_team_id: None,+ expires_at: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());diff --git a/rust/feature-flags/tests/test_personal_api_key_scopes.rs b/rust/feature-flags/tests/test_personal_api_key_scopes.rsindex 8874f83725f6..23122fef8a82 100644--- a/rust/feature-flags/tests/test_personal_api_key_scopes.rs+++ b/rust/feature-flags/tests/test_personal_api_key_scopes.rs@@ -2,6 +2,7 @@ mod common;use feature_flags::config::DEFAULT_TEST_CONFIG;use feature_flags::utils::test_utils::TestContext;+use sha2::Digest;use uuid::Uuid;/// Helper: Clean up test data (PAK, organization memberships, and user)@@ -402,6 +403,94 @@ async fn test_personal_api_key_mixed_scopes_both_valid() {cleanup_test_data(&ctx, pak_id, user_id).await;}+/// Expiry is enforced in the flags service itself: a key that is valid in every other way is+/// refused once `expires_at` has passed, including on a cache hit from before it expired.+#[tokio::test]+async fn test_personal_api_key_expired_is_rejected() {+ let config = DEFAULT_TEST_CONFIG.clone();+ let ctx = TestContext::new(Some(&config)).await;++ let org_id = Uuid::new_v4();+ let team = ctx+ .insert_new_team_with_org(None, &org_id.to_string())+ .await+ .unwrap();+ let user_email = format!("test_{}@example.com", Uuid::new_v4());+ let user_id = ctx+ .create_user_with_options(&user_email, &org_id, Some(team.id), true)+ .await+ .unwrap();+ ctx.add_user_to_organization(user_id, &org_id, 15)+ .await+ .unwrap();+ let (pak_id, secure_value) = ctx+ .create_personal_api_key(+ user_id,+ "Test PAK - Expiry",+ vec!["feature_flag:read"],+ None,+ None,+ )+ .await+ .unwrap();++ let server = common::ServerHandle::for_config(config.clone()).await;+ server.wait_until_ready().await;+ let client = reqwest::Client::new();+ let url = format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ );++ // A key with no expiry authenticates, and this request caches its auth data.+ let response = client+ .get(&url)+ .header("Authorization", format!("Bearer {secure_value}"))+ .send()+ .await+ .unwrap();+ assert_ne!(+ response.status(),+ 401,+ "A key without an expiry is accepted"+ );++ // Expire the key and evict its cache entry, as Django does when it saves an expiry, so the+ // next request reloads the key through the SQL and sees the new value.+ let mut conn = ctx.get_non_persons_connection().await.unwrap();+ sqlx::query(+ "UPDATE posthog_personalapikey SET expires_at = NOW() - INTERVAL '1 minute' WHERE id = $1",+ )+ .bind(&pak_id)+ .execute(&mut *conn)+ .await+ .unwrap();+ // The cache key is the token's sha256 hash, the same hashing `hash_token_value` does.+ let token_hash = format!(+ "sha256${}",+ hex::encode(sha2::Sha256::digest(secure_value.as_bytes()))+ );+ let redis_client =+ feature_flags::utils::test_utils::setup_redis_client(Some(config.redis_url.clone())).await;+ redis_client+ .del(format!(+ "{}{token_hash}",+ feature_flags::api::auth::TOKEN_CACHE_PREFIX+ ))+ .await+ .expect("Failed to evict the auth token cache entry");++ let response = client+ .get(&url)+ .header("Authorization", format!("Bearer {secure_value}"))+ .send()+ .await+ .unwrap();+ assert_eq!(response.status(), 401, "An expired key is refused");++ cleanup_test_data(&ctx, pak_id, user_id).await;+}+#[tokio::test]async fn test_personal_api_key_mixed_scopes_team_valid_org_invalid() {let config = DEFAULT_TEST_CONFIG.clone();