Skip to content

: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.

fix(flags): stamp last_used_at on project secret API keys (#94532)

Jovan Sakovic1126485eaefe
diff --git a/rust/feature-flags/src/api/api_key_usage.rs b/rust/feature-flags/src/api/api_key_usage.rs
new file mode 100644
index 000000000000..366bba16c257
--- /dev/null
+++ b/rust/feature-flags/src/api/api_key_usage.rs
@@ -0,0 +1,257 @@
+use common_database::Client as DatabaseClient;
+use common_redis::Client as RedisClient;
+use std::sync::Arc;
+use tracing::warn;
+
+pub const DEBOUNCE_TTL_SECONDS: u64 = 3600; // 1 hour, matching Django's debounce window
+
+/// Which API key model a `last_used_at` stamp targets. Personal and project secret keys live in
+/// different tables with different id spaces, so each kind gets its own debounce namespace.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ApiKeyKind {
+ Personal,
+ ProjectSecret,
+}
+
+impl ApiKeyKind {
+ fn table(self) -> &'static str {
+ match self {
+ ApiKeyKind::Personal => "posthog_personalapikey",
+ ApiKeyKind::ProjectSecret => "posthog_projectsecretapikey",
+ }
+ }
+
+ fn debounce_prefix(self) -> &'static str {
+ match self {
+ ApiKeyKind::Personal => "posthog:pak_last_used",
+ ApiKeyKind::ProjectSecret => "posthog:psak_last_used",
+ }
+ }
+}
+
+/// Returns the Redis debounce key for a given API key.
+pub fn debounce_key(kind: ApiKeyKind, key_id: &str) -> String {
+ format!("{}:{key_id}", kind.debounce_prefix())
+}
+
+/// Debounces and records an API key's last_used_at.
+///
+/// Uses Redis SET NX EX to gate updates to once per hour per key.
+/// When the debounce key is newly set, spawns a background task
+/// to update the database and returns its `JoinHandle`.
+pub async fn record_api_key_last_used(
+ redis: Arc<dyn RedisClient + Send + Sync>,
+ pg_writer: Arc<dyn DatabaseClient + Send + Sync>,
+ kind: ApiKeyKind,
+ key_id: String,
+) -> Option<tokio::task::JoinHandle<()>> {
+ let key = debounce_key(kind, &key_id);
+ match redis
+ .set_nx_ex(key, "1".to_string(), DEBOUNCE_TTL_SECONDS)
+ .await
+ {
+ Ok(true) => Some(tokio::spawn(async move {
+ update_api_key_last_used_at(pg_writer, kind, key_id).await;
+ })),
+ Ok(false) => None,
+ Err(e) => {
+ warn!(
+ error = %e,
+ ?kind,
+ "Redis debounce check failed for API key last_used_at"
+ );
+ None
+ }
+ }
+}
+
+/// Updates an API key's last_used_at in the database.
+///
+/// Includes a WHERE guard as a safety net matching Django's semantics.
+pub async fn update_api_key_last_used_at(
+ pg_writer: Arc<dyn DatabaseClient + Send + Sync>,
+ kind: ApiKeyKind,
+ key_id: String,
+) {
+ let mut conn = match pg_writer.get_connection().await {
+ Ok(conn) => conn,
+ Err(e) => {
+ warn!(key_id, ?kind, error = %e, "Failed to acquire connection for API key last_used_at update");
+ return;
+ }
+ };
+ // The table name comes from the enum, never from input.
+ let sql = format!(
+ "UPDATE {} SET last_used_at = NOW() \
+ WHERE id = $1 AND (last_used_at IS NULL OR last_used_at < NOW() - INTERVAL '1 hour')",
+ kind.table()
+ );
+ if let Err(e) = sqlx::query(&sql).bind(&key_id).execute(&mut *conn).await {
+ warn!(key_id, ?kind, error = %e, "Failed to update API key last_used_at");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::utils::test_utils::TestContext;
+ use common_redis::MockRedisClient;
+ use rstest::rstest;
+
+ async fn create_test_key(ctx: &TestContext, kind: ApiKeyKind) -> String {
+ let team = ctx.insert_new_team(None).await.unwrap();
+ match kind {
+ ApiKeyKind::Personal => {
+ let org_id = ctx.get_organization_id_for_team(&team).await.unwrap();
+ let email = TestContext::generate_test_email("pak_test");
+ let user_id = ctx.create_user(&email, &org_id, team.id).await.unwrap();
+ let (pak_id, _) = ctx
+ .create_personal_api_key(user_id, "test", vec!["feature_flag:read"], None, None)
+ .await
+ .unwrap();
+ pak_id
+ }
+ ApiKeyKind::ProjectSecret => {
+ let (key_id, _) = ctx
+ .create_project_secret_api_key(team.id, "test", Some(vec!["feature_flag:read"]))
+ .await
+ .unwrap();
+ key_id
+ }
+ }
+ }
+
+ async fn count_where(ctx: &TestContext, kind: ApiKeyKind, key_id: &str, cond: &str) -> i64 {
+ let mut conn = ctx.get_non_persons_connection().await.unwrap();
+ let sql = format!(
+ "SELECT COUNT(*) FROM {} WHERE id = $1 AND {cond}",
+ kind.table()
+ );
+ let count: (i64,) = sqlx::query_as(&sql)
+ .bind(key_id)
+ .fetch_one(&mut *conn)
+ .await
+ .unwrap();
+ count.0
+ }
+
+ #[rstest]
+ #[case::personal(ApiKeyKind::Personal)]
+ #[case::project_secret(ApiKeyKind::ProjectSecret)]
+ #[tokio::test]
+ async fn test_updates_last_used_at_for_new_key(#[case] kind: ApiKeyKind) {
+ let ctx = TestContext::new(None).await;
+ let key_id = create_test_key(&ctx, kind).await;
+
+ update_api_key_last_used_at(ctx.non_persons_writer.clone(), kind, key_id.clone()).await;
+
+ assert_eq!(
+ count_where(&ctx, kind, &key_id, "last_used_at IS NOT NULL").await,
+ 1,
+ "last_used_at should be set after update"
+ );
+ }
+
+ #[rstest]
+ #[case::personal(ApiKeyKind::Personal)]
+ #[case::project_secret(ApiKeyKind::ProjectSecret)]
+ #[tokio::test]
+ async fn test_skips_update_when_last_used_at_is_recent(#[case] kind: ApiKeyKind) {
+ let ctx = TestContext::new(None).await;
+ let key_id = create_test_key(&ctx, kind).await;
+
+ // Set last_used_at to 30 minutes ago (within the 1-hour window)
+ let mut conn = ctx.get_non_persons_connection().await.unwrap();
+ let sql = format!(
+ "UPDATE {} SET last_used_at = NOW() - INTERVAL '30 minutes' WHERE id = $1",
+ kind.table()
+ );
+ sqlx::query(&sql)
+ .bind(&key_id)
+ .execute(&mut *conn)
+ .await
+ .unwrap();
+
+ update_api_key_last_used_at(ctx.non_persons_writer.clone(), kind, key_id.clone()).await;
+
+ // Verify last_used_at is still ~30 minutes ago, not updated to NOW()
+ assert_eq!(
+ count_where(
+ &ctx,
+ kind,
+ &key_id,
+ "last_used_at < NOW() - INTERVAL '25 minutes'"
+ )
+ .await,
+ 1,
+ "last_used_at should not change when within the 1-hour window"
+ );
+ }
+
+ async fn assert_record_key(
+ kind: ApiKeyKind,
+ set_nx_ex_result: Result<bool, common_redis::CustomRedisError>,
+ expect_last_used_set: bool,
+ expect_handle: bool,
+ ) {
+ let ctx = TestContext::new(None).await;
+ let key_id = create_test_key(&ctx, kind).await;
+ let key = debounce_key(kind, &key_id);
+
+ let redis: Arc<dyn RedisClient + Send + Sync> =
+ Arc::new(MockRedisClient::new().set_nx_ex_ret(&key, set_nx_ex_result));
+
+ let handle =
+ record_api_key_last_used(redis, ctx.non_persons_writer.clone(), kind, key_id.clone())
+ .await;
+ assert_eq!(handle.is_some(), expect_handle);
+ if let Some(h) = handle {
+ h.await.unwrap();
+ }
+
+ let cond = if expect_last_used_set {
+ "last_used_at IS NOT NULL"
+ } else {
+ "last_used_at IS NULL"
+ };
+ assert_eq!(count_where(&ctx, kind, &key_id, cond).await, 1);
+ }
+
+ #[rstest]
+ #[case::personal(ApiKeyKind::Personal)]
+ #[case::project_secret(ApiKeyKind::ProjectSecret)]
+ #[tokio::test]
+ async fn test_record_last_used_writes_when_debounce_key_is_new(#[case] kind: ApiKeyKind) {
+ assert_record_key(kind, Ok(true), true, true).await;
+ }
+
+ #[rstest]
+ #[case::personal(ApiKeyKind::Personal)]
+ #[case::project_secret(ApiKeyKind::ProjectSecret)]
+ #[tokio::test]
+ async fn test_record_last_used_skips_write_when_debounce_key_exists(#[case] kind: ApiKeyKind) {
+ assert_record_key(kind, Ok(false), false, false).await;
+ }
+
+ #[rstest]
+ #[case::personal(ApiKeyKind::Personal)]
+ #[case::project_secret(ApiKeyKind::ProjectSecret)]
+ #[tokio::test]
+ async fn test_record_last_used_skips_write_on_redis_error(#[case] kind: ApiKeyKind) {
+ assert_record_key(
+ kind,
+ Err(common_redis::CustomRedisError::Timeout),
+ false,
+ false,
+ )
+ .await;
+ }
+
+ #[test]
+ fn test_debounce_keys_are_namespaced_per_kind() {
+ assert_ne!(
+ debounce_key(ApiKeyKind::Personal, "abc"),
+ debounce_key(ApiKeyKind::ProjectSecret, "abc")
+ );
+ }
+}
diff --git a/rust/feature-flags/src/api/auth.rs b/rust/feature-flags/src/api/auth.rs
index d816c32d9405..f49f20a51c90 100644
--- a/rust/feature-flags/src/api/auth.rs
+++ b/rust/feature-flags/src/api/auth.rs
@@ -56,6 +56,25 @@ pub enum TokenAuthData {
},
}
+/// A validated `phs_` bearer token. `project_secret_key_id` is set only when the token was a
+/// project secret API key; the team-level secret token has no key row to stamp usage on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SecretTokenAuth {
+ pub team_id: i32,
+ pub api_token: Option<String>,
+ pub project_secret_key_id: Option<String>,
+}
+
+impl SecretTokenAuth {
+ pub fn method_label(&self) -> &'static str {
+ if self.project_secret_key_id.is_some() {
+ "project_secret_api_key"
+ } else {
+ "secret_api_key"
+ }
+ }
+}
+
/// Extracts bearer token from Authorization header
pub fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {
headers
@@ -78,26 +97,18 @@ pub fn extract_personal_api_key(headers: &HeaderMap) -> Result<Option<String>, F
Ok(extract_bearer_token(headers).filter(|token| !token.starts_with(SECRET_TOKEN_PREFIX)))
}
-/// Validates a phs_-prefixed token against both Team secret tokens and ProjectSecretAPIKeys.
-///
-/// The unified loader tries Team.secret_api_token first, then posthog_projectsecretapikey.
-/// Both share the same cache key space (posthog:auth_token:{hash}), so a single loader
-/// prevents negative-cache poisoning when one source misses but the other would hit.
-///
-/// Returns the matched TokenAuthData variant on success for metric labeling.
/// Validates a phs_-prefixed token and checks it belongs to the expected team.
-/// Returns `(team_id, api_token, is_project_secret)` — same as
-/// `validate_secret_api_token` but with the team_id cross-check.
+/// Same as `validate_secret_api_token` but with the team_id cross-check.
pub async fn validate_secret_api_token_for_team(
state: &AppState,
token: &str,
expected_team_id: i32,
-) -> Result<(i32, Option<String>, bool), FlagError> {
+) -> Result<SecretTokenAuth, FlagError> {
let result = validate_secret_api_token(state, token).await?;
- if result.0 != expected_team_id {
+ if result.team_id != expected_team_id {
warn!(
- cached_team_id = result.0,
+ cached_team_id = result.team_id,
expected_team_id = expected_team_id,
"Token belongs to a different team"
);
@@ -110,14 +121,14 @@ pub async fn validate_secret_api_token_for_team(
/// Validates a phs_-prefixed token without checking against a specific team.
///
/// Used when the `?token=` query parameter is omitted and the team must be derived
-/// from the secret token itself. Returns `(team_id, api_token, is_project_secret)`.
+/// from the secret token itself.
///
/// Only works for Secret and ProjectSecret tokens (which are team-scoped).
/// Personal API keys are multi-team and cannot be used to derive a team.
pub async fn validate_secret_api_token(
state: &AppState,
token: &str,
-) -> Result<(i32, Option<String>, bool), FlagError> {
+) -> Result<SecretTokenAuth, FlagError> {
let token_hash = hash_token_value(token);
let pg_reader: PostgresReader = state.database_pools.non_persons_reader.clone();
let token_owned = token.to_string();
@@ -138,16 +149,27 @@ pub async fn validate_secret_api_token(
team_id = team_id,
"Secret API token validated (no token param)"
);
- Ok((team_id, api_token, false))
+ Ok(SecretTokenAuth {
+ team_id,
+ api_token,
+ project_secret_key_id: None,
+ })
}
Some(TokenAuthData::ProjectSecret {
- team_id, api_token, ..
+ team_id,
+ api_token,
+ key_id,
+ ..
}) => {
debug!(
team_id = team_id,
"Project secret API key validated (no token param)"
);
- Ok((team_id, api_token, true))
+ Ok(SecretTokenAuth {
+ team_id,
+ api_token,
+ project_secret_key_id: Some(key_id),
+ })
}
_ => Err(FlagError::SecretApiTokenInvalid),
}
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rs
index 8708afd72c5a..bb9d19546fab 100644
--- a/rust/feature-flags/src/api/flag_definitions.rs
+++ b/rust/feature-flags/src/api/flag_definitions.rs
@@ -1,3 +1,4 @@
+use crate::api::api_key_usage::ApiKeyKind;
use crate::{
api::{
auth,
@@ -370,26 +371,25 @@ async fn fetch_team_by_token(state: &AppState, token: &str) -> Result<Team, Flag
/// `?token=` param to disambiguate — returns an error in that case.
async fn resolve_team_from_auth(state: &AppState, headers: &HeaderMap) -> Result<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?;
-
- let method = if is_project_secret {
- "project_secret_api_key"
- } else {
- "secret_api_key"
- };
+ let secret = auth::validate_secret_api_token(state, &token).await?;
inc(
FLAG_DEFINITIONS_AUTH_COUNTER,
- &[("method".to_string(), method.to_string())],
+ &[("method".to_string(), secret.method_label().to_string())],
1,
);
+ // The team comes from the token itself, so the key is fully authenticated here. Stamp
+ // before the lookup so an infrastructure failure there does not leave it "never used".
+ state
+ .record_project_secret_key_usage(secret.project_secret_key_id)
+ .await;
+
// Prefer HyperCache via api_token (new cache entries include it).
// Fall back to PG for old cache entries that predate the field.
let svc = state.flag_service();
- return match api_token {
+ return match secret.api_token {
Some(t) => svc.verify_token_and_get_team(&t).await,
- None => svc.get_team_by_id(team_id).await,
+ None => svc.get_team_by_id(secret.team_id).await,
};
}
@@ -521,18 +521,15 @@ async fn authenticate_flag_definitions(
// Try team secret token or project secret API key (from Authorization header only)
// Both use phs_ prefix and share the same cache; the unified loader handles both.
if let Some(token) = auth::extract_team_secret_token(headers) {
- let (_, _, is_project_secret) =
- auth::validate_secret_api_token_for_team(state, &token, team.id).await?;
- let method = if is_project_secret {
- "project_secret_api_key"
- } else {
- "secret_api_key"
- };
+ let secret = auth::validate_secret_api_token_for_team(state, &token, team.id).await?;
inc(
FLAG_DEFINITIONS_AUTH_COUNTER,
- &[("method".to_string(), method.to_string())],
+ &[("method".to_string(), secret.method_label().to_string())],
1,
);
+ state
+ .record_project_secret_key_usage(secret.project_secret_key_id)
+ .await;
return Ok(());
}
@@ -547,7 +544,9 @@ async fn authenticate_flag_definitions(
);
// PAK last_used_at tracking is advisory; shared with remote_config via the State helper.
- state.record_pak_last_used(pak_id).await;
+ state
+ .record_api_key_last_used(ApiKeyKind::Personal, pak_id)
+ .await;
return Ok(());
}
diff --git a/rust/feature-flags/src/api/mod.rs b/rust/feature-flags/src/api/mod.rs
index 2a6d9ba9a741..d08445454b39 100644
--- a/rust/feature-flags/src/api/mod.rs
+++ b/rust/feature-flags/src/api/mod.rs
@@ -1,3 +1,4 @@
+pub mod api_key_usage;
pub mod auth;
pub mod batch_flag_evaluation;
pub mod body_read_metrics;
@@ -8,7 +9,6 @@ pub mod flag_definitions;
pub mod flag_definitions_rate_limiter;
pub mod flags_rate_limiter;
pub mod instance_setting;
-pub mod pak_usage;
pub mod rate_parser;
pub mod remote_config;
pub mod types;
diff --git a/rust/feature-flags/src/api/pak_usage.rs b/rust/feature-flags/src/api/pak_usage.rs
deleted file mode 100644
index 9eb222407f2b..000000000000
--- a/rust/feature-flags/src/api/pak_usage.rs
+++ /dev/null
@@ -1,183 +0,0 @@
-use common_database::Client as DatabaseClient;
-use common_redis::Client as RedisClient;
-use std::sync::Arc;
-use tracing::warn;
-
-pub const DEBOUNCE_TTL_SECONDS: u64 = 3600; // 1 hour, matching Django's debounce window
-
-/// Returns the Redis debounce key for a given PAK ID.
-pub fn debounce_key(pak_id: &str) -> String {
- format!("posthog:pak_last_used:{pak_id}")
-}
-
-/// Debounces and records PAK last_used_at.
-///
-/// Uses Redis SET NX EX to gate updates to once per hour per PAK.
-/// When the debounce key is newly set, spawns a background task
-/// to update the database and returns its `JoinHandle`.
-pub async fn record_pak_last_used(
- redis: Arc<dyn RedisClient + Send + Sync>,
- pg_writer: Arc<dyn DatabaseClient + Send + Sync>,
- pak_id: String,
-) -> Option<tokio::task::JoinHandle<()>> {
- let key = debounce_key(&pak_id);
- match redis
- .set_nx_ex(key, "1".to_string(), DEBOUNCE_TTL_SECONDS)
- .await
- {
- Ok(true) => Some(tokio::spawn(async move {
- update_pak_last_used_at(pg_writer, pak_id).await;
- })),
- Ok(false) => None,
- Err(e) => {
- warn!(
- error = %e,
- "Redis debounce check failed for PAK last_used_at"
- );
- None
- }
- }
-}
-
-/// Updates PAK last_used_at in the database.
-///
-/// Includes a WHERE guard as a safety net matching Django's semantics.
-pub async fn update_pak_last_used_at(
- pg_writer: Arc<dyn DatabaseClient + Send + Sync>,
- pak_id: String,
-) {
- let mut conn = match pg_writer.get_connection().await {
- Ok(conn) => conn,
- Err(e) => {
- warn!(pak_id, error = %e, "Failed to acquire connection for PAK last_used_at update");
- return;
- }
- };
- if let Err(e) = sqlx::query(
- "UPDATE posthog_personalapikey SET last_used_at = NOW() \
- WHERE id = $1 AND (last_used_at IS NULL OR last_used_at < NOW() - INTERVAL '1 hour')",
- )
- .bind(&pak_id)
- .execute(&mut *conn)
- .await
- {
- warn!(pak_id, error = %e, "Failed to update PAK last_used_at");
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::utils::test_utils::TestContext;
- use common_redis::MockRedisClient;
-
- async fn create_test_pak(ctx: &TestContext) -> String {
- let team = ctx.insert_new_team(None).await.unwrap();
- let org_id = ctx.get_organization_id_for_team(&team).await.unwrap();
- let email = TestContext::generate_test_email("pak_test");
- let user_id = ctx.create_user(&email, &org_id, team.id).await.unwrap();
- let (pak_id, _) = ctx
- .create_personal_api_key(user_id, "test", vec!["feature_flag:read"], None, None)
- .await
- .unwrap();
- pak_id
- }
-
- #[tokio::test]
- async fn test_updates_last_used_at_for_new_pak() {
- let ctx = TestContext::new(None).await;
- let pak_id = create_test_pak(&ctx).await;
-
- update_pak_last_used_at(ctx.non_persons_writer.clone(), pak_id.clone()).await;
-
- let mut conn = ctx.get_non_persons_connection().await.unwrap();
- let count: (i64,) = sqlx::query_as(
- "SELECT COUNT(*) FROM posthog_personalapikey WHERE id = $1 AND last_used_at IS NOT NULL",
- )
- .bind(&pak_id)
- .fetch_one(&mut *conn)
- .await
- .unwrap();
- assert_eq!(count.0, 1, "last_used_at should be set after update");
- }
-
- #[tokio::test]
- async fn test_skips_update_when_last_used_at_is_recent() {
- let ctx = TestContext::new(None).await;
- let pak_id = create_test_pak(&ctx).await;
-
- // Set last_used_at to 30 minutes ago (within the 1-hour window)
- let mut conn = ctx.get_non_persons_connection().await.unwrap();
- sqlx::query(
- "UPDATE posthog_personalapikey SET last_used_at = NOW() - INTERVAL '30 minutes' WHERE id = $1",
- )
- .bind(&pak_id)
- .execute(&mut *conn)
- .await
- .unwrap();
-
- update_pak_last_used_at(ctx.non_persons_writer.clone(), pak_id.clone()).await;
-
- // Verify last_used_at is still ~30 minutes ago, not updated to NOW()
- let mut conn = ctx.get_non_persons_connection().await.unwrap();
- let count: (i64,) = sqlx::query_as(
- "SELECT COUNT(*) FROM posthog_personalapikey \
- WHERE id = $1 AND last_used_at < NOW() - INTERVAL '25 minutes'",
- )
- .bind(&pak_id)
- .fetch_one(&mut *conn)
- .await
- .unwrap();
- assert_eq!(
- count.0, 1,
- "last_used_at should not change when within the 1-hour window"
- );
- }
-
- async fn assert_record_pak(
- set_nx_ex_result: Result<bool, common_redis::CustomRedisError>,
- expect_last_used_set: bool,
- expect_handle: bool,
- ) {
- let ctx = TestContext::new(None).await;
- let pak_id = create_test_pak(&ctx).await;
- let key = debounce_key(&pak_id);
-
- let redis: Arc<dyn RedisClient + Send + Sync> =
- Arc::new(MockRedisClient::new().set_nx_ex_ret(&key, set_nx_ex_result));
-
- let handle =
- record_pak_last_used(redis, ctx.non_persons_writer.clone(), pak_id.clone()).await;
- assert_eq!(handle.is_some(), expect_handle);
- if let Some(h) = handle {
- h.await.unwrap();
- }
-
- let mut conn = ctx.get_non_persons_connection().await.unwrap();
- let count: (i64,) = sqlx::query_as(if expect_last_used_set {
- "SELECT COUNT(*) FROM posthog_personalapikey WHERE id = $1 AND last_used_at IS NOT NULL"
- } else {
- "SELECT COUNT(*) FROM posthog_personalapikey WHERE id = $1 AND last_used_at IS NULL"
- })
- .bind(&pak_id)
- .fetch_one(&mut *conn)
- .await
- .unwrap();
- assert_eq!(count.0, 1);
- }
-
- #[tokio::test]
- async fn test_record_pak_last_used_writes_when_debounce_key_is_new() {
- assert_record_pak(Ok(true), true, true).await;
- }
-
- #[tokio::test]
- async fn test_record_pak_last_used_skips_write_when_debounce_key_exists() {
- assert_record_pak(Ok(false), false, false).await;
- }
-
- #[tokio::test]
- async fn test_record_pak_last_used_skips_write_on_redis_error() {
- assert_record_pak(Err(common_redis::CustomRedisError::Timeout), false, false).await;
- }
-}
diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rs
index e97042d368d8..5686887a20a3 100644
--- a/rust/feature-flags/src/api/remote_config.rs
+++ b/rust/feature-flags/src/api/remote_config.rs
@@ -30,6 +30,7 @@
//! request could replay the decrypted body to a secret-key caller without ever hitting
//! the etag check.
+use crate::api::api_key_usage::ApiKeyKind;
use crate::{
api::{auth, errors::FlagError, flag_definitions},
database::get_connection_with_metrics,
@@ -359,8 +360,8 @@ async fn authenticate(
headers: &HeaderMap,
) -> Result<AuthOutcome, 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?;
+ let secret = auth::validate_secret_api_token(state, &token).await?;
+ let team_id = secret.team_id;
// Django: authenticated_team.id == view.team.id.
if team_id != scope_team_id {
// Mismatch resolves like Django: 403 when a real (different) team owns the
@@ -378,16 +379,12 @@ async fn authenticate(
// because it decides redact-vs-decrypt, so the mix is worth watching during phase 2/3.
inc(
REMOTE_CONFIG_AUTH_COUNTER,
- &[(
- "method".to_string(),
- if is_project_secret {
- "project_secret_api_key".to_string()
- } else {
- "secret_api_key".to_string()
- },
- )],
+ &[("method".to_string(), secret.method_label().to_string())],
1,
);
+ state
+ .record_project_secret_key_usage(secret.project_secret_key_id)
+ .await;
// Secret-key requests are not throttled by Django's RemoteConfigThrottle.
return Ok(AuthOutcome::Authorized {
should_decrypt: false,
@@ -426,7 +423,9 @@ async fn authenticate(
// Track PAK usage so a key used only for remote config doesn't look dormant and get
// rotated as unused. Shared with flag_definitions via the State helper.
- state.record_pak_last_used(pak_id).await;
+ state
+ .record_api_key_last_used(ApiKeyKind::Personal, pak_id)
+ .await;
return Ok(AuthOutcome::Authorized {
should_decrypt: true,
@@ -449,8 +448,9 @@ async fn resolve_current_team(
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?;
+ let team_id = auth::validate_secret_api_token(state, &token)
+ .await?
+ .team_id;
return Ok(Some(state.flag_service().get_team_by_id(team_id).await?));
}
if let Some(key) = auth::extract_personal_api_key(headers)? {
diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rs
index 6752ad27ebf6..70e81480d2a6 100644
--- a/rust/feature-flags/src/router.rs
+++ b/rust/feature-flags/src/router.rs
@@ -1,3 +1,4 @@
+use crate::api::api_key_usage::ApiKeyKind;
use std::{
future::ready,
panic::{catch_unwind, AssertUnwindSafe},
@@ -149,19 +150,31 @@ impl State {
)
}
- /// Records personal-API-key usage (`last_used_at`), gated on `skip_writes`. Centralized so the
- /// personal-key auth paths (`flag_definitions`, `remote_config`) share one set of gating and
+ /// Records API key usage (`last_used_at`), gated on `skip_writes`. Centralized so the
+ /// API key auth paths (`flag_definitions`, `remote_config`) share one set of gating and
/// client choices instead of copying them per handler. Advisory: uses the shared Redis client
/// (not the flags cache) and the non-persons writer, and the DB write only fires when the
/// Redis debounce key is newly set.
- pub(crate) async fn record_pak_last_used(&self, pak_id: String) {
+ pub(crate) async fn record_api_key_last_used(&self, kind: ApiKeyKind, key_id: String) {
if *self.config.skip_writes {
return;
}
let redis = self.redis_client.clone();
let pg_writer: Arc<dyn common_database::Client + Send + Sync> =
self.database_pools.non_persons_writer.clone();
- drop(crate::api::pak_usage::record_pak_last_used(redis, pg_writer, pak_id).await);
+ drop(
+ crate::api::api_key_usage::record_api_key_last_used(redis, pg_writer, kind, key_id)
+ .await,
+ );
+ }
+
+ /// Stamps a project secret API key when the `phs_` token resolved to one. A team-level secret
+ /// token carries no key id, so it records nothing.
+ pub(crate) async fn record_project_secret_key_usage(&self, key_id: Option<String>) {
+ if let Some(key_id) = key_id {
+ self.record_api_key_last_used(ApiKeyKind::ProjectSecret, key_id)
+ .await;
+ }
}
}
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index 99fd717fd932..5f9a8b83b114 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -1625,7 +1625,7 @@ impl TestContext {
team_id: i32,
label: &str,
scopes: Option<Vec<&str>>,
- ) -> Result<String, Error> {
+ ) -> 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]);
@@ -1651,7 +1651,7 @@ impl TestContext {
.execute(&mut *conn)
.await?;
- Ok(raw_key)
+ Ok((key_id, raw_key))
}
/// Creates a team with both public token and secret API token
diff --git a/rust/feature-flags/tests/common/mod.rs b/rust/feature-flags/tests/common/mod.rs
index 3be33d78f1f1..dac41efe5c27 100644
--- a/rust/feature-flags/tests/common/mod.rs
+++ b/rust/feature-flags/tests/common/mod.rs
@@ -558,3 +558,27 @@ pub async fn poll_for_billing_counter_across_buckets(
"billing counter at {key} did not appear within 1s for buckets {first_bucket}..={last_bucket}"
);
}
+
+/// Poll until `last_used_at` is set for the given project secret API key, or panic after ~4s.
+#[allow(dead_code)]
+pub async fn poll_for_psak_last_used_at(
+ context: &feature_flags::utils::test_utils::TestContext,
+ key_id: &str,
+ message: &str,
+) {
+ let mut conn = context.get_non_persons_connection().await.unwrap();
+ for _ in 0..80 {
+ let count: (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) FROM posthog_projectsecretapikey WHERE id = $1 AND last_used_at IS NOT NULL",
+ )
+ .bind(key_id)
+ .fetch_one(&mut *conn)
+ .await
+ .unwrap();
+ if count.0 > 0 {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("{message}");
+}
diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rs
index ad9560420a31..eb38a055d564 100644
--- a/rust/feature-flags/tests/test_flag_definitions.rs
+++ b/rust/feature-flags/tests/test_flag_definitions.rs
@@ -457,7 +457,7 @@ async fn test_missing_token_param_success(#[case] auth_type: &str) {
}
"project_secret" => {
let team = context.insert_new_team(None).await.unwrap();
- let key = context
+ let (_, key) = context
.create_project_secret_api_key(team.id, "Test Key", Some(vec!["feature_flag:read"]))
.await
.unwrap();
@@ -1962,7 +1962,7 @@ async fn test_flag_definitions_project_secret_api_key(
other_team.id
};
- let raw_key = context
+ let (_, raw_key) = context
.create_project_secret_api_key(key_team_id, "Test Key", scopes)
.await
.unwrap();
@@ -1995,7 +1995,9 @@ async fn test_flag_definitions_project_secret_api_key(
#[tokio::test]
async fn test_valid_pak_used_to_authenticate_from_cache_updates_last_used_at() {
use feature_flags::{
- api::pak_usage::debounce_key, config::Config, utils::test_utils::TestContext,
+ api::api_key_usage::{debounce_key, ApiKeyKind},
+ config::Config,
+ utils::test_utils::TestContext,
};
use reqwest;
@@ -2057,7 +2059,7 @@ async fn test_valid_pak_used_to_authenticate_from_cache_updates_last_used_at() {
let redis_client =
feature_flags::utils::test_utils::setup_redis_client(Some(config.redis_url.clone())).await;
redis_client
- .del(debounce_key(&pak_id))
+ .del(debounce_key(ApiKeyKind::Personal, &pak_id))
.await
.expect("Failed to delete debounce key");
@@ -2070,7 +2072,7 @@ async fn test_valid_pak_used_to_authenticate_from_cache_updates_last_used_at() {
.unwrap();
// Second request: auth comes from the token cache (no DB query for auth),
- // but should still trigger the last_used_at update via record_pak_last_used
+ // but should still trigger the last_used_at update via record_api_key_last_used
let response = client
.get(&url)
.header("Authorization", format!("Bearer {api_key_value}"))
@@ -2088,6 +2090,50 @@ async fn test_valid_pak_used_to_authenticate_from_cache_updates_last_used_at() {
.await;
}
+#[rstest::rstest]
+#[case::with_token_param(true)]
+#[case::bearer_only(false)]
+#[tokio::test]
+async fn test_project_secret_api_key_updates_last_used_at(#[case] with_token_param: bool) {
+ use feature_flags::{config::Config, utils::test_utils::TestContext};
+ use reqwest;
+
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let (key_id, key) = context
+ .create_project_secret_api_key(team.id, "PSAK LastUsed", Some(vec!["feature_flag:read"]))
+ .await
+ .unwrap();
+ context.populate_cache_for_team(team.id).await.unwrap();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ server.wait_until_ready().await;
+ let url = if with_token_param {
+ format!(
+ "http://{}/flags/definitions?token={}",
+ server.addr, team.api_token
+ )
+ } else {
+ format!("http://{}/flags/definitions", server.addr)
+ };
+ let response = reqwest::Client::new()
+ .get(url)
+ .header("Authorization", format!("Bearer {key}"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), 200);
+
+ common::poll_for_psak_last_used_at(
+ &context,
+ &key_id,
+ "Timed out waiting for last_used_at to be set for the project secret API key",
+ )
+ .await;
+}
+
#[tokio::test]
async fn test_flag_definitions_with_legacy_secret_token_fallback() {
use feature_flags::{config::Config, utils::test_utils::TestContext};
diff --git a/rust/feature-flags/tests/test_remote_config.rs b/rust/feature-flags/tests/test_remote_config.rs
index 37687dd5f7e0..3846ca338978 100644
--- a/rust/feature-flags/tests/test_remote_config.rs
+++ b/rust/feature-flags/tests/test_remote_config.rs
@@ -1294,9 +1294,38 @@ async fn test_remote_config_personal_key_updates_last_used_at() {
.await;
}
+#[tokio::test]
+async fn test_remote_config_project_secret_key_updates_last_used_at() {
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let (psak_id, psak) = context
+ .create_project_secret_api_key(team.id, "RC PSAK LastUsed", Some(vec!["feature_flag:read"]))
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-psak-lastused", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-psak-lastused"))
+ .header("Authorization", format!("Bearer {psak}"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), 200);
+
+ common::poll_for_psak_last_used_at(
+ &context,
+ &psak_id,
+ "Timed out waiting for last_used_at to be set for the remote_config project secret key",
+ )
+ .await;
+}
+
#[tokio::test]
async fn test_remote_config_skip_writes_does_not_update_last_used_at() {
- // The shared State::record_pak_last_used helper must honor skip_writes: with it on, a
+ // The shared State::record_api_key_last_used helper must honor skip_writes: with it on, a
// personal-key request still authenticates (200) but records no last_used_at. Complements
// test_remote_config_personal_key_updates_last_used_at, which covers the write path.
let mut config = Config::default_test_config();
@@ -1489,7 +1518,7 @@ async fn test_remote_config_project_secret_api_key_encrypted_returns_redacted()
config.flags_secret_keys = K1.to_string();
let context = TestContext::new(Some(&config)).await;
let team = context.insert_new_team(None).await.unwrap();
- let psak = context
+ let (_, psak) = context
.create_project_secret_api_key(team.id, "RC PSAK", Some(vec!["feature_flag:read"]))
.await
.unwrap();