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): accept sdk identity from request body (#68988)

Manoel Aranda Neto58b4340fdec6
diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rs
index 8217f2fc21d6..e38707e066ab 100644
--- a/rust/feature-flags/src/api/endpoint.rs
+++ b/rust/feature-flags/src/api/endpoint.rs
@@ -377,9 +377,9 @@ pub async fn flags(
request_id,
ip: ip_string.clone(),
user_agent: user_agent.map(|s| s.to_string()),
- lib: ua_info.lib_for_logging(),
- // Browser SDK sends ver= query param, server SDKs send version in User-Agent
- lib_version: query_params.lib_version.clone().or(ua_info.sdk_version),
+ lib: ua_info.lib_for_logging().map(str::to_string),
+ // The decoded body can override this later. Until then, prefer SDK User-Agent over legacy query params.
+ lib_version: initial_lib_version(&ua_info, &query_params),
api_version: query_params.version.clone(),
queue_time_ms,
concurrency_limit_wait_ms,
@@ -579,6 +579,14 @@ pub async fn flags(
}
}
+fn initial_lib_version(ua_info: &UserAgentInfo, query_params: &FlagsQueryParams) -> Option<String> {
+ // Server SDKs report versions in User-Agent, while browser SDKs use the legacy query parameter.
+ ua_info
+ .sdk_version
+ .clone()
+ .or_else(|| query_params.lib_version.clone())
+}
+
fn create_request_span(
headers: &HeaderMap,
query_params: &FlagsQueryParams,
@@ -728,6 +736,34 @@ mod tests {
assert!(matches!(params.compression, Some(Compression::Unsupported)));
}
+ #[test]
+ fn test_initial_lib_version_prefers_user_agent_over_query_param() {
+ let query_params = FlagsQueryParams {
+ lib_version: Some("query-1.0".to_string()),
+ ..Default::default()
+ };
+ let ua_info = UserAgentInfo::parse(Some("posthog-node/2.0"));
+
+ assert_eq!(
+ initial_lib_version(&ua_info, &query_params).as_deref(),
+ Some("2.0")
+ );
+ }
+
+ #[test]
+ fn test_initial_lib_version_falls_back_to_query_param() {
+ let query_params = FlagsQueryParams {
+ lib_version: Some("query-1.0".to_string()),
+ ..Default::default()
+ };
+ let ua_info = UserAgentInfo::parse(Some("Mozilla/5.0"));
+
+ assert_eq!(
+ initial_lib_version(&ua_info, &query_params).as_deref(),
+ Some("query-1.0")
+ );
+ }
+
#[test]
fn test_default_params_logic() {
// Test the parameter modification logic that's applied in the flags endpoint
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 91e4d7161048..553ab2c669ed 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -1388,7 +1388,7 @@ impl FeatureFlagMatcher {
flag_key = %flag.key,
team_id = %flag.team_id,
condition_index = %index,
- lib = log.lib,
+ lib = log.lib.as_deref(),
lib_version = log.lib_version.as_deref(),
"Person condition uses device_id bucketing but no device_id provided, skipping"
);
diff --git a/rust/feature-flags/src/flags/flag_request.rs b/rust/feature-flags/src/flags/flag_request.rs
index c6c38d55476a..07be85aec7d5 100644
--- a/rust/feature-flags/src/flags/flag_request.rs
+++ b/rust/feature-flags/src/flags/flag_request.rs
@@ -13,6 +13,8 @@ use crate::handler::flags::EvaluationRuntime;
/// which use VARCHAR(200). The main persons tables allow up to 400 chars.
pub const MAX_DISTINCT_ID_LEN: usize = 200;
+const MAX_LIB_LEN: usize = 64;
+
fn deserialize_distinct_id<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
@@ -169,6 +171,25 @@ impl FlagRequest {
}
}
+ fn extract_person_property_string(&self, key: &str) -> Option<String> {
+ self.person_properties
+ .as_ref()
+ .and_then(|properties| properties.get(key))
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+ }
+
+ pub fn extract_lib(&self) -> Option<String> {
+ self.extract_person_property_string("$lib")
+ .map(|lib| lib.chars().take(MAX_LIB_LEN).collect())
+ }
+
+ pub fn extract_lib_version(&self) -> Option<String> {
+ self.extract_person_property_string("$lib_version")
+ .map(|version| version.chars().take(MAX_LIB_LEN).collect())
+ }
+
/// Extracts the token from the request.
/// If the token is missing or empty, an error is returned.
pub fn extract_token(&self) -> Result<String, FlagError> {
@@ -212,17 +233,10 @@ impl FlagRequest {
/// person_properties.$device_id for SDKs that only send it as a property.
pub fn extract_device_id(&self) -> Option<String> {
self.device_id
- .as_ref()
- .filter(|s| !s.is_empty())
- .cloned()
- .or_else(|| {
- self.person_properties
- .as_ref()
- .and_then(|props| props.get("$device_id"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string())
- })
+ .as_deref()
+ .filter(|device_id| !device_id.is_empty())
+ .map(str::to_string)
+ .or_else(|| self.extract_person_property_string("$device_id"))
}
/// Checks if feature flags should be disabled for this request.
@@ -241,7 +255,7 @@ mod tests {
use crate::api::errors::FlagError;
use crate::flags::flag_definitions_cache::FlagDefinitionsCache;
- use crate::flags::flag_request::{FlagRequest, MAX_DISTINCT_ID_LEN};
+ use crate::flags::flag_request::{FlagRequest, MAX_DISTINCT_ID_LEN, MAX_LIB_LEN};
use crate::flags::flag_service::FlagService;
use crate::utils::test_utils::{
insert_new_team_in_redis, setup_hypercache_reader, setup_pg_reader_client,
@@ -887,6 +901,53 @@ mod tests {
assert_eq!(props.get("age").unwrap(), &json!(25));
}
+ #[test]
+ fn test_sdk_info_is_extracted_from_person_properties() {
+ let flag_payload = FlagRequest::from_bytes(Bytes::from(
+ json!({
+ "distinct_id": "user123",
+ "token": "my_token1",
+ "person_properties": {
+ "$lib": "web",
+ "$lib_version": "1.2.3"
+ }
+ })
+ .to_string(),
+ ))
+ .expect("failed to parse request");
+
+ assert_eq!(flag_payload.extract_lib().as_deref(), Some("web"));
+ assert_eq!(flag_payload.extract_lib_version().as_deref(), Some("1.2.3"));
+ }
+
+ #[test]
+ fn test_sdk_info_is_truncated() {
+ let flag_payload = FlagRequest {
+ person_properties: Some(HashMap::from([
+ ("$lib".to_string(), json!("a".repeat(MAX_LIB_LEN + 1))),
+ (
+ "$lib_version".to_string(),
+ json!("🦔".repeat(MAX_LIB_LEN + 1)),
+ ),
+ ])),
+ ..Default::default()
+ };
+
+ let expected_lib = "a".repeat(MAX_LIB_LEN);
+ assert_eq!(
+ flag_payload.extract_lib().as_deref(),
+ Some(expected_lib.as_str())
+ );
+ assert_eq!(
+ flag_payload
+ .extract_lib_version()
+ .expect("expected lib version")
+ .chars()
+ .count(),
+ MAX_LIB_LEN
+ );
+ }
+
#[test]
fn test_group_properties_field_accepts_dollar_group_properties_for_backwards_compatibility() {
let json = json!({
diff --git a/rust/feature-flags/src/handler/authentication.rs b/rust/feature-flags/src/handler/authentication.rs
index 5d721cb04e55..4a2ee164b96c 100644
--- a/rust/feature-flags/src/handler/authentication.rs
+++ b/rust/feature-flags/src/handler/authentication.rs
@@ -1,28 +1,53 @@
+use std::sync::OnceLock;
+
use axum::http::HeaderMap;
+use bytes::Bytes;
use crate::{
- api::errors::FlagError,
+ api::{errors::FlagError, types::FlagsQueryParams},
flags::{flag_request::FlagRequest, flag_service::FlagService},
team::team_models::Team,
};
-use super::{decoding, types::RequestContext};
+use super::{
+ decoding,
+ types::{Library, RequestContext},
+};
-pub async fn parse_and_authenticate(
- context: &RequestContext,
- flag_service: &FlagService,
-) -> Result<(Option<String>, Team, FlagRequest), FlagError> {
- let (request, decoded_body) =
- decoding::decode_request(&context.headers, context.body.clone(), &context.meta)?;
+fn decode_and_stamp_request(
+ headers: &HeaderMap,
+ body: Bytes,
+ meta: &FlagsQueryParams,
+ decoded_body_for_logging: Option<&OnceLock<Bytes>>,
+ metrics_library: &mut Library,
+) -> Result<FlagRequest, FlagError> {
+ let (request, decoded_body) = decoding::decode_request(headers, body, meta)?;
// Hand the decoded body to the body-log side channel if one is installed.
// `set` is a no-op once filled, which can't happen here because each
// request has its own OnceLock — but this future-proofs against a
// hypothetical retry that calls `parse_and_authenticate` twice.
- if let Some(slot) = context.decoded_body_for_logging.as_ref() {
+ if let Some(slot) = decoded_body_for_logging {
slot.set(decoded_body).ok();
}
+ super::stamp_body_sdk_info(&request, metrics_library);
+
+ Ok(request)
+}
+
+pub async fn parse_and_authenticate(
+ context: &RequestContext,
+ flag_service: &FlagService,
+ metrics_library: &mut Library,
+) -> Result<(Option<String>, Team, FlagRequest), FlagError> {
+ let request = decode_and_stamp_request(
+ &context.headers,
+ context.body.clone(),
+ &context.meta,
+ context.decoded_body_for_logging.as_deref(),
+ metrics_library,
+ )?;
let token = request.extract_token()?;
let team = flag_service.verify_token_and_get_team(&token).await?;
@@ -36,6 +61,52 @@ pub async fn parse_and_authenticate(
Ok((distinct_id, team, request))
}
+#[cfg(test)]
+mod sdk_info_tests {
+ use serde_json::json;
+
+ use crate::handler::{run_with_canonical_log, FlagsCanonicalLogLine};
+
+ use super::*;
+
+ #[tokio::test]
+ async fn body_sdk_info_is_preserved_when_token_is_missing() {
+ let mut metrics_library = Library::PosthogNode;
+ let log = FlagsCanonicalLogLine {
+ lib: Some("posthog-node".to_string()),
+ lib_version: Some("fallback-1.0".to_string()),
+ ..Default::default()
+ };
+
+ let (result, final_log) = run_with_canonical_log(log, async {
+ let request = decode_and_stamp_request(
+ &HeaderMap::new(),
+ Bytes::from(
+ json!({
+ "distinct_id": "user123",
+ "person_properties": {
+ "$lib": "web",
+ "$lib_version": "body-1.0"
+ }
+ })
+ .to_string(),
+ ),
+ &FlagsQueryParams::default(),
+ None,
+ &mut metrics_library,
+ )?;
+
+ request.extract_token()
+ })
+ .await;
+
+ assert!(matches!(result, Err(FlagError::NoTokenError)));
+ assert_eq!(metrics_library, Library::PosthogJs);
+ assert_eq!(final_log.lib.as_deref(), Some("web"));
+ assert_eq!(final_log.lib_version.as_deref(), Some("body-1.0"));
+ }
+}
+
/// Checks if the request is an internal request.
/// Returns true if the Authorization header contains a Bearer token that matches
/// the configured internal_request_token.
diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rs
index 6e35d1884503..9f93799c9cb3 100644
--- a/rust/feature-flags/src/handler/canonical_log.rs
+++ b/rust/feature-flags/src/handler/canonical_log.rs
@@ -183,7 +183,7 @@ pub struct FlagsCanonicalLogLine {
// Request metadata (useful for SDK debugging)
pub user_agent: Option<String>,
- pub lib: Option<&'static str>,
+ pub lib: Option<String>,
pub lib_version: Option<String>,
pub api_version: Option<String>,
@@ -388,7 +388,7 @@ impl FlagsCanonicalLogLine {
anon_distinct_id = self.anon_distinct_id.as_deref(),
ip = %self.ip,
user_agent = user_agent,
- lib = self.lib,
+ lib = self.lib.as_deref(),
lib_version = self.lib_version.as_deref(),
api_version = self.api_version.as_deref(),
duration_ms = duration_ms,
@@ -708,7 +708,7 @@ mod tests {
fn test_emit_with_all_fields_populated() {
let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());
log.user_agent = Some("posthog-python/1.0.0".to_string());
- log.lib = Some("posthog-python");
+ log.lib = Some("posthog-python".to_string());
log.lib_version = Some("1.0.0".to_string());
log.api_version = Some("3".to_string());
log.team_id = Some(123);
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index f58f63be7607..4f833550d551 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -62,6 +62,29 @@ struct MetricsData {
evaluation_type: Option<EvaluationType>,
}
+fn stamp_body_sdk_info(
+ request: &crate::flags::flag_request::FlagRequest,
+ metrics_library: &mut Library,
+) {
+ let lib = request.extract_lib();
+ let lib_version = request.extract_lib_version();
+
+ if let Some(lib) = lib.as_deref() {
+ *metrics_library = Library::from_sdk_name(lib);
+ }
+
+ if lib.is_some() || lib_version.is_some() {
+ with_canonical_log(|log| {
+ if let Some(lib) = lib {
+ log.lib = Some(lib);
+ }
+ if let Some(lib_version) = lib_version {
+ log.lib_version = Some(lib_version);
+ }
+ });
+ }
+}
+
fn record_metrics(
result: &Result<FlagsResponse, FlagError>,
data: MetricsData,
@@ -139,7 +162,12 @@ async fn process_request_inner(
// log; histogram emission is deferred to `emit_phase_metrics`
// so the metric carries a `team_id` label.
let _phase = PhaseGuard::enter(Phase::Auth);
- authentication::parse_and_authenticate(&context, &flag_service).await?
+ authentication::parse_and_authenticate(
+ &context,
+ &flag_service,
+ &mut metrics_data.library,
+ )
+ .await?
};
let distinct_id_for_logging = original_distinct_id
@@ -321,6 +349,72 @@ fn apply_minimal_flag_called_events(response: &mut FlagsResponse, team: &Team) {
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod sdk_info_tests {
+ use crate::{flags::flag_request::FlagRequest, handler::Library};
+ use serde_json::json;
+
+ use super::{run_with_canonical_log, stamp_body_sdk_info, FlagsCanonicalLogLine};
+
+ #[tokio::test]
+ async fn body_sdk_info_overrides_existing_log_value() {
+ let request = FlagRequest::from_bytes(bytes::Bytes::from(
+ json!({
+ "token": "my_token1",
+ "distinct_id": "user123",
+ "person_properties": {
+ "$lib": "web",
+ "$lib_version": "body-1.0"
+ }
+ })
+ .to_string(),
+ ))
+ .expect("failed to parse request");
+ let log = FlagsCanonicalLogLine {
+ lib: Some("posthog-node".to_string()),
+ lib_version: Some("fallback-1.0".to_string()),
+ ..Default::default()
+ };
+
+ let mut metrics_library = Library::PosthogNode;
+ let (_, final_log) = run_with_canonical_log(log, async {
+ stamp_body_sdk_info(&request, &mut metrics_library);
+ })
+ .await;
+
+ assert_eq!(metrics_library, Library::PosthogJs);
+ assert_eq!(final_log.lib.as_deref(), Some("web"));
+ assert_eq!(final_log.lib_version.as_deref(), Some("body-1.0"));
+ }
+
+ #[tokio::test]
+ async fn missing_body_sdk_info_keeps_existing_log_value() {
+ let request = FlagRequest::from_bytes(bytes::Bytes::from(
+ json!({
+ "token": "my_token1",
+ "distinct_id": "user123"
+ })
+ .to_string(),
+ ))
+ .expect("failed to parse request");
+ let log = FlagsCanonicalLogLine {
+ lib: Some("web".to_string()),
+ lib_version: Some("fallback-1.0".to_string()),
+ ..Default::default()
+ };
+
+ let mut metrics_library = Library::PosthogJs;
+ let (_, final_log) = run_with_canonical_log(log, async {
+ stamp_body_sdk_info(&request, &mut metrics_library);
+ })
+ .await;
+
+ assert_eq!(metrics_library, Library::PosthogJs);
+ assert_eq!(final_log.lib.as_deref(), Some("web"));
+ assert_eq!(final_log.lib_version.as_deref(), Some("fallback-1.0"));
+ }
+}
+
#[cfg(test)]
mod test_metrics {
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index 7c15ecd9e2da..0d0346e60338 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -249,7 +249,12 @@ impl Library {
///
/// Uses `as_str()` as the source of truth to ensure consistency between
/// parsing and serialization.
- fn from_sdk_name(sdk_name: &str) -> Self {
+ pub(crate) fn from_sdk_name(sdk_name: &str) -> Self {
+ // posthog-js reports its library as "web" in request body properties.
+ if sdk_name == "web" {
+ return Library::PosthogJs;
+ }
+
// Check all known variants using as_str() as the source of truth
for lib in Self::ALL_KNOWN {
if lib.as_str() == sdk_name {
@@ -413,6 +418,11 @@ mod tests {
}
}
+ #[test]
+ fn test_from_sdk_name_maps_web_to_posthog_js() {
+ assert_eq!(Library::from_sdk_name("web"), Library::PosthogJs);
+ }
+
#[test]
fn test_from_sdk_name_unknown_returns_other() {
assert_eq!(Library::from_sdk_name("unknown-sdk"), Library::Other);