: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): shadow check legacy token mirror rows (#116653)
Patricio026a156124ad
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.mdindex c79b78561829..df18e2704c34 100644--- a/docs/internal/feature-flags/rust-service-overview.md+++ b/docs/internal/feature-flags/rust-service-overview.md@@ -301,12 +301,13 @@ 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 |-| `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 |+| 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 |+| `LEGACY_TOKEN_MIRROR_SHADOW` | `true` | Transitional (PostHog/posthog#66179): after a successful legacy-token auth, a background query checks that the token's PSAK mirror row resolves to the same team, and emits `flags_legacy_token_mirror_shadow_total{result}`. A sustained zero `missing`/`team_mismatch` rate, with `match` nonzero, gates flipping `ACCEPT_TEAM_SECRET_TOKENS` off; `revoked` means leak revocation removed the row on purpose, so that token must not be backfilled. Runs only while legacy auth is on and only on auth-cache misses, with a hard concurrency cap (excess checks count as `skipped`) |+| `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 deb4d803ff60..777a43706111 100644--- a/rust/feature-flags/src/api/auth.rs+++ b/rust/feature-flags/src/api/auth.rs@@ -1,10 +1,14 @@use crate::{- api::errors::FlagError, database::get_connection_with_metrics, router::State as AppState,+ api::errors::FlagError, database::get_connection_with_metrics,+ metrics::consts::LEGACY_TOKEN_MIRROR_SHADOW_COUNTER, router::State as AppState,team::team_models::Team,};use axum::http::HeaderMap;use common_database::PostgresReader;+use metrics::counter;use serde::{Deserialize, Serialize};+use std::time::Duration;+use tokio::sync::Semaphore;use tracing::{debug, warn};/// Token prefix constants@@ -134,6 +138,8 @@ pub async fn validate_secret_api_token(let token_owned = token.to_string();let hash_for_loader = token_hash.clone();let accept_team_secret_tokens = *state.config.accept_team_secret_tokens;+ // The shadow only informs the flip, so it has nothing to compare once legacy is off.+ let mirror_shadow = accept_team_secret_tokens && *state.config.legacy_token_mirror_shadow;let result = state.auth_token_cache@@ -143,6 +149,7 @@ pub async fn validate_secret_api_token(&token_owned,&hash_for_loader,accept_team_secret_tokens,+ mirror_shadow,)}).await?;@@ -191,6 +198,7 @@ async fn load_token_from_pg(plaintext_token: &str,hashed_token: &str,accept_team_secret_tokens: bool,+ mirror_shadow: bool,) -> Result<Option<TokenAuthData>, FlagError> {use sqlx::Row;@@ -200,10 +208,17 @@ async fn load_token_from_pg(// to avoid doubling DB work during outages.match Team::from_pg_by_secret_token(pg_reader.clone(), plaintext_token).await {Ok(team) => {+ if mirror_shadow {+ drop(spawn_mirror_shadow_check(+ pg_reader.clone(),+ hashed_token.to_string(),+ team.id,+ ));+ }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),@@ -214,20 +229,17 @@ async fn load_token_from_pg(let mut conn =get_connection_with_metrics(&pg_reader, "non_persons_reader", "fetch_project_secret_key").await?;- let query = r#"+ let query = format!(+ r#"SELECT k.id, k.team_id, k.scopes, t.api_tokenFROM posthog_projectsecretapikey kJOIN posthog_team t ON t.id = k.team_idWHERE k.secure_value = $1- AND (- k.scopes IS NULL- OR '*' = ANY(k.scopes)- OR 'feature_flag:read' = ANY(k.scopes)- OR 'feature_flag:write' = ANY(k.scopes)- )- "#;+ AND {PSAK_FLAG_SCOPE_FILTER}+ "#+ );- match sqlx::query(query)+ match sqlx::query(&query).bind(hashed_token).fetch_optional(&mut *conn).await@@ -255,6 +267,145 @@ async fn load_token_from_pg(}}+/// Shared by the real PSAK lookup and the mirror shadow query so the predicates cannot+/// drift. The key table must be aliased as `k`.+const PSAK_FLAG_SCOPE_FILTER: &str = "(+ k.scopes IS NULL+ OR '*' = ANY(k.scopes)+ OR 'feature_flag:read' = ANY(k.scopes)+ OR 'feature_flag:write' = ANY(k.scopes)+ )";++// One in-flight check per pod: the definitions fleet's non_persons_reader pool is tiny,+// and when Redis degrades the loader runs per request. The flip gate reads the rates of+// missing and team_mismatch results, so skipping excess checks (counted as "skipped")+// loses nothing.+static MIRROR_SHADOW_PERMITS: Semaphore = Semaphore::const_new(1);++// Bounds only the query, not the pool checkout (acquire_timeout covers that):+// statement_timeout cannot unblock a client whose socket stopped responding.+const MIRROR_SHADOW_TIMEOUT: Duration = Duration::from_secs(5);++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum MirrorShadowResult {+ Match,+ Missing,+ TeamMismatch,+ Revoked,+ Error,+ Timeout,+}++impl MirrorShadowResult {+ const fn as_label(self) -> &'static str {+ match self {+ Self::Match => "match",+ Self::Missing => "missing",+ Self::TeamMismatch => "team_mismatch",+ Self::Revoked => "revoked",+ Self::Error => "error",+ Self::Timeout => "timeout",+ }+ }+}++/// Transitional (#66179): after a successful legacy-token auth, check in the background+/// that the PSAK lookup replacing the legacy branch post-flip resolves this token to the+/// same team. Fire-and-forget: it never delays or fails the auth path, and while the+/// auth cache is healthy it only runs on cache misses, so the extra query is bounded by+/// unique active tokens per cache TTL, not by request volume. Returns the task handle+/// (None when skipped) so tests can await the classification.+fn spawn_mirror_shadow_check(+ pg_reader: PostgresReader,+ hashed_token: String,+ team_id: i32,+) -> Option<tokio::task::JoinHandle<MirrorShadowResult>> {+ let Ok(permit) = MIRROR_SHADOW_PERMITS.try_acquire() else {+ counter!(LEGACY_TOKEN_MIRROR_SHADOW_COUNTER, "result" => "skipped").increment(1);+ return None;+ };+ Some(tokio::spawn(async move {+ let _permit = permit;+ let result = mirror_shadow_result(pg_reader, &hashed_token, team_id).await;+ match result {+ MirrorShadowResult::Match => {}+ // Quiet: leak revocation deleted the mirror row on purpose; do not backfill.+ MirrorShadowResult::Revoked => {}+ // Already logged with the error at the query site.+ MirrorShadowResult::Error | MirrorShadowResult::Timeout => {}+ MirrorShadowResult::Missing => warn!(+ team_id = team_id,+ "Legacy token has no usable PSAK mirror row"+ ),+ MirrorShadowResult::TeamMismatch => warn!(+ team_id = team_id,+ "Legacy token's PSAK mirror row belongs to another team"+ ),+ }+ counter!(LEGACY_TOKEN_MIRROR_SHADOW_COUNTER, "result" => result.as_label()).increment(1);+ result+ }))+}++/// Classify a legacy token's PSAK mirror state. Uses the same scope filter as the real+/// PSAK lookup in `load_token_from_pg`, so `Match` means the post-flip lookup would+/// authenticate this token hash for this team.+async fn mirror_shadow_result(+ pg_reader: PostgresReader,+ hashed_token: &str,+ team_id: i32,+) -> MirrorShadowResult {+ let mut conn = match get_connection_with_metrics(+ &pg_reader,+ "non_persons_reader",+ "legacy_token_mirror_shadow",+ )+ .await+ {+ Ok(conn) => conn,+ Err(e) => {+ warn!(team_id = team_id, error = %e, "Legacy token mirror shadow could not get a connection");+ return MirrorShadowResult::Error;+ }+ };+ let query = format!(+ r#"+ SELECT+ (SELECT k.team_id FROM posthog_projectsecretapikey k+ WHERE k.secure_value = $1 AND {PSAK_FLAG_SCOPE_FILTER}) AS team_id,+ EXISTS (+ SELECT 1 FROM posthog_revokedteamsecrettoken WHERE secure_value = $1+ ) AS revoked+ "#+ );+ match tokio::time::timeout(+ MIRROR_SHADOW_TIMEOUT,+ sqlx::query_as::<_, (Option<i32>, bool)>(&query)+ .bind(hashed_token)+ .fetch_one(&mut *conn),+ )+ .await+ {+ Ok(Ok((Some(row_team_id), _))) if row_team_id == team_id => MirrorShadowResult::Match,+ Ok(Ok((Some(_), _))) => MirrorShadowResult::TeamMismatch,+ Ok(Ok((None, true))) => MirrorShadowResult::Revoked,+ Ok(Ok((None, false))) => MirrorShadowResult::Missing,+ Ok(Err(e)) => {+ warn!(team_id = team_id, error = %e, "Legacy token mirror shadow query failed");+ MirrorShadowResult::Error+ }+ Err(_) => {+ // Return-to-pool pings with no deadline; closing frees the slot instead.+ conn.close_on_drop();+ warn!(+ team_id = team_id,+ "Legacy token mirror shadow query timed out"+ );+ MirrorShadowResult::Timeout+ }+ }+}+/// Load personal API key auth data from PostgreSQL.////// Extracted from `validate_personal_api_key_with_scopes_for_team` for consistency@@ -477,6 +628,126 @@ pub async fn validate_personal_api_key_with_scopes_for_team(mod tests {use super::*;+ /// The mirror shadow check (#66179) must classify a legacy token's PSAK mirror+ /// state the way the post-flip lookup would resolve it: same team with usable+ /// scopes is a match, a row for another team is the cross-team case, and no row+ /// (or a row without flag scopes) means the token dies at the flip. A leak-revoked+ /// hash is its own class: it must not read as a backfill candidate.+ #[rstest::rstest]+ #[case::mirror_row_same_team("same_team", MirrorShadowResult::Match)]+ #[case::mirror_row_other_team("other_team", MirrorShadowResult::TeamMismatch)]+ #[case::mirror_row_without_flag_scopes("wrong_scopes", MirrorShadowResult::Missing)]+ #[case::no_mirror_row("none", MirrorShadowResult::Missing)]+ #[case::leak_revoked("revoked", MirrorShadowResult::Revoked)]+ #[tokio::test]+ async fn test_mirror_shadow_result_classification(+ #[case] row: &str,+ #[case] expected: MirrorShadowResult,+ ) {+ use crate::utils::test_utils::TestContext;++ let context = TestContext::new(None).await;+ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ match row {+ "same_team" => {+ 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();+ }+ "other_team" => {+ let other_team = context.insert_new_team(None).await.unwrap();+ context+ .create_project_secret_api_key_with_value(+ other_team.id,+ "Migrated legacy secret API key",+ Some(vec!["feature_flag:read"]),+ &secret_token,+ )+ .await+ .unwrap();+ }+ "wrong_scopes" => {+ context+ .create_project_secret_api_key_with_value(+ team.id,+ "Migrated legacy secret API key",+ Some(vec!["support_ticket:read"]),+ &secret_token,+ )+ .await+ .unwrap();+ }+ "none" => {}+ "revoked" => {+ context+ .create_revoked_team_secret_token(team.id, &secret_token)+ .await+ .unwrap();+ }+ _ => unreachable!(),+ }++ let hashed = hash_token_value(&secret_token);+ let result =+ mirror_shadow_result(context.non_persons_reader.clone(), &hashed, team.id).await;+ assert_eq!(result, expected);+ }++ /// Guards the wiring, not the classification: if a refactor stopped the spawned+ /// shadow from running (or from reaching the classifier), the flip gate would read+ /// green by absence of data. The single global permit may be held by a concurrent+ /// test, so acquiring retries briefly.+ #[tokio::test]+ async fn test_spawn_mirror_shadow_check_classifies_in_background() {+ use crate::utils::test_utils::TestContext;++ let context = TestContext::new(None).await;+ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ let hashed = hash_token_value(&secret_token);++ let spawn_with_retry = |hashed: String, team_id: i32| {+ let pg_reader = context.non_persons_reader.clone();+ async move {+ for _ in 0..100 {+ if let Some(handle) =+ spawn_mirror_shadow_check(pg_reader.clone(), hashed.clone(), team_id)+ {+ return handle;+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ panic!("no mirror shadow permit became available");+ }+ };++ let handle = spawn_with_retry(hashed.clone(), team.id).await;+ assert_eq!(handle.await.unwrap(), MirrorShadowResult::Missing);++ context+ .create_project_secret_api_key_with_value(+ team.id,+ "Migrated legacy secret API key",+ Some(vec!["feature_flag:read"]),+ &secret_token,+ )+ .await+ .unwrap();+ let handle = spawn_with_retry(hashed, team.id).await;+ assert_eq!(handle.await.unwrap(), MirrorShadowResult::Match);+ }+#[test]fn test_extract_team_secret_token_from_header() {use axum::http::HeaderMap;@@ -1076,7 +1347,8 @@ 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", true).await;+ let result =+ load_token_from_pg(pg_reader, "phs_test_token", "sha256$fake", true, false).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 333071adfd88..4e8ded785fd3 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -960,6 +960,15 @@ pub struct Config {#[envconfig(from = "ACCEPT_TEAM_SECRET_TOKENS", default = "true")]pub accept_team_secret_tokens: FlexBool,+ // Transitional (#66179): after a successful legacy-token auth, verify in the+ // background that the PSAK mirror row resolves the same token to the same team.+ // Emits flags_legacy_token_mirror_shadow_total; a sustained zero rate of missing+ // and team_mismatch results is the evidence gate for flipping+ // ACCEPT_TEAM_SECRET_TOKENS off. Only runs while legacy auth is on, and only on+ // auth-cache misses.+ #[envconfig(from = "LEGACY_TOKEN_MIRROR_SHADOW", default = "true")]+ pub legacy_token_mirror_shadow: FlexBool,+#[envconfig(from = "SERVICE_MODE", default = "all")]pub service_mode: ServiceMode,@@ -1250,6 +1259,7 @@ impl Config {hypercache_read_repair_ttl_seconds: 600,skip_pg_team_fallback: FlexBool(false),accept_team_secret_tokens: FlexBool(true),+ legacy_token_mirror_shadow: FlexBool(true),service_mode: ServiceMode::All,auth_token_cache_ttl_seconds: 300,internal_request_token: None,diff --git a/rust/feature-flags/src/database/connection.rs b/rust/feature-flags/src/database/connection.rsindex 44830d0b61b4..cd19fb366d44 100644--- a/rust/feature-flags/src/database/connection.rs+++ b/rust/feature-flags/src/database/connection.rs@@ -28,6 +28,12 @@ impl TrackedConnection {labels,}}++ /// Close on drop instead of returning to the pool: sqlx's return-to-pool path pings+ /// with no deadline, so abandoning a stalled connection would hold the pool slot.+ pub fn close_on_drop(&mut self) {+ self.conn.close_on_drop();+ }}impl Deref for TrackedConnection {diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 33eaa7097cf1..643110201dc0 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -400,6 +400,11 @@ pub const FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER: &str =// Labels: method (secret_api_key, personal_api_key) — Rust only supports these two; Python also tracks oauth, jwt, session, otherpub const FLAG_DEFINITIONS_AUTH_COUNTER: &str = "flags_flag_definitions_auth_total";+// Transitional (#66179): background comparison of legacy-token auth against the+// backfilled PSAK mirror rows. Labels: result = match | missing | team_mismatch |+// revoked (leak-revoked, must stay without a row) | error | timeout | skipped (cap).+pub const LEGACY_TOKEN_MIRROR_SHADOW_COUNTER: &str = "flags_legacy_token_mirror_shadow_total";+// Counter for /flags requests classified as bot traffic. Fires regardless// of whether the request was actually short-circuited, so dashboards can// plot the "would-have-rejected" rate during the log-only rollout phasediff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex 12411c8aacc8..7eded8e114da 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -1852,6 +1852,25 @@ impl TestContext {Ok((key_id, raw_key))}+ /// Records a token hash as leak-revoked (`revoke_exposed_project_secret_api_key`).+ pub async fn create_revoked_team_secret_token(+ &self,+ team_id: i32,+ raw_key: &str,+ ) -> Result<(), Error> {+ let secure_value = crate::api::auth::hash_token_value(raw_key);+ let mut conn = self.non_persons_writer.get_connection().await?;+ sqlx::query(+ r#"INSERT INTO posthog_revokedteamsecrettoken (team_id, secure_value, created_at)+ VALUES ($1, $2, NOW())"#,+ )+ .bind(team_id)+ .bind(&secure_value)+ .execute(&mut *conn)+ .await?;+ Ok(())+ }+/// Creates a team with both public token and secret API token/// Optionally accepts a backup secret tokenpub async fn create_team_with_secret_token(