: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(flags): add legacy secret token kill switch (#116434)
Patricio439a6237f5c7
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.mdindex 44923f3d3a4d..afdfde40aef3 100644--- a/docs/internal/feature-flags/rust-service-overview.md+++ b/docs/internal/feature-flags/rust-service-overview.md@@ -299,11 +299,12 @@ Cache and query health are observable via the `flags_cohort_membership_cache_*`### Team lookup-| Variable | Default | Purpose |-| --------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `SKIP_PG_TEAM_FALLBACK` | `false` | When enabled, skip PostgreSQL fallback for team token lookups. HyperCache (Redis/S3) is treated as the source of truth — a cache miss means the token is invalid |-| `TEAM_NEGATIVE_CACHE_TTL_SECONDS` | `30` | TTL (seconds) for negative cache entries for invalid team tokens |-| `TEAM_NEGATIVE_CACHE_CAPACITY` | `10000` | Max entries in the negative cache for invalid team tokens |+| Variable | Default | Purpose |+| --------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `SKIP_PG_TEAM_FALLBACK` | `false` | When enabled, skip PostgreSQL fallback for team token lookups. HyperCache (Redis/S3) is treated as the source of truth — a cache miss means the token is invalid |+| `ACCEPT_TEAM_SECRET_TOKENS` | `true` | When `false`, `phs_` bearer tokens authenticate only through `ProjectSecretAPIKey` rows — the legacy `Team.secret_api_token` lookup is skipped (PostHog/posthog#66179). A token already in the auth cache keeps authenticating the way it did before a flip until its entry expires, up to `AUTH_TOKEN_CACHE_TTL_SECONDS` later |+| `TEAM_NEGATIVE_CACHE_TTL_SECONDS` | `30` | TTL (seconds) for negative cache entries for invalid team tokens |+| `TEAM_NEGATIVE_CACHE_CAPACITY` | `10000` | Max entries in the negative cache for invalid team tokens |When `SKIP_PG_TEAM_FALLBACK` is enabled, HyperCache misses return a token validation error instead of querying PostgreSQL. This eliminates database pressure from requests with invalid tokens. Transient errors (Redis/S3 timeouts) bypass the fallback entirely and are not negative-cached.diff --git a/rust/feature-flags/src/api/auth.rs b/rust/feature-flags/src/api/auth.rsindex f49f20a51c90..deb4d803ff60 100644--- a/rust/feature-flags/src/api/auth.rs+++ b/rust/feature-flags/src/api/auth.rs@@ -133,11 +133,17 @@ pub async fn validate_secret_api_token(let pg_reader: PostgresReader = state.database_pools.non_persons_reader.clone();let token_owned = token.to_string();let hash_for_loader = token_hash.clone();+ let accept_team_secret_tokens = *state.config.accept_team_secret_tokens;let result = state.auth_token_cache.get_or_load(&token_hash, |_key| {- load_token_from_pg(pg_reader, &token_owned, &hash_for_loader)+ load_token_from_pg(+ pg_reader,+ &token_owned,+ &hash_for_loader,+ accept_team_secret_tokens,+ )}).await?;@@ -175,28 +181,33 @@ pub async fn validate_secret_api_token(}}-/// Load token auth data from PostgreSQL, trying Team secret tokens first then ProjectSecretAPIKeys.+/// Load token auth data from PostgreSQL: posthog_team secret tokens first when+/// `accept_team_secret_tokens` is true (see `Config::accept_team_secret_tokens`), then+/// ProjectSecretAPIKeys.////// Extracted from `validate_secret_api_token_for_team` for testability.async fn load_token_from_pg(pg_reader: PostgresReader,plaintext_token: &str,hashed_token: &str,+ accept_team_secret_tokens: bool,) -> Result<Option<TokenAuthData>, FlagError> {use sqlx::Row;- // Try Team.secret_api_token / secret_api_token_backup first.- // Only fall through to PSAK on RowNotFound; propagate transient DB errors immediately- // to avoid doubling DB work during outages.- match Team::from_pg_by_secret_token(pg_reader.clone(), plaintext_token).await {- Ok(team) => {- return Ok(Some(TokenAuthData::Secret {- team_id: team.id,- api_token: Some(team.api_token),- }))+ if accept_team_secret_tokens {+ // Try Team.secret_api_token / secret_api_token_backup first.+ // Only fall through to PSAK on RowNotFound; propagate transient DB errors immediately+ // to avoid doubling DB work during outages.+ match Team::from_pg_by_secret_token(pg_reader.clone(), plaintext_token).await {+ Ok(team) => {+ return Ok(Some(TokenAuthData::Secret {+ team_id: team.id,+ api_token: Some(team.api_token),+ }))+ }+ Err(FlagError::RowNotFound) => { /* token not in posthog_team, try PSAK below */ }+ Err(e) => return Err(e),}- Err(FlagError::RowNotFound) => { /* token not in posthog_team, try PSAK below */ }- Err(e) => return Err(e),}// Try ProjectSecretAPIKey (JOIN with posthog_team to get api_token for HyperCache lookups)@@ -235,7 +246,10 @@ async fn load_token_from_pg(}))}None => {- warn!("phs_ token not found in team or project secret API key tables");+ warn!(+ checked_posthog_team = accept_team_secret_tokens,+ "phs_ token not found in project secret API key table"+ );Ok(None)}}@@ -1062,7 +1076,7 @@ mod tests {let client = Arc::new(FailingClient::new());let pg_reader: common_database::PostgresReader = client.clone();- let result = load_token_from_pg(pg_reader, "phs_test_token", "sha256$fake").await;+ let result = load_token_from_pg(pg_reader, "phs_test_token", "sha256$fake", true).await;// The first query (Team::from_pg_by_secret_token) should fail with DatabaseUnavailable.// The function should propagate that error immediately, NOT fall through to thediff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex 306e3edf70d6..333071adfd88 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -952,6 +952,14 @@ pub struct Config {#[envconfig(from = "SKIP_PG_TEAM_FALLBACK", default = "false")]pub skip_pg_team_fallback: FlexBool,+ // Kill switch for legacy Team.secret_api_token auth (PostHog/posthog#66179).+ // When false, phs_ bearer lookups skip posthog_team and validate against+ // ProjectSecretAPIKey only; migrated legacy tokens then match their backfilled+ // mirror rows. Cached legacy entries survive until AUTH_TOKEN_CACHE_TTL_SECONDS,+ // so a flip (either direction) settles within that window.+ #[envconfig(from = "ACCEPT_TEAM_SECRET_TOKENS", default = "true")]+ pub accept_team_secret_tokens: FlexBool,+#[envconfig(from = "SERVICE_MODE", default = "all")]pub service_mode: ServiceMode,@@ -1241,6 +1249,7 @@ impl Config {team_negative_cache_ttl_seconds: 30,hypercache_read_repair_ttl_seconds: 600,skip_pg_team_fallback: FlexBool(false),+ accept_team_secret_tokens: FlexBool(true),service_mode: ServiceMode::All,auth_token_cache_ttl_seconds: 300,internal_request_token: None,@@ -1414,6 +1423,10 @@ mod tests {// posture so a future env-var rename / refactor can't silently// flip it back to Enforced.assert_eq!(config.bot_filter_mode, BotFilterMode::LogOnly);+ // Legacy tokens must stay accepted by default: a default of false would 401+ // every legacy token without a mirror row while CI stays green, because the+ // integration tests build their config from default_test_config() instead.+ assert_eq!(config.accept_team_secret_tokens, FlexBool(true));}#[test]diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex 437f63c2b7cb..12411c8aacc8 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -1810,8 +1810,22 @@ impl TestContext {label: &str,scopes: Option<Vec<&str>>,) -> Result<(String, String), Error> {- let key_id = format!("test_psk_{}", &uuid::Uuid::new_v4().to_string()[..8]);let raw_key = format!("phs_{}", &uuid::Uuid::new_v4().to_string()[..12]);+ self.create_project_secret_api_key_with_value(team_id, label, scopes, &raw_key)+ .await+ }++ /// Same, but hashing a caller-provided token value — e.g. a mirror row holding a+ /// team's legacy secret token, as the backfill migration writes them.+ pub async fn create_project_secret_api_key_with_value(+ &self,+ team_id: i32,+ label: &str,+ scopes: Option<Vec<&str>>,+ raw_key: &str,+ ) -> Result<(String, String), Error> {+ let key_id = format!("test_psk_{}", &uuid::Uuid::new_v4().to_string()[..8]);+ let raw_key = raw_key.to_string();let secure_value = crate::api::auth::hash_token_value(&raw_key);let mask_value = format!("...{}", &raw_key[raw_key.len().saturating_sub(5)..]);diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rsindex c3c3a8fcb76f..5569cb3e666f 100644--- a/rust/feature-flags/tests/test_flag_definitions.rs+++ b/rust/feature-flags/tests/test_flag_definitions.rs@@ -435,6 +435,63 @@ async fn test_secret_api_token_authentication_invalid_token() {assert_eq!(body["attr"], Value::Null);}+/// ACCEPT_TEAM_SECRET_TOKENS=false (the legacy-removal kill switch, #66179): the+/// posthog_team lookup is skipped, so a legacy secret token only authenticates through a+/// backfilled PSAK mirror row holding the same string. The default (true) path is covered+/// by `test_secret_api_token_authentication_valid_token`.+#[rstest::rstest]+#[case::with_mirror_row(true, 200)]+#[case::without_mirror_row(false, 401)]+#[tokio::test]+async fn test_kill_switch_off_legacy_token_only_matches_mirror_row(+ #[case] mirror_row: bool,+ #[case] expected_status: u16,+) {+ use feature_flags::{+ config::{Config, FlexBool},+ utils::test_utils::TestContext,+ };+ use reqwest;++ let mut config = Config::default_test_config();+ config.accept_team_secret_tokens = FlexBool(false);+ let context = TestContext::new(Some(&config)).await;++ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ if mirror_row {+ context+ .create_project_secret_api_key_with_value(+ team.id,+ "Migrated legacy secret API key",+ Some(vec!["feature_flag:read", "support_ticket:read"]),+ &secret_token,+ )+ .await+ .unwrap();+ }+ context.populate_cache_for_team(team.id).await.unwrap();++ let server = common::ServerHandle::for_config(config.clone()).await;+ let client = reqwest::Client::new();++ let response = client+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ let status = response.status();+ let body_text = response.text().await.unwrap();+ assert_eq!(status, expected_status, "Response body: {body_text}");+}+/// Token param absent with a valid team-scoped secret — team is derived from the token.#[rstest::rstest]#[case::team_secret_token("secret")]