: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(flags): resolve @current project for header-authed remote_config (#66703)
Patricio40e59a90ec8b
diff --git a/rust/feature-flags/src/api/auth.rs b/rust/feature-flags/src/api/auth.rsindex 1f3b7c89b8ae..d816c32d9405 100644--- a/rust/feature-flags/src/api/auth.rs+++ b/rust/feature-flags/src/api/auth.rs@@ -39,6 +39,11 @@ pub enum TokenAuthData {scoped_teams: Option<Vec<i32>>,scoped_orgs: Option<Vec<String>>,scopes: Option<Vec<String>>,+ /// The user's `current_team_id`, used only by remote_config's `@current` resolution.+ /// `#[serde(default)]` keeps backwards compatibility with cached entries that predate+ /// this field (they resolve as `None` until the entry refreshes).+ #[serde(default)]+ current_team_id: Option<i32>,},#[serde(rename = "project_secret")]ProjectSecret {@@ -233,6 +238,7 @@ async fn load_personal_key_from_pg(pak.scoped_teams,pak.scoped_organizations,u.id as user_id,+ u.current_team_id,ARRAY(SELECT om.organization_id::textFROM posthog_organizationmembership om@@ -257,6 +263,7 @@ async fn load_personal_key_from_pg(let scoped_organizations: Option<Vec<String>> = row.try_get("scoped_organizations")?;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")?;Ok(Some(TokenAuthData::Personal {user_id,@@ -265,6 +272,7 @@ async fn load_personal_key_from_pg(scoped_teams,scoped_orgs: scoped_organizations,scopes,+ current_team_id,}))}None => {@@ -274,6 +282,39 @@ async fn load_personal_key_from_pg(}}+/// Resolves the current team id for a personal API key's user — Django's `user.current_team`,+/// used only by the remote_config endpoint's `@current` project resolution. Goes through the+/// shared `auth_token_cache` (same loader as `validate_personal_api_key_with_scopes_for_team`),+/// so it does no uncached DB work before the request is authenticated and throttled, and the+/// subsequent `authenticate` call reuses the warm cache entry. Returns `Ok(None)` when the key is+/// valid but the user has no current team set (Django: 404), and `Err(PersonalApiKeyInvalid)`+/// (401) when the key is unknown or the user is inactive.+pub async fn current_team_id_for_personal_api_key(+ state: &AppState,+ key: &str,+) -> Result<Option<i32>, FlagError> {+ let sha256_hash = hash_token_value(key);+ let pg_reader: PostgresReader = state.database_pools.non_persons_reader.clone();+ let hash_for_loader = sha256_hash.clone();++ let result = state+ .auth_token_cache+ .get_or_load(&sha256_hash, |_key| async move {+ load_personal_key_from_pg(pg_reader, &hash_for_loader).await+ })+ .await?;++ match &result.value {+ Some(TokenAuthData::Personal {+ current_team_id, ..+ }) => Ok(*current_team_id),+ // Unknown key, inactive user, or a non-personal credential hashing to this value: an+ // invalid credential (-> 401), not a missing project. Matches+ // `validate_personal_api_key_with_scopes_for_team`'s not-found behaviour.+ Some(_) | None => Err(FlagError::PersonalApiKeyInvalid),+ }+}+/// Hash a token value using SHA256/// Ported from PostHog's `hash_key_value` function in `posthog/models/utils.py`/// Used by both PersonalAPIKey and ProjectSecretAPIKey@@ -542,6 +583,7 @@ mod tests {scoped_teams: Some(vec![1, 2]),scoped_orgs: None,scopes: Some(vec!["feature_flag:read".to_string()]),+ current_team_id: None,};let json = serde_json::to_string(&data).unwrap();assert!(json.contains("\"type\":\"personal\""));@@ -626,6 +668,7 @@ mod tests {scoped_teams: Some(vec![1, 2]),scoped_orgs: None,scopes: Some(vec!["feature_flag:read".to_string()]),+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -648,6 +691,7 @@ mod tests {scoped_teams: Some(vec![1, 2]),scoped_orgs: None,scopes: Some(vec!["feature_flag:read".to_string()]),+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -670,6 +714,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: None,+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -692,6 +737,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: None,+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -714,6 +760,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: Some(vec!["*".to_string()]),+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -736,6 +783,7 @@ mod tests {scoped_teams: None,scoped_orgs: Some(vec!["550e8400-e29b-41d4-a716-446655440000".to_string()]),scopes: None,+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -758,6 +806,7 @@ mod tests {scoped_teams: None,scoped_orgs: Some(vec!["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string()]),scopes: None,+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -780,6 +829,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: Some(vec!["session_recording:read".to_string()]),+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_err());@@ -840,6 +890,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: Some(vec!["feature_flag:write".to_string()]),+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -865,6 +916,7 @@ mod tests {"session_recording:read".to_string(),"feature_flag:read".to_string(),]),+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -889,6 +941,7 @@ mod tests {scoped_teams: Some(vec![]), // empty = no restriction, team 99 should passscoped_orgs: Some(vec![]), // empty = no restrictionscopes: None, // None = no restriction+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());@@ -913,6 +966,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: Some(vec![]),+ current_team_id: None,};assert!(matches!(@@ -936,6 +990,7 @@ mod tests {scoped_teams: None,scoped_orgs: None,scopes: None,+ current_team_id: None,};assert!(validate_personal_key_metadata(&data, &team).is_ok());diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rsindex 9a0c01e0a14d..b92cd0fb278c 100644--- a/rust/feature-flags/src/api/remote_config.rs+++ b/rust/feature-flags/src/api/remote_config.rs@@ -81,9 +81,8 @@ pub async fn remote_config(// `?api_key=` is an alias). SDKs call this with `@current` as the URL segment plus a// `?token=phc_...` project key; Django resolves the project from the token first, so the token// wins when present (and `@current` never needs interpreting). Without a token, a numeric- // segment is the project id; `@current` and other non-numeric values 404 (Django's `int()`- // ValueError), and the `@current`-without-token path that resolves the caller's current team- // is not an SDK call and is not ported.+ // segment is the project id, and `@current` resolves to the bearer credential's project (see+ // `resolve_current_team`); any other non-numeric segment 404s (Django's `int()` ValueError).let token_param = params.token.as_deref()@@ -94,7 +93,8 @@ pub async fn remote_config(// team. The project id is needed solely for the flag lookup, so it is computed after auth and// the throttle — no DB read happens before an unauthenticated caller is rejected.// `verify_token_and_get_team` is cache-backed, so the `?token=` path does no uncached DB work- // at this point either.+ // at this point either, and `resolve_current_team` goes through the shared auth-token cache so+ // the bearer-only `@current` path doesn't either.let (scope_team_id, resolved_team): (i32, Option<Team>) = if let Some(token) = token_param {match state.flag_service().verify_token_and_get_team(token).await {// Keep the team so the personal-key auth path and the project lookup below don't@@ -102,6 +102,16 @@ pub async fn remote_config(Ok(team) => (team.id, Some(team)),Err(_) => return Ok(StatusCode::UNAUTHORIZED.into_response()),}+ } else if project_segment == "@current" {+ // `@current` without a `?token=`: resolve the project from the bearer credential,+ // mirroring Django (`current_team = team_from_request or user.current_team`). Server+ // SDKs fetch remote config exactly this way — a `phs_`/`phx_` bearer, `@current`, no+ // query token — so this must resolve, not 404. `Ok(None)` is a valid credential with no+ // current team (Django: 404 "Project not found"); a missing credential surfaces as 401.+ match resolve_current_team(&state, &headers).await? {+ Some(team) => (team.id, Some(team)),+ None => return Ok(StatusCode::NOT_FOUND.into_response()),+ }} else {match project_segment.parse::<i32>() {Ok(id) => (id, None),@@ -325,6 +335,30 @@ async fn authenticate(Err(FlagError::NoAuthenticationProvided)}+/// Resolves the project scope for an `@current` request that has no `?token=`, from the bearer+/// credential — mirroring Django's `current_team = team_from_request or user.current_team`: a+/// team/project secret token (`phs_`) resolves its own team; a personal API key (`phx_`) resolves+/// its user's current team. `Ok(None)` means the credential is valid but has no current team+/// (Django: 404 "Project not found"); an absent or invalid credential surfaces as 401 via the+/// propagated error. The resolved team is re-validated by `authenticate`, so this only establishes scope.+async fn resolve_current_team(+ state: &AppState,+ headers: &HeaderMap,+) -> Result<Option<Team>, FlagError> {+ if let Some(token) = auth::extract_team_secret_token(headers) {+ let (team_id, _api_token, _is_project_secret) =+ auth::validate_secret_api_token(state, &token).await?;+ return Ok(Some(state.flag_service().get_team_by_id(team_id).await?));+ }+ if let Some(key) = auth::extract_personal_api_key(headers)? {+ return match auth::current_team_id_for_personal_api_key(state, &key).await? {+ Some(team_id) => Ok(Some(state.flag_service().get_team_by_id(team_id).await?)),+ None => Ok(None),+ };+ }+ Err(FlagError::NoAuthenticationProvided)+}+/// Resolves a team's `project_id`. Used on the `?token=` path only for cache entries that predate/// the cached `project_id`, where the flag is scoped to the token team's project, not its team id./// Returns `None` when no such team exists (stale cache: team deleted from Postgres). `project_id`diff --git a/rust/feature-flags/tests/test_remote_config.rs b/rust/feature-flags/tests/test_remote_config.rsindex ee7f400766dd..6b8e60b2fb3c 100644--- a/rust/feature-flags/tests/test_remote_config.rs+++ b/rust/feature-flags/tests/test_remote_config.rs@@ -552,7 +552,140 @@ async fn test_remote_config_at_current_with_token_resolves_project() {}#[tokio::test]-async fn test_remote_config_at_current_without_token_returns_404() {+async fn test_remote_config_at_current_secret_token_resolves_project() {+ // `@current` with no `?token=`, authenticated by a team secret token: the project resolves+ // from the credential's own team (Django: `team_from_request`). This server-SDK shape+ // previously 404'd before auth.+ let config = Config::default_test_config();+ let context = TestContext::new(Some(&config)).await;+ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ insert_rc_flag(+ &context,+ team.id,+ "rc-current-secret",+ "plain-payload",+ true,+ false,+ )+ .await;++ let server = common::ServerHandle::for_config(config.clone()).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/api/projects/@current/feature_flags/rc-current-secret/remote_config",+ server.addr+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 200);+ assert_eq!(+ response.json::<Value>().await.unwrap(),+ Value::String("plain-payload".to_string())+ );+}++#[tokio::test]+async fn test_remote_config_at_current_personal_key_resolves_current_team() {+ // `@current` with no `?token=`, authenticated by a personal API key: the project resolves+ // from the key user's current team (Django: `user.current_team`). This is how server SDKs+ // fetch remote config with a personal key, and it previously 404'd before auth.+ let config = Config::default_test_config();+ let context = TestContext::new(Some(&config)).await;+ let team = context.insert_new_team(None).await.unwrap();+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();+ let user_email = TestContext::generate_test_email("rc_current_pak");+ let user_id = context+ .create_user(&user_email, &org_id, team.id)+ .await+ .unwrap();+ context+ .add_user_to_organization(user_id, &org_id, 15)+ .await+ .unwrap();+ let (_pak_id, api_key) = context+ .create_personal_api_key(user_id, "RC Current", vec!["feature_flag:read"], None, None)+ .await+ .unwrap();+ insert_rc_flag(+ &context,+ team.id,+ "rc-current-pak",+ "plain-payload",+ true,+ false,+ )+ .await;++ let server = common::ServerHandle::for_config(config.clone()).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/api/projects/@current/feature_flags/rc-current-pak/remote_config",+ server.addr+ ))+ .header("Authorization", format!("Bearer {api_key}"))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 200);+ assert_eq!(+ response.json::<Value>().await.unwrap(),+ Value::String("plain-payload".to_string())+ );+}++#[tokio::test]+async fn test_remote_config_at_current_without_credentials_returns_401() {+ // `@current` with neither a `?token=` nor a bearer credential cannot resolve a project and is+ // unauthenticated (Django: AuthenticationFailed) — resolution must not leak as a 404.+ let config = Config::default_test_config();+ let _context = TestContext::new(Some(&config)).await;++ let server = common::ServerHandle::for_config(config.clone()).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/api/projects/@current/feature_flags/whatever/remote_config",+ server.addr+ ))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 401);+}++#[tokio::test]+async fn test_remote_config_at_current_invalid_personal_key_returns_401() {+ // `@current` with a personal-key-shaped bearer that doesn't exist must be 401 (invalid+ // credential), not 404: an unknown key can't resolve a project, but it's an auth failure+ // rather than a missing project, matching the numeric-id path and Django.+ let config = Config::default_test_config();+ let _context = TestContext::new(Some(&config)).await;++ let server = common::ServerHandle::for_config(config.clone()).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/api/projects/@current/feature_flags/whatever/remote_config",+ server.addr+ ))+ .header("Authorization", "Bearer phx_nonexistent_key")+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 401);+}++#[tokio::test]+async fn test_remote_config_at_current_resolves_then_404s_missing_flag() {+ // `@current` resolves the project from the credential, then a flag that doesn't exist (or+ // isn't a remote-config flag) still 404s — the resolution must not over-serve.let config = Config::default_test_config();let context = TestContext::new(Some(&config)).await;let (_team, secret_token, _) = context@@ -561,11 +694,9 @@ async fn test_remote_config_at_current_without_token_returns_404() {.unwrap();let server = common::ServerHandle::for_config(config.clone()).await;- // `@current` without a `?token=` needs the caller's current team (not an SDK path, not- // ported), and any other non-numeric segment is Django's int() ValueError -> 404.let response = reqwest::Client::new().get(format!(- "http://{}/api/projects/@current/feature_flags/x/remote_config",+ "http://{}/api/projects/@current/feature_flags/does-not-exist/remote_config",server.addr)).header("Authorization", format!("Bearer {secret_token}"))