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.

feat(flags): block bots (#59254)

Matheus Batista633dc72f6a29
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 17a84fc75ea1..bf9afd290a3b 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3335,6 +3335,7 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
name = "feature-flags"
version = "0.1.0"
dependencies = [
+ "aho-corasick",
"anyhow",
"assert-json-diff",
"async-trait",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 395b07caeafd..c2a222b0b3ae 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -84,6 +84,7 @@ js-source-scopes = { git = "https://github.com/getsentry/js-source-scopes", rev
debug = "line-tables-only"
[workspace.dependencies]
+aho-corasick = "1.1"
anyhow = "1.0"
assert-json-diff = "2.0.2"
async-compression = { version = "0.4", features = [
diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.toml
index e8ee42960550..89d987f264df 100644
--- a/rust/feature-flags/Cargo.toml
+++ b/rust/feature-flags/Cargo.toml
@@ -7,6 +7,7 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+aho-corasick = { workspace = true }
anyhow = { workspace = true }
async-trait = { workspace = true }
aws-config = { workspace = true, optional = true }
diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rs
index 446e71fc5e32..052e1678ab3d 100644
--- a/rust/feature-flags/src/api/endpoint.rs
+++ b/rust/feature-flags/src/api/endpoint.rs
@@ -8,13 +8,16 @@ use crate::{
ConfigResponse, FlagsQueryParams, FlagsResponse, LegacyFlagsResponse, ServiceResponse,
},
},
+ config::BotFilterMode,
handler::{
decoding, process_request, run_with_canonical_log, with_canonical_log,
FlagsCanonicalLogLine, RequestContext,
},
- metrics::consts::{FLAG_RATE_LIMIT_CHECK_TIME_MS, FLAG_TOKEN_EXTRACT_TIME_MS},
+ metrics::consts::{
+ FLAG_BOT_DETECTED_COUNTER, FLAG_RATE_LIMIT_CHECK_TIME_MS, FLAG_TOKEN_EXTRACT_TIME_MS,
+ },
router,
- utils::user_agent::UserAgentInfo,
+ utils::{bot_detection, user_agent::UserAgentInfo},
};
// TODO: stream this instead
use axum::extract::{Extension, MatchedPath, Query, State};
@@ -103,16 +106,71 @@ fn rate_limit_error(error: FlagError) -> FlagError {
error
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum BotFilterOutcome {
+ /// No match, `Disabled` mode, or `LogOnly` classified — continue through
+ /// the normal pipeline.
+ Continue,
+ /// `Enforced` classified — short-circuit with the minimal flags envelope.
+ Reject,
+}
+
+/// Classify the request against the bot filter, stamp the canonical log,
+/// and bump `flags_bot_detected_total`. Side effects are scoped so a unit
+/// test can drive the function directly and inspect the log + recorded
+/// metric without spinning up the request pipeline.
+fn classify_and_stamp(
+ log: &mut FlagsCanonicalLogLine,
+ mode: &BotFilterMode,
+ user_agent: Option<&str>,
+ ip: IpAddr,
+) -> BotFilterOutcome {
+ if matches!(mode, BotFilterMode::Disabled) {
+ return BotFilterOutcome::Continue;
+ }
+ let Some((category, source)) = bot_detection::classify_request(user_agent, ip) else {
+ return BotFilterOutcome::Continue;
+ };
+ log.is_bot = true;
+ log.bot_category = Some(category);
+ log.bot_source = Some(source);
+
+ let mode_label = match mode {
+ BotFilterMode::LogOnly => "log_only",
+ BotFilterMode::Enforced => "enforced",
+ BotFilterMode::Disabled => unreachable!("guarded above"),
+ };
+ common_metrics::inc(
+ FLAG_BOT_DETECTED_COUNTER,
+ &[
+ ("bot_category".to_string(), category.as_str().to_string()),
+ ("bot_source".to_string(), source.as_str().to_string()),
+ ("mode".to_string(), mode_label.to_string()),
+ ],
+ 1,
+ );
+
+ match mode {
+ BotFilterMode::Enforced => BotFilterOutcome::Reject,
+ BotFilterMode::LogOnly => BotFilterOutcome::Continue,
+ BotFilterMode::Disabled => unreachable!("guarded above"),
+ }
+}
+
+/// Empty-flags + minimal-config response shared by the GET and bot-reject
+/// paths. The envelope is selected by [`get_versioned_response`] so the
+/// `is_from_legacy_decide × version` matrix lives in one place.
fn get_minimal_flags_response(
headers: &HeaderMap,
version: Option<&str>,
-) -> Result<Json<ServiceResponse>, FlagError> {
+ is_from_legacy_decide: bool,
+) -> Json<ServiceResponse> {
let request_id = extract_request_id(headers);
- // Parse version string to determine response format
- let version_num = version.map(|v| v.parse::<i32>().unwrap_or(1)).unwrap_or(1);
+ // `None` is preserved so `get_versioned_response` can apply its
+ // decide/non-decide defaults.
+ let version_num = version.map(|v| v.parse::<i32>().unwrap_or(1));
- // Create minimal config response
let mut config = ConfigResponse::new();
config.set(
"supportedCompression",
@@ -126,18 +184,13 @@ fn get_minimal_flags_response(
config.set("isAuthenticated", serde_json::json!(false));
config.set("sessionRecording", serde_json::json!(false));
- // Create empty flags response with minimal config
let mut response = FlagsResponse::new(false, HashMap::new(), None, request_id);
response.config = config;
- // Return versioned response
- let service_response = if version_num >= 2 {
- ServiceResponse::V2(response)
- } else {
- ServiceResponse::Default(LegacyFlagsResponse::from_response(response))
- };
-
- Ok(Json(service_response))
+ let (service_response, _) =
+ get_versioned_response(is_from_legacy_decide, version_num, response)
+ .expect("get_versioned_response is total for any (bool, Option<i32>, FlagsResponse)");
+ Json(service_response)
}
/// Determines the response format based on whether the request came from decide and the version parameter.
@@ -154,11 +207,11 @@ fn get_minimal_flags_response(
///
/// Returns a tuple of (response, format_name) for logging purposes
fn get_versioned_response(
- is_from_decide: bool,
+ is_from_legacy_decide: bool,
version: Option<i32>,
response: FlagsResponse,
) -> Result<(ServiceResponse, &'static str), FlagError> {
- if is_from_decide {
+ if is_from_legacy_decide {
match version {
Some(1) | None => Ok((
ServiceResponse::DecideV1(crate::api::types::DecideV1Response::from_response(
@@ -228,11 +281,14 @@ pub async fn flags(
// Handle different HTTP methods (these don't need canonical logging)
match method {
Method::GET => {
- // GET requests return minimal flags response
- return Ok(
- get_minimal_flags_response(&headers, query_params.version.as_deref())?
- .into_response(),
- );
+ // The decide proxy forwards POSTs only, so GETs are always
+ // direct hits (`is_from_legacy_decide = false`).
+ return Ok(get_minimal_flags_response(
+ &headers,
+ query_params.version.as_deref(),
+ false,
+ )
+ .into_response());
}
Method::POST => {
// POST requests continue with full processing logic below
@@ -270,11 +326,10 @@ pub async fn flags(
// Convert IP to string once and reuse throughout the request
let ip_string = ip.to_string();
- // Anchor for `flags_pre_handler_time_ms` — placed before UA parse so
- // that synchronous pre-handler work (UA parse → token rate-limit) is
- // included end-to-end, matching the metric's documented scope. The
- // actual emission happens inside the canonical-log scope so the metric
- // carries a `team_id` label once it's resolved.
+ // Anchor for `flags_pre_handler_time_ms`. Covers all synchronous
+ // pre-handler work (UA parse → IP rate-limit → bot check → token
+ // rate-limit). The histogram is emitted from inside the canonical-log
+ // scope once `team_id` is resolved.
let pre_handler_start = std::time::Instant::now();
// Parse User-Agent and extract SDK info for logging
@@ -305,9 +360,19 @@ pub async fn flags(
// surface.
let body_read_ms = body_read_duration.map(|Extension(d)| d.0.as_secs_f64() * 1000.0);
- // Initialize canonical log with all upfront request metadata.
- // Fields discovered during processing (team_id, flags_evaluated, etc.) are set via with_canonical_log().
- let canonical_log = FlagsCanonicalLogLine {
+ // Needed by both the bot short-circuit and the normal-path response
+ // for envelope selection (Decide vs Flags shape).
+ let is_from_legacy_decide = headers
+ .get("X-Original-Endpoint")
+ .and_then(|v| v.to_str().ok())
+ .map(|v| v == "decide")
+ .unwrap_or(false);
+
+ // Mutable: the IP rate-limit and bot branches below mark fields on
+ // it directly because they run outside the canonical-log scope.
+ // Fields resolved inside `run_with_canonical_log` go through
+ // `with_canonical_log()`.
+ let mut canonical_log = FlagsCanonicalLogLine {
request_id,
ip: ip_string.clone(),
user_agent: user_agent.map(|s| s.to_string()),
@@ -321,16 +386,53 @@ pub async fn flags(
..Default::default()
};
- // Check if this request came through the decide proxy
- let is_from_decide = headers
- .get("X-Original-Endpoint")
- .and_then(|v| v.to_str().ok())
- .map(|v| v == "decide")
- .unwrap_or(false);
+ // Runs before the bot check: UA matching is public and trivially
+ // forgeable, so a spoofed Googlebot UA must still hit the per-IP
+ // limiter. Mutates `canonical_log` directly since the task-local
+ // scope has not been entered.
+ let ip_rl_result = {
+ let _t = common_metrics::timing_guard_high_precision(FLAG_RATE_LIMIT_CHECK_TIME_MS, &[])
+ .label("kind", "ip");
+ state.ip_rate_limiter.allow_request(&ip_string)
+ };
+ match ip_rl_result {
+ RateLimitResult::Blocked => {
+ let err = FlagError::ClientFacing(ClientFacingError::IpRateLimited);
+ canonical_log.rate_limited = true;
+ canonical_log.set_error(&err);
+ // queue_time/body_read histograms emit with team_id="unknown".
+ canonical_log.emit_short_circuit();
+ return Err(err);
+ }
+ RateLimitResult::Warned => canonical_log.rate_limit_warned = true,
+ RateLimitResult::Allowed => {}
+ }
+
+ // Runs after IP rate-limit (so spoofed UAs are still throttled) but
+ // before token rate-limit, auth, billing, and evaluation. LogOnly
+ // stamps the canonical log and falls through; Enforced short-circuits.
+ let bot_outcome = classify_and_stamp(
+ &mut canonical_log,
+ &state.config.bot_filter_mode,
+ user_agent,
+ ip,
+ );
+ if bot_outcome == BotFilterOutcome::Reject {
+ // `rate_limit_warned` stays on the canonical log but is not
+ // surfaced as `X-PostHog-Rate-Limit-Warning`: bots do not read
+ // response headers.
+ canonical_log.emit_short_circuit();
+ return Ok(get_minimal_flags_response(
+ &headers,
+ query_params.version.as_deref(),
+ is_from_legacy_decide,
+ )
+ .into_response());
+ }
// Modify query params to enable config for decide requests
let mut modified_query_params = query_params.clone();
- if is_from_decide && modified_query_params.config.is_none() {
+ if is_from_legacy_decide && modified_query_params.config.is_none() {
modified_query_params.config = Some(true);
}
@@ -368,38 +470,13 @@ pub async fn flags(
// Run the request within a canonical log scope.
// All code within can use with_canonical_log() to update the log.
+ //
+ // Only the token-based rate limit runs here: it needs the parsed JSON
+ // body, so it lives next to `process_request`. The IP-based limit
+ // runs above, before the bot check, so a spoofed bot UA cannot
+ // bypass it.
let (result, mut log) = run_with_canonical_log(canonical_log, async {
- // Rate limiting strategy (order matters for security):
- // 1. IP-based rate limiting first - prevents DDoS with rotating tokens
- // 2. Token-based rate limiting second - enforces per-project limits
- //
- // This order ensures that an attacker cannot bypass rate limiting by
- // simply rotating through fake tokens from the same IP address.
-
- let mut rate_limit_warned = false;
-
- // Check IP-based rate limit first.
- // Time the governor `allow_request` call (sharded DashMap + sync
- // mutex) — Mutex contention on a hot token is a known source of
- // pre-handler latency spikes. Guard records on drop, before the
- // match arm runs.
- let ip_rl_result = {
- let _t =
- common_metrics::timing_guard_high_precision(FLAG_RATE_LIMIT_CHECK_TIME_MS, &[])
- .label("kind", "ip");
- state.ip_rate_limiter.allow_request(&ip_string)
- };
- match ip_rl_result {
- RateLimitResult::Blocked => {
- return Err(rate_limit_error(FlagError::ClientFacing(
- ClientFacingError::IpRateLimited,
- )));
- }
- RateLimitResult::Warned => rate_limit_warned = true,
- RateLimitResult::Allowed => {}
- }
-
- // Check token-based rate limit
+ // Check token-based rate limit.
// Extract token from body, use IP as fallback if extraction fails.
// Time the JSON DOM scan separately — pathological large bodies
// are the suspected outlier driver here.
@@ -420,14 +497,11 @@ pub async fn flags(
ClientFacingError::TokenRateLimited,
)));
}
- RateLimitResult::Warned => rate_limit_warned = true,
+ // OR-combines with any IP warn already on the canonical log.
+ RateLimitResult::Warned => with_canonical_log(|l| l.rate_limit_warned = true),
RateLimitResult::Allowed => {}
}
- if rate_limit_warned {
- with_canonical_log(|l| l.rate_limit_warned = true);
- }
-
// Stamp pre-handler duration into the canonical log just before we
// hand off to async processing. `Instant::now()` is monotonic, so
// this is robust to wall-clock jumps. Emission of the histogram is
@@ -453,7 +527,7 @@ pub async fn flags(
match result {
Ok(response) => {
// Determine the response format based on whether request is from decide and version
- match get_versioned_response(is_from_decide, query_version, response) {
+ match get_versioned_response(is_from_legacy_decide, query_version, response) {
Ok((versioned_response, _response_format)) => {
log.http_status = 200;
log.emit();
@@ -835,4 +909,163 @@ mod tests {
fn test_parse_request_start_ms(#[case] input: &str, #[case] expected: Option<i64>) {
assert_eq!(parse_request_start_ms(input), expected);
}
+
+ mod bot_filter_tests {
+ use super::*;
+ use crate::utils::bot_detection::{BotCategory, BotSource};
+ use metrics_util::debugging::DebuggingRecorder;
+ use std::net::Ipv4Addr;
+
+ const GOOGLEBOT_UA: &str =
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
+ const GOOGLEBOT_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(66, 249, 79, 123));
+ const BENIGN_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8));
+ const BENIGN_UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X) Chrome/120 Safari/537.36";
+
+ fn fresh_log() -> FlagsCanonicalLogLine {
+ FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string())
+ }
+
+ /// True iff `FLAG_BOT_DETECTED_COUNTER` was emitted with all three
+ /// labels matching.
+ fn counter_labels_match(
+ recorder: &DebuggingRecorder,
+ mode: &str,
+ category: &str,
+ source: &str,
+ ) -> bool {
+ recorder
+ .snapshotter()
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .any(|(ckey, _, _, _)| {
+ let key = ckey.key();
+ if key.name() != FLAG_BOT_DETECTED_COUNTER {
+ return false;
+ }
+ let pairs: Vec<(String, String)> = key
+ .labels()
+ .map(|l| (l.key().to_string(), l.value().to_string()))
+ .collect();
+ pairs.iter().any(|(k, v)| k == "mode" && v == mode)
+ && pairs
+ .iter()
+ .any(|(k, v)| k == "bot_category" && v == category)
+ && pairs.iter().any(|(k, v)| k == "bot_source" && v == source)
+ })
+ }
+
+ fn any_bot_counter_emitted(recorder: &DebuggingRecorder) -> bool {
+ recorder
+ .snapshotter()
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .any(|(ckey, _, _, _)| ckey.key().name() == FLAG_BOT_DETECTED_COUNTER)
+ }
+
+ #[test]
+ fn disabled_mode_does_not_stamp_or_count() {
+ let recorder = DebuggingRecorder::new();
+ let mut log = fresh_log();
+ let outcome = metrics::with_local_recorder(&recorder, || {
+ classify_and_stamp(
+ &mut log,
+ &BotFilterMode::Disabled,
+ Some(GOOGLEBOT_UA),
+ GOOGLEBOT_IP,
+ )
+ });
+ assert_eq!(outcome, BotFilterOutcome::Continue);
+ assert!(!log.is_bot);
+ assert_eq!(log.bot_category, None);
+ assert_eq!(log.bot_source, None);
+ assert!(!any_bot_counter_emitted(&recorder));
+ }
+
+ #[test]
+ fn no_match_continues_without_stamping() {
+ let recorder = DebuggingRecorder::new();
+ let mut log = fresh_log();
+ let outcome = metrics::with_local_recorder(&recorder, || {
+ classify_and_stamp(
+ &mut log,
+ &BotFilterMode::Enforced,
+ Some(BENIGN_UA),
+ BENIGN_IP,
+ )
+ });
+ assert_eq!(outcome, BotFilterOutcome::Continue);
+ assert!(!log.is_bot);
+ assert!(!any_bot_counter_emitted(&recorder));
+ }
+
+ #[test]
+ fn log_only_ua_match_continues_and_records_observability() {
+ let recorder = DebuggingRecorder::new();
+ let mut log = fresh_log();
+ let outcome = metrics::with_local_recorder(&recorder, || {
+ classify_and_stamp(
+ &mut log,
+ &BotFilterMode::LogOnly,
+ Some(GOOGLEBOT_UA),
+ BENIGN_IP,
+ )
+ });
+ assert_eq!(outcome, BotFilterOutcome::Continue);
+ assert!(log.is_bot);
+ assert_eq!(log.bot_category, Some(BotCategory::Google));
+ assert_eq!(log.bot_source, Some(BotSource::UserAgent));
+ assert!(counter_labels_match(
+ &recorder,
+ "log_only",
+ "google",
+ "user_agent"
+ ));
+ }
+
+ #[test]
+ fn log_only_ip_match_stamps_with_ip_source() {
+ let recorder = DebuggingRecorder::new();
+ let mut log = fresh_log();
+ let outcome = metrics::with_local_recorder(&recorder, || {
+ classify_and_stamp(
+ &mut log,
+ &BotFilterMode::LogOnly,
+ Some(BENIGN_UA),
+ GOOGLEBOT_IP,
+ )
+ });
+ assert_eq!(outcome, BotFilterOutcome::Continue);
+ assert!(log.is_bot);
+ assert_eq!(log.bot_category, Some(BotCategory::Google));
+ assert_eq!(log.bot_source, Some(BotSource::Ip));
+ assert!(counter_labels_match(&recorder, "log_only", "google", "ip"));
+ }
+
+ #[test]
+ fn enforced_match_rejects_and_records_observability() {
+ let recorder = DebuggingRecorder::new();
+ let mut log = fresh_log();
+ let outcome = metrics::with_local_recorder(&recorder, || {
+ classify_and_stamp(
+ &mut log,
+ &BotFilterMode::Enforced,
+ Some(GOOGLEBOT_UA),
+ BENIGN_IP,
+ )
+ });
+ assert_eq!(outcome, BotFilterOutcome::Reject);
+ assert!(log.is_bot);
+ assert_eq!(log.bot_category, Some(BotCategory::Google));
+ assert_eq!(log.bot_source, Some(BotSource::UserAgent));
+ assert!(counter_labels_match(
+ &recorder,
+ "enforced",
+ "google",
+ "user_agent"
+ ));
+ }
+ }
}
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 94369b62eb46..85d1abf4dc65 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -64,6 +64,41 @@ impl FromStr for ServiceMode {
}
}
+/// Tri-state controller for the /flags bot filter. Classification runs iff
+/// mode != Disabled; short-circuit happens iff mode == Enforced. Default is
+/// LogOnly so the filter ships observable-but-inert, then operators flip to
+/// Enforced once dashboards confirm the per-category rejection profile is sane.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum BotFilterMode {
+ /// Skip the bot check entirely — no classification, no canonical-log
+ /// stamp, no metric. Use to back out of an unexpected interaction with
+ /// the rest of the pipeline.
+ Disabled,
+ /// Classify, stamp `is_bot`/`bot_category`/`bot_source` on the canonical
+ /// log, bump `flags_bot_detected_total{mode="log_only"}`, then continue
+ /// through the normal pipeline. Safe-rollout default.
+ LogOnly,
+ /// Classify, stamp the canonical log, bump
+ /// `flags_bot_detected_total{mode="enforced"}`, and return the minimal
+ /// envelope without running auth/billing/eval.
+ Enforced,
+}
+
+impl FromStr for BotFilterMode {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_lowercase().as_str() {
+ "disabled" => Ok(BotFilterMode::Disabled),
+ "log_only" | "log-only" => Ok(BotFilterMode::LogOnly),
+ "enforced" | "enforce" => Ok(BotFilterMode::Enforced),
+ _ => Err(format!(
+ "Invalid FLAGS_BOT_FILTER_MODE: '{s}'. Expected 'disabled', 'log_only', or 'enforced'"
+ )),
+ }
+ }
+}
+
/// Tristate selector for the in-process billing aggregator. Encoded as one
/// enum so `(authoritative=true, enabled=false)` is unrepresentable — the
/// previous two-boolean form allowed it and `server.rs` had to panic on it.
@@ -584,6 +619,14 @@ pub struct Config {
#[envconfig(from = "OTEL_LOG_LEVEL", default = "info")]
pub otel_log_level: Level,
+ // Tri-state controller for the /flags bot filter. See [`BotFilterMode`]
+ // for the per-variant semantics. Defaults to `log_only` so the filter
+ // ships observable-but-inert; operators flip to `enforced` once the
+ // rejection profile in `flags_bot_detected_total{mode="log_only"}` looks
+ // correct, or to `disabled` to back out of an interaction entirely.
+ #[envconfig(from = "FLAGS_BOT_FILTER_MODE", default = "log_only")]
+ pub bot_filter_mode: BotFilterMode,
+
// Rate limiting configuration for /flags endpoint (token-based)
// Enable/disable token-based rate limiting (defaults to off to match /decide)
#[envconfig(from = "FLAGS_RATE_LIMIT_ENABLED", default = "false")]
@@ -949,6 +992,9 @@ impl Config {
object_storage_bucket: "posthog".to_string(),
object_storage_region: "us-east-1".to_string(),
object_storage_endpoint: "".to_string(),
+ // `Enforced` so tests exercise the bot short-circuit envelope.
+ // Tests wanting prod posture override to `LogOnly` explicitly.
+ bot_filter_mode: BotFilterMode::Enforced,
flags_rate_limit_enabled: FlexBool(false),
flags_bucket_capacity: 625,
flags_bucket_replenish_rate: 10.0,
@@ -1117,6 +1163,10 @@ mod tests {
assert_eq!(config.debug, FlexBool(false));
assert!(!config.flags_session_replay_quota_check);
assert_eq!(config.skip_writes, FlexBool(false));
+ // Bot filter ships in LogOnly mode by default — pin the safe
+ // posture so a future env-var rename / refactor can't silently
+ // flip it back to Enforced.
+ assert_eq!(config.bot_filter_mode, BotFilterMode::LogOnly);
assert_eq!(config.billing_aggregator_mode, AggregatorModeConfig::Shadow);
}
@@ -1497,6 +1547,49 @@ mod service_mode_tests {
let config = Config::default_test_config();
assert_eq!(config.service_mode, ServiceMode::All);
}
+
+ #[test]
+ fn test_bot_filter_mode_from_str() {
+ // Canonical spellings.
+ assert_eq!(
+ "disabled".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::Disabled
+ );
+ assert_eq!(
+ "log_only".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::LogOnly
+ );
+ assert_eq!(
+ "enforced".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::Enforced
+ );
+ // Aliases — operators often reach for the simpler form.
+ assert_eq!(
+ "log-only".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::LogOnly
+ );
+ assert_eq!(
+ "enforce".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::Enforced
+ );
+ // Case-insensitive + whitespace-tolerant (mirrors ServiceMode).
+ assert_eq!(
+ "LOG_ONLY".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::LogOnly
+ );
+ assert_eq!(
+ " Enforced ".parse::<BotFilterMode>().unwrap(),
+ BotFilterMode::Enforced
+ );
+ }
+
+ #[test]
+ fn test_bot_filter_mode_invalid() {
+ assert!("".parse::<BotFilterMode>().is_err());
+ assert!("on".parse::<BotFilterMode>().is_err());
+ assert!("off".parse::<BotFilterMode>().is_err());
+ assert!("true".parse::<BotFilterMode>().is_err());
+ }
}
#[cfg(test)]
diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rs
index 18acf71940ca..0d7869a27a06 100644
--- a/rust/feature-flags/src/handler/canonical_log.rs
+++ b/rust/feature-flags/src/handler/canonical_log.rs
@@ -5,6 +5,7 @@ use crate::metrics::consts::{
FLAG_BODY_READ_TIME_MS, FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS, FLAG_DB_OPERATIONS_PER_REQUEST,
FLAG_PHASE_DURATION_MS, FLAG_PRE_HANDLER_TIME_MS, FLAG_QUEUE_TIME_MS,
};
+use crate::utils::bot_detection::{BotCategory, BotSource};
use std::cell::RefCell;
use std::future::Future;
use std::time::Instant;
@@ -307,6 +308,15 @@ pub struct FlagsCanonicalLogLine {
pub http_status: u16,
/// Error code from FlagError::error_code(). Uses &'static str to avoid allocation.
pub error_code: Option<&'static str>,
+
+ /// True when the request was short-circuited by the bot filter and
+ /// skipped token rate-limit, auth, billing, and evaluation.
+ pub is_bot: bool,
+ /// Matched bot category, set iff `is_bot` is true. The enum bounds
+ /// the label set; [`Self::emit`] stringifies at log time.
+ pub bot_category: Option<BotCategory>,
+ /// Which signal fired (UA or IP), set iff `is_bot` is true.
+ pub bot_source: Option<BotSource>,
}
impl Default for FlagsCanonicalLogLine {
@@ -355,6 +365,9 @@ impl Default for FlagsCanonicalLogLine {
team_cache_source: None,
http_status: 200,
error_code: None,
+ is_bot: false,
+ bot_category: None,
+ bot_source: None,
}
}
}
@@ -424,6 +437,9 @@ impl FlagsCanonicalLogLine {
billing_duration_ms = self.billing_duration_ms,
team_cache_source = self.team_cache_source,
error_code = self.error_code,
+ is_bot = self.is_bot,
+ bot_category = self.bot_category.map(|c| c.as_str()),
+ bot_source = self.bot_source.map(|s| s.as_str()),
"canonical_log_line"
);
}
@@ -594,6 +610,16 @@ impl FlagsCanonicalLogLine {
self.set_error(error);
self.emit();
}
+
+ /// Emit dependent histograms then the canonical log. For short-circuit
+ /// paths that bypass `run_with_canonical_log` (IP rate-limit blocked,
+ /// bot-Enforced).
+ pub fn emit_short_circuit(&self) {
+ self.emit_db_operations_metrics();
+ self.emit_timing_metrics();
+ self.emit_phase_metrics();
+ self.emit();
+ }
}
#[cfg(test)]
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index f7d48e93dd24..b790eb655d17 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -293,6 +293,18 @@ pub const FLAG_DEFINITIONS_ETAG_COUNTER: &str = "flags_flag_definitions_etag_tot
// Labels: method (secret_api_key, personal_api_key) — Rust only supports these two; Python also tracks oauth, jwt, session, other
pub const FLAG_DEFINITIONS_AUTH_COUNTER: &str = "flags_flag_definitions_auth_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 phase
+// alongside the actual enforce-mode reject rate.
+// Labels: `bot_category` (google, ai, seo, uptime, social, headless,
+// crawler, other), `bot_source` (user_agent, ip), and
+// `mode` (`log_only` — classified but not blocked; `enforced` — classified
+// and short-circuited). No `team_id` because classification fires before
+// token extraction; per-team analysis lives in the canonical log line via
+// Loki.
+pub const FLAG_BOT_DETECTED_COUNTER: &str = "flags_bot_detected_total";
+
// Request-level timeout (tower TimeoutLayer killed the request before completion)
pub const FLAG_REQUEST_TIMEOUT_COUNTER: &str = "flags_request_timeout_total";
diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rs
index 0329f57bbd2c..527716ed9648 100644
--- a/rust/feature-flags/src/router.rs
+++ b/rust/feature-flags/src/router.rs
@@ -55,6 +55,7 @@ use crate::{
utils::team_id_label_filter,
},
rayon_dispatcher::RayonDispatcher,
+ utils::bot_detection,
};
#[derive(Clone)]
@@ -194,6 +195,11 @@ pub fn router(
config.rate_limiter_cleanup_interval_secs,
);
+ // Force eager construction of the bot UA matcher and IP-range table so
+ // the first `/flags` request after a pod restart doesn't pay the
+ // (sub-ms) build cost on its hot path.
+ bot_detection::warm_caches();
+
let state = State {
redis_client,
dedicated_redis_client,
diff --git a/rust/feature-flags/src/utils/bot_detection.rs b/rust/feature-flags/src/utils/bot_detection.rs
new file mode 100644
index 000000000000..887fb2f8b965
--- /dev/null
+++ b/rust/feature-flags/src/utils/bot_detection.rs
@@ -0,0 +1,750 @@
+//! Bot detection for `/flags`. UA-substring matcher mirrors posthog-js
+//! (`sdk/js-sdk/packages/core/src/utils/bot-detection.ts`); IP-range matcher
+//! covers the case where an upstream proxy (e.g. CloudFront) rewrites the
+//! User-Agent and only the source IP is usable.
+
+use aho_corasick::{AhoCorasick, MatchKind};
+use std::net::IpAddr;
+use std::sync::LazyLock;
+
+/// Used as a Prometheus label, so the variant set must stay closed and
+/// low-cardinality.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BotCategory {
+ Google,
+ Ai,
+ Seo,
+ Uptime,
+ Social,
+ Headless,
+ Crawler,
+ Other,
+}
+
+impl BotCategory {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ BotCategory::Google => "google",
+ BotCategory::Ai => "ai",
+ BotCategory::Seo => "seo",
+ BotCategory::Uptime => "uptime",
+ BotCategory::Social => "social",
+ BotCategory::Headless => "headless",
+ BotCategory::Crawler => "crawler",
+ BotCategory::Other => "other",
+ }
+ }
+}
+
+/// Which signal triggered the bot classification. Reported as a metric label
+/// and on the canonical log so operators can see whether UA or IP did the work.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BotSource {
+ UserAgent,
+ Ip,
+}
+
+impl BotSource {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ BotSource::UserAgent => "user_agent",
+ BotSource::Ip => "ip",
+ }
+ }
+}
+
+/// (lowercased pattern, category). First-hit; specific names come before
+/// generic substrings like `bot/` so e.g. AhrefsBot UAs that also contain
+/// `bot/` via a reference URL classify as Seo, not Crawler.
+const BOT_PATTERNS: &[(&str, BotCategory)] = &[
+ // Google crawlers
+ ("google-hoteladsverifier", BotCategory::Google),
+ ("adsbot-google", BotCategory::Google),
+ ("apis-google", BotCategory::Google),
+ ("duplexweb-google", BotCategory::Google),
+ ("feedfetcher-google", BotCategory::Google),
+ ("google favicon", BotCategory::Google),
+ ("google web preview", BotCategory::Google),
+ ("google-read-aloud", BotCategory::Google),
+ ("googlebot", BotCategory::Google),
+ ("googleother", BotCategory::Google),
+ ("google-cloudvertexbot", BotCategory::Google),
+ ("googleweblight", BotCategory::Google),
+ ("mediapartners-google", BotCategory::Google),
+ ("storebot-google", BotCategory::Google),
+ ("google-inspectiontool", BotCategory::Google),
+ // AI crawlers
+ ("gptbot", BotCategory::Ai),
+ ("oai-searchbot", BotCategory::Ai),
+ ("chatgpt-user", BotCategory::Ai),
+ ("perplexitybot", BotCategory::Ai),
+ ("bytespider", BotCategory::Ai),
+ // SEO tools
+ ("ahrefsbot", BotCategory::Seo),
+ ("ahrefssiteaudit", BotCategory::Seo),
+ ("semrushbot", BotCategory::Seo),
+ ("siteauditbot", BotCategory::Seo),
+ ("splitsignalbot", BotCategory::Seo),
+ ("backlinksextendedbot", BotCategory::Seo),
+ ("dataforseobot", BotCategory::Seo),
+ ("mj12bot", BotCategory::Seo),
+ ("rogerbot", BotCategory::Seo),
+ ("screaming frog", BotCategory::Seo),
+ ("sitebulb", BotCategory::Seo),
+ // Uptime monitors
+ ("better uptime bot", BotCategory::Uptime),
+ ("sentryuptimebot", BotCategory::Uptime),
+ ("uptimerobot", BotCategory::Uptime),
+ // Headless browsers / automation
+ ("headlesschrome", BotCategory::Headless),
+ ("cypress", BotCategory::Headless),
+ ("chrome-lighthouse", BotCategory::Headless),
+ ("prerender", BotCategory::Headless),
+ ("vercel-screenshot", BotCategory::Headless),
+ // Social link unfurlers
+ ("facebookexternal", BotCategory::Social),
+ ("facebookcatalog", BotCategory::Social),
+ ("linkedinbot", BotCategory::Social),
+ ("meta-externalagent", BotCategory::Social),
+ ("pinterest", BotCategory::Social),
+ ("slackbot", BotCategory::Social),
+ ("twitterbot", BotCategory::Social),
+ // Named search crawlers
+ ("baiduspider", BotCategory::Crawler),
+ ("bingbot", BotCategory::Crawler),
+ ("bingpreview", BotCategory::Crawler),
+ ("duckduckbot", BotCategory::Crawler),
+ ("http://yandex.com/bots", BotCategory::Crawler),
+ ("msnbot", BotCategory::Crawler),
+ ("petalbot", BotCategory::Crawler),
+ ("slurp", BotCategory::Crawler),
+ ("yahoo! slurp", BotCategory::Crawler),
+ ("yandexbot", BotCategory::Crawler),
+ // Other named bots
+ ("amazonbot", BotCategory::Other),
+ ("amazonproductbot", BotCategory::Other),
+ ("app.hypefactors.com", BotCategory::Other),
+ ("applebot", BotCategory::Other),
+ ("archive.org_bot", BotCategory::Other),
+ ("awariobot", BotCategory::Other),
+ ("deepscan", BotCategory::Other),
+ ("hubspot", BotCategory::Other),
+ ("ia_archiver", BotCategory::Other),
+ ("leikibot", BotCategory::Other),
+ ("nessus", BotCategory::Other),
+ ("sebot-wa", BotCategory::Other),
+ ("trendictionbot", BotCategory::Other),
+ ("turnitin", BotCategory::Other),
+ ("vercelbot", BotCategory::Other),
+ ("zoombot", BotCategory::Other),
+ // Generic substrings — keep below the named-bot entries. `classify`
+ // returns the lowest pattern index, so specific names win over `bot/`
+ // / `crawler`. Guarded by `specific_pattern_beats_generic_bot_substring`.
+ ("bot.htm", BotCategory::Crawler),
+ ("bot.php", BotCategory::Crawler),
+ ("(bot;", BotCategory::Crawler),
+ ("bot/", BotCategory::Crawler),
+ ("crawler", BotCategory::Crawler),
+];
+
+/// `MatchKind::Standard` is required for `find_overlapping_iter`, which
+/// is what `classify` uses to enumerate every match so the lowest pattern
+/// index wins (specific bot names ahead of generic `bot/` / `crawler`).
+static BOT_MATCHER: LazyLock<AhoCorasick> = LazyLock::new(|| {
+ AhoCorasick::builder()
+ .ascii_case_insensitive(true)
+ .match_kind(MatchKind::Standard)
+ .build(BOT_PATTERNS.iter().map(|(p, _)| *p))
+ .expect("BOT_PATTERNS is a valid Aho-Corasick input")
+});
+
+/// Call once at server start to keep the first `/flags` request after a
+/// pod restart off the matcher/IP-range build path.
+pub fn warm_caches() {
+ LazyLock::force(&BOT_MATCHER);
+ LazyLock::force(&BOT_IP_RANGES);
+}
+
+/// When multiple patterns match, the lowest index in `BOT_PATTERNS` wins.
+pub fn classify(user_agent: &str) -> Option<BotCategory> {
+ if user_agent.is_empty() {
+ return None;
+ }
+ BOT_MATCHER
+ .find_overlapping_iter(user_agent)
+ .map(|m| m.pattern().as_usize())
+ .min()
+ .map(|idx| BOT_PATTERNS[idx].1)
+}
+
+/// Published bot IP ranges. Refresh from the provider source-of-truth files:
+/// Googlebot: https://developers.google.com/search/apis/ipranges/googlebot.json
+/// Bingbot: https://www.bing.com/toolbox/bingbot.json
+/// YandexBot: https://yandex.com/ips/
+/// Applebot: https://search.developer.apple.com/applebot.json
+///
+/// Prefer supernets over the dozens of /27s each provider publishes — every
+/// CIDR here costs one `Vec` entry + a binary-search comparison.
+const BOT_CIDRS: &[(&str, BotCategory)] = &[
+ // Googlebot
+ ("66.249.64.0/19", BotCategory::Google),
+ ("2001:4860:4801::/48", BotCategory::Google),
+ // Bingbot
+ ("40.77.139.0/25", BotCategory::Crawler),
+ ("207.46.13.0/24", BotCategory::Crawler),
+ ("157.55.39.0/24", BotCategory::Crawler),
+ // YandexBot
+ ("5.45.207.0/24", BotCategory::Crawler),
+ ("5.255.250.0/24", BotCategory::Crawler),
+ ("87.250.224.0/19", BotCategory::Crawler),
+ ("95.108.128.0/17", BotCategory::Crawler),
+ ("213.180.192.0/19", BotCategory::Crawler),
+ // Applebot
+ ("17.241.75.0/26", BotCategory::Other),
+];
+
+/// Half-open is tempting but inclusive `[start, end]` is what fits CIDR
+/// semantics and lets v4 share the lookup with v6 by widening to `u128`.
+#[derive(Debug, Clone, Copy)]
+struct IpRange {
+ start: u128,
+ end: u128,
+ category: BotCategory,
+}
+
+/// Split-by-family so v4 lookups never scan v6 entries and vice versa. Each
+/// slice is sorted by `start`, enabling `partition_point` binary search.
+struct BotIpRanges {
+ v4: Box<[IpRange]>,
+ v6: Box<[IpRange]>,
+}
+
+static BOT_IP_RANGES: LazyLock<BotIpRanges> = LazyLock::new(|| build_ranges(BOT_CIDRS));
+
+/// Minimum CIDR prefix in `BOT_CIDRS` — bounds how many addresses a
+/// single entry classifies as bots. Enforced by `build_ranges`, surfaced
+/// at server start via `warm_caches()`.
+///
+/// Current widest entries: `/17` (Yandex v4), `/48` (Googlebot v6).
+const MIN_V4_PREFIX: u32 = 16;
+const MIN_V6_PREFIX: u32 = 32;
+
+fn build_ranges(cidrs: &[(&str, BotCategory)]) -> BotIpRanges {
+ let mut v4 = Vec::new();
+ let mut v6 = Vec::new();
+ for (cidr, category) in cidrs {
+ let parsed =
+ parse_cidr(cidr).unwrap_or_else(|| panic!("invalid CIDR in BOT_CIDRS: {cidr}"));
+ // `2^host_bits = end - start + 1` for an inclusive [start, end].
+ let host_bits = (parsed.end - parsed.start + 1).trailing_zeros();
+ let max_host_bits = if parsed.is_v4 {
+ 32 - MIN_V4_PREFIX
+ } else {
+ 128 - MIN_V6_PREFIX
+ };
+ assert!(
+ host_bits <= max_host_bits,
+ "BOT_CIDRS entry {cidr} is broader than the minimum prefix \
+ (/{} v4, /{} v6); refusing to classify that many addresses as bots",
+ MIN_V4_PREFIX,
+ MIN_V6_PREFIX,
+ );
+ let range = IpRange {
+ start: parsed.start,
+ end: parsed.end,
+ category: *category,
+ };
+ if parsed.is_v4 {
+ v4.push(range);
+ } else {
+ v6.push(range);
+ }
+ }
+ v4.sort_by_key(|r| r.start);
+ v6.sort_by_key(|r| r.start);
+ BotIpRanges {
+ v4: v4.into_boxed_slice(),
+ v6: v6.into_boxed_slice(),
+ }
+}
+
+struct ParsedCidr {
+ start: u128,
+ end: u128,
+ is_v4: bool,
+}
+
+fn parse_cidr(cidr: &str) -> Option<ParsedCidr> {
+ let (addr_str, prefix_str) = cidr.split_once('/')?;
+ let prefix: u8 = prefix_str.parse().ok()?;
+ let addr: IpAddr = addr_str.parse().ok()?;
+ match addr {
+ IpAddr::V4(v4) => {
+ if prefix > 32 {
+ return None;
+ }
+ let base = u32::from(v4);
+ let mask = if prefix == 0 {
+ 0
+ } else {
+ !0u32 << (32 - prefix)
+ };
+ let start = base & mask;
+ let end = start | !mask;
+ Some(ParsedCidr {
+ start: u128::from(start),
+ end: u128::from(end),
+ is_v4: true,
+ })
+ }
+ IpAddr::V6(v6) => {
+ if prefix > 128 {
+ return None;
+ }
+ let base = u128::from(v6);
+ let mask = if prefix == 0 {
+ 0
+ } else {
+ !0u128 << (128 - prefix)
+ };
+ let start = base & mask;
+ let end = start | !mask;
+ Some(ParsedCidr {
+ start,
+ end,
+ is_v4: false,
+ })
+ }
+ }
+}
+
+/// Collapse IPv4-mapped IPv6 (`::ffff:1.2.3.4`) to IPv4 so reverse proxies
+/// that hand us mapped form still hit the v4 ranges.
+fn normalize(ip: IpAddr) -> IpAddr {
+ match ip {
+ IpAddr::V6(v6) => v6
+ .to_ipv4_mapped()
+ .map(IpAddr::V4)
+ .unwrap_or(IpAddr::V6(v6)),
+ v4 => v4,
+ }
+}
+
+/// Returns the matched bot category if `ip` falls inside any published bot
+/// range. Hot path is one `partition_point` over a few dozen sorted entries.
+pub fn classify_ip(ip: IpAddr) -> Option<BotCategory> {
+ let ranges = &*BOT_IP_RANGES;
+ match normalize(ip) {
+ IpAddr::V4(v4) => lookup(&ranges.v4, u128::from(u32::from(v4))),
+ IpAddr::V6(v6) => lookup(&ranges.v6, u128::from(v6)),
+ }
+}
+
+fn lookup(ranges: &[IpRange], key: u128) -> Option<BotCategory> {
+ // `partition_point` returns the count of entries whose `start <= key`.
+ // The candidate range, if any, is the immediately preceding entry.
+ let idx = ranges.partition_point(|r| r.start <= key);
+ if idx == 0 {
+ return None;
+ }
+ let r = ranges[idx - 1];
+ (key <= r.end).then_some(r.category)
+}
+
+/// Unified classifier: UA first (cheaper, more specific), then IP. Returns
+/// the matched category plus which signal fired, so the caller can label
+/// metrics and logs without re-running either check.
+pub fn classify_request(user_agent: Option<&str>, ip: IpAddr) -> Option<(BotCategory, BotSource)> {
+ if let Some(ua) = user_agent {
+ if let Some(c) = classify(ua) {
+ return Some((c, BotSource::UserAgent));
+ }
+ }
+ classify_ip(ip).map(|c| (c, BotSource::Ip))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rstest::rstest;
+
+ #[rstest]
+ #[case(
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
+ BotCategory::Google
+ )]
+ #[case("Googlebot-Image/1.0", BotCategory::Google)]
+ #[case(
+ "AdsBot-Google (+http://www.google.com/adsbot.html)",
+ BotCategory::Google
+ )]
+ #[case(
+ "APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)",
+ BotCategory::Google
+ )]
+ #[case("Mozilla/5.0 (compatible; GoogleOther)", BotCategory::Google)]
+ #[case(
+ "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
+ BotCategory::Crawler
+ )]
+ #[case(
+ "DuckDuckBot/1.1; (+http://duckduckgo.com/duckduckbot.html)",
+ BotCategory::Crawler
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)",
+ BotCategory::Crawler
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)",
+ BotCategory::Crawler
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)",
+ BotCategory::Seo
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html)",
+ BotCategory::Seo
+ )]
+ #[case("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.0; +https://openai.com/gptbot)", BotCategory::Ai)]
+ #[case("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ChatGPT-User/1.0; +https://openai.com/bot)", BotCategory::Ai)]
+ #[case("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; PerplexityBot/1.0; +https://perplexity.ai/bot)", BotCategory::Ai)]
+ #[case(
+ "Mozilla/5.0 (compatible; Bytespider; [email protected])",
+ BotCategory::Ai
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; UptimeRobot/2.0; http://www.uptimerobot.com/)",
+ BotCategory::Uptime
+ )]
+ #[case("Better Uptime Bot Manifest/1.0", BotCategory::Uptime)]
+ #[case(
+ "Mozilla/5.0 (compatible; LinkedInBot/1.0; +http://www.linkedin.com/)",
+ BotCategory::Social
+ )]
+ #[case(
+ "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
+ BotCategory::Social
+ )]
+ #[case("Twitterbot/1.0", BotCategory::Social)]
+ #[case(
+ "Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)",
+ BotCategory::Social
+ )]
+ #[case("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/120.0.0.0 Safari/537.36", BotCategory::Headless)]
+ #[case(
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Cypress/13.0.0",
+ BotCategory::Headless
+ )]
+ fn classify_returns_expected_category(#[case] ua: &str, #[case] expected: BotCategory) {
+ assert_eq!(classify(ua), Some(expected), "UA: {}", ua);
+ }
+
+ #[rstest]
+ #[case("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")]
+ #[case("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0")]
+ #[case("Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1")]
+ #[case("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15")]
+ #[case("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0")]
+ #[case("posthog-js/1.374.3")]
+ #[case("posthog-python/3.0.0")]
+ #[case("posthog-node/5.34.7")]
+ #[case("posthog-go/1.0.0")]
+ fn classify_returns_none_for_real_clients(#[case] ua: &str) {
+ assert_eq!(
+ classify(ua),
+ None,
+ "Should not match real client UA: {}",
+ ua
+ );
+ }
+
+ #[test]
+ fn empty_user_agent_is_not_a_bot() {
+ assert_eq!(classify(""), None);
+ }
+
+ #[rstest]
+ #[case("Mozilla/5.0 (compatible; GoogleBot/2.1)", BotCategory::Google)]
+ #[case("Mozilla/5.0 (compatible; GOOGLEBOT/2.1)", BotCategory::Google)]
+ #[case("Mozilla/5.0 (compatible; googlebot/2.1)", BotCategory::Google)]
+ #[case("MOZILLA/5.0 GPTBOT/1.0", BotCategory::Ai)]
+ #[case("AHREFSBOT/7.0", BotCategory::Seo)]
+ fn matching_is_case_insensitive(#[case] ua: &str, #[case] expected: BotCategory) {
+ assert_eq!(classify(ua), Some(expected));
+ }
+
+ #[test]
+ fn category_as_str_is_low_cardinality() {
+ // Guards the Prometheus label invariant: short, stable, ASCII.
+ for &(_, cat) in BOT_PATTERNS {
+ let s = cat.as_str();
+ assert!(!s.is_empty());
+ assert!(s.len() < 32);
+ assert!(s.chars().all(|c| c.is_ascii_lowercase() || c == '_'));
+ }
+ }
+
+ #[test]
+ fn bot_patterns_are_lowercase() {
+ // Keeps the source-of-truth comparison with the SDK list trivial.
+ for &(pattern, _) in BOT_PATTERNS {
+ assert_eq!(
+ pattern,
+ pattern.to_ascii_lowercase(),
+ "Pattern must be lowercase: {}",
+ pattern
+ );
+ }
+ }
+
+ #[test]
+ fn every_pattern_classifies_as_its_own_category() {
+ // A UA equal to a pattern must classify as that pattern's
+ // category — guards the lowest-index-wins rule against any
+ // future matcher drift.
+ for &(pattern, expected) in BOT_PATTERNS {
+ assert_eq!(
+ classify(pattern),
+ Some(expected),
+ "Pattern {pattern:?} should classify as {expected:?}",
+ );
+ }
+ }
+
+ /// UAs that contain both a specific bot name and the generic `bot/`
+ /// substring — exercises the lowest-index tiebreaker.
+ #[rstest]
+ #[case(
+ "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)",
+ BotCategory::Seo
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html)",
+ BotCategory::Seo
+ )]
+ #[case(
+ "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
+ BotCategory::Crawler
+ )]
+ fn specific_pattern_beats_generic_bot_substring(
+ #[case] ua: &str,
+ #[case] expected: BotCategory,
+ ) {
+ assert_eq!(classify(ua), Some(expected));
+ }
+
+ mod ip {
+ use super::*;
+ use std::net::Ipv4Addr;
+
+ #[rstest]
+ // Googlebot IPv4 range 66.249.64.0/19 (66.249.64.0 — 66.249.95.255).
+ #[case("66.249.64.0", BotCategory::Google)]
+ #[case("66.249.79.123", BotCategory::Google)]
+ #[case("66.249.95.255", BotCategory::Google)]
+ // Bingbot.
+ #[case("207.46.13.42", BotCategory::Crawler)]
+ #[case("40.77.139.5", BotCategory::Crawler)]
+ // YandexBot.
+ #[case("95.108.200.10", BotCategory::Crawler)]
+ fn classify_ip_matches_known_bot_ranges(#[case] ip: &str, #[case] expected: BotCategory) {
+ let parsed: IpAddr = ip.parse().unwrap();
+ assert_eq!(classify_ip(parsed), Some(expected));
+ }
+
+ #[rstest]
+ // Just outside Googlebot's /19 on either side.
+ #[case("66.249.63.255")]
+ #[case("66.249.96.0")]
+ // Common public DNS / CDN ranges that aren't on the bot list.
+ #[case("8.8.8.8")]
+ #[case("1.1.1.1")]
+ #[case("104.16.0.1")]
+ // Private RFC1918.
+ #[case("10.0.0.1")]
+ #[case("192.168.1.1")]
+ // Loopback.
+ #[case("127.0.0.1")]
+ fn classify_ip_returns_none_for_non_bot_ips(#[case] ip: &str) {
+ let parsed: IpAddr = ip.parse().unwrap();
+ assert_eq!(classify_ip(parsed), None);
+ }
+
+ #[test]
+ fn googlebot_ipv6_range_matches() {
+ // 2001:4860:4801::/48 is a Googlebot IPv6 supernet.
+ let ip: IpAddr = "2001:4860:4801:42::1".parse().unwrap();
+ assert_eq!(classify_ip(ip), Some(BotCategory::Google));
+ }
+
+ #[test]
+ fn ipv4_mapped_ipv6_normalizes_to_ipv4_match() {
+ // `::ffff:66.249.79.123` represents Googlebot via IPv4-mapped form;
+ // upstream proxies sometimes hand us this shape.
+ let mapped = Ipv4Addr::new(66, 249, 79, 123).to_ipv6_mapped();
+ assert_eq!(classify_ip(IpAddr::V6(mapped)), Some(BotCategory::Google));
+ }
+
+ #[test]
+ fn arbitrary_ipv6_outside_bot_ranges_is_none() {
+ let ip: IpAddr = "2606:4700:4700::1111".parse().unwrap(); // Cloudflare DNS.
+ assert_eq!(classify_ip(ip), None);
+ }
+
+ #[rstest]
+ #[case("0.0.0.0/0", 0u32, u32::MAX)]
+ #[case("10.0.0.0/8", 10u32 << 24, (10u32 << 24) | 0x00_FF_FF_FF)]
+ #[case("192.168.1.0/24", (192u32 << 24) | (168 << 16) | (1 << 8), (192u32 << 24) | (168 << 16) | (1 << 8) | 0xFF)]
+ #[case("203.0.113.42/32", (203u32 << 24) | (113 << 8) | 42, (203u32 << 24) | (113 << 8) | 42)]
+ fn parse_cidr_v4_boundaries(
+ #[case] cidr: &str,
+ #[case] expected_start: u32,
+ #[case] expected_end: u32,
+ ) {
+ let p = parse_cidr(cidr).unwrap();
+ assert!(p.is_v4);
+ assert_eq!(p.start, u128::from(expected_start));
+ assert_eq!(p.end, u128::from(expected_end));
+ }
+
+ #[rstest]
+ #[case("not-an-ip/24")]
+ #[case("10.0.0.0/33")]
+ #[case("::/129")]
+ #[case("missing-prefix")]
+ fn parse_cidr_rejects_malformed(#[case] cidr: &str) {
+ assert!(parse_cidr(cidr).is_none());
+ }
+
+ #[test]
+ fn built_ranges_are_sorted_by_start() {
+ // The lookup uses `partition_point` which requires the slice to
+ // be sorted by `start`. Guard the invariant the builder enforces.
+ let ranges = &*BOT_IP_RANGES;
+ assert!(ranges.v4.windows(2).all(|w| w[0].start <= w[1].start));
+ assert!(ranges.v6.windows(2).all(|w| w[0].start <= w[1].start));
+ }
+
+ #[test]
+ fn built_ranges_are_non_overlapping() {
+ // `lookup` only inspects the largest `start <= key` entry,
+ // so an overlapping later range would mask an earlier one.
+ let ranges = &*BOT_IP_RANGES;
+ for w in ranges.v4.windows(2) {
+ assert!(
+ w[0].end < w[1].start,
+ "overlapping v4 ranges: [{}, {}] and [{}, {}]",
+ w[0].start,
+ w[0].end,
+ w[1].start,
+ w[1].end,
+ );
+ }
+ for w in ranges.v6.windows(2) {
+ assert!(
+ w[0].end < w[1].start,
+ "overlapping v6 ranges: [{}, {}] and [{}, {}]",
+ w[0].start,
+ w[0].end,
+ w[1].start,
+ w[1].end,
+ );
+ }
+ }
+
+ #[test]
+ fn every_published_cidr_parses() {
+ // build_ranges panics on a bad CIDR; touching LazyLock would
+ // have already done this, but be explicit for future drift.
+ for (cidr, _) in BOT_CIDRS {
+ assert!(parse_cidr(cidr).is_some(), "failed to parse {cidr}");
+ }
+ }
+
+ #[test]
+ fn published_cidrs_respect_width_floor() {
+ for (cidr, _) in BOT_CIDRS {
+ let parsed = parse_cidr(cidr).expect("BOT_CIDRS entry parses");
+ let host_bits = (parsed.end - parsed.start + 1).trailing_zeros();
+ let max_host_bits = if parsed.is_v4 {
+ 32 - MIN_V4_PREFIX
+ } else {
+ 128 - MIN_V6_PREFIX
+ };
+ assert!(
+ host_bits <= max_host_bits,
+ "{cidr} exceeds the BOT_CIDRS width floor",
+ );
+ }
+ }
+
+ #[test]
+ #[should_panic(expected = "broader than the minimum prefix")]
+ fn build_ranges_rejects_overly_broad_v4_cidr() {
+ drop(build_ranges(&[("66.0.0.0/8", BotCategory::Google)]));
+ }
+
+ #[test]
+ #[should_panic(expected = "broader than the minimum prefix")]
+ fn build_ranges_rejects_overly_broad_v6_cidr() {
+ drop(build_ranges(&[("2001::/16", BotCategory::Google)]));
+ }
+ }
+
+ mod request {
+ use super::*;
+ use std::net::Ipv4Addr;
+
+ const GOOGLEBOT_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(66, 249, 79, 123));
+ const NON_BOT_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8));
+
+ #[test]
+ fn ua_match_takes_priority_over_ip() {
+ // Even if both signals match, UA wins because it's the more
+ // specific signal (the IP could be a misconfigured network).
+ let (cat, source) = classify_request(
+ Some("Mozilla/5.0 (compatible; AhrefsBot/7.0)"),
+ GOOGLEBOT_IP,
+ )
+ .unwrap();
+ assert_eq!(cat, BotCategory::Seo);
+ assert_eq!(source, BotSource::UserAgent);
+ }
+
+ #[test]
+ fn falls_back_to_ip_when_ua_does_not_match() {
+ let (cat, source) = classify_request(
+ Some("Mozilla/5.0 (Windows NT 10.0) Chrome/120"),
+ GOOGLEBOT_IP,
+ )
+ .unwrap();
+ assert_eq!(cat, BotCategory::Google);
+ assert_eq!(source, BotSource::Ip);
+ }
+
+ #[test]
+ fn missing_ua_still_runs_ip_check() {
+ let (cat, source) = classify_request(None, GOOGLEBOT_IP).unwrap();
+ assert_eq!(cat, BotCategory::Google);
+ assert_eq!(source, BotSource::Ip);
+ }
+
+ #[test]
+ fn returns_none_when_neither_signal_matches() {
+ assert!(classify_request(Some("Mozilla/5.0 Chrome/120"), NON_BOT_IP).is_none());
+ assert!(classify_request(None, NON_BOT_IP).is_none());
+ }
+
+ #[test]
+ fn bot_source_labels_are_low_cardinality() {
+ for s in [BotSource::UserAgent, BotSource::Ip] {
+ let label = s.as_str();
+ assert!(!label.is_empty());
+ assert!(label.len() < 32);
+ assert!(label.chars().all(|c| c.is_ascii_lowercase() || c == '_'));
+ }
+ }
+ }
+}
diff --git a/rust/feature-flags/src/utils/mod.rs b/rust/feature-flags/src/utils/mod.rs
index cc41ff83983c..08528274295e 100644
--- a/rust/feature-flags/src/utils/mod.rs
+++ b/rust/feature-flags/src/utils/mod.rs
@@ -1,3 +1,4 @@
+pub mod bot_detection;
pub mod graph_utils;
pub mod json_size;
#[cfg(test)]
diff --git a/rust/feature-flags/tests/test_bot_filtering.rs b/rust/feature-flags/tests/test_bot_filtering.rs
new file mode 100644
index 000000000000..d3a71098726f
--- /dev/null
+++ b/rust/feature-flags/tests/test_bot_filtering.rs
@@ -0,0 +1,619 @@
+use anyhow::Result;
+use reqwest::header::{CONTENT_TYPE, USER_AGENT};
+use reqwest::StatusCode;
+use rstest::rstest;
+use serde_json::json;
+
+use feature_flags::api::types::{FlagsResponse, LegacyFlagsResponse};
+use feature_flags::config::{BotFilterMode, FlexBool, DEFAULT_TEST_CONFIG};
+use feature_flags::utils::test_utils::{
+ insert_flags_for_team_in_redis, insert_new_team_in_redis, setup_redis_client, TestContext,
+};
+
+use crate::common::*;
+
+pub mod common;
+
+const GOOGLEBOT_UA: &str =
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
+/// Reproduces the customer scenario: CloudFront rewrites the UA to its own
+/// brand string before the request reaches us, so the UA matcher cannot fire.
+const CLOUDFRONT_UA: &str = "Amazon CloudFront";
+/// Inside the published Googlebot /19 (66.249.64.0/19).
+const GOOGLEBOT_FORWARDED_IP: &str = "66.249.79.123";
+/// Public-DNS IP, used as a benign baseline.
+const BENIGN_FORWARDED_IP: &str = "8.8.8.8";
+
+#[derive(Default)]
+struct RequestOptions<'a> {
+ user_agent: Option<&'a str>,
+ forwarded_for: Option<&'a str>,
+ /// Value for the `X-Original-Endpoint` header (set to `"decide"` to
+ /// simulate the Python `/decide` proxy).
+ original_endpoint: Option<&'a str>,
+}
+
+async fn post_flags(
+ addr: std::net::SocketAddr,
+ path: &str,
+ body: serde_json::Value,
+ user_agent: Option<&str>,
+) -> reqwest::Response {
+ post_flags_with_version(
+ addr,
+ path,
+ body,
+ RequestOptions {
+ user_agent,
+ ..Default::default()
+ },
+ "2",
+ )
+ .await
+}
+
+async fn post_flags_v1(
+ addr: std::net::SocketAddr,
+ path: &str,
+ body: serde_json::Value,
+ user_agent: Option<&str>,
+) -> reqwest::Response {
+ post_flags_with_version(
+ addr,
+ path,
+ body,
+ RequestOptions {
+ user_agent,
+ ..Default::default()
+ },
+ "1",
+ )
+ .await
+}
+
+async fn post_flags_with_options(
+ addr: std::net::SocketAddr,
+ path: &str,
+ body: serde_json::Value,
+ opts: RequestOptions<'_>,
+) -> reqwest::Response {
+ post_flags_with_version(addr, path, body, opts, "2").await
+}
+
+async fn post_flags_v1_with_options(
+ addr: std::net::SocketAddr,
+ path: &str,
+ body: serde_json::Value,
+ opts: RequestOptions<'_>,
+) -> reqwest::Response {
+ post_flags_with_version(addr, path, body, opts, "1").await
+}
+
+async fn post_flags_with_version(
+ addr: std::net::SocketAddr,
+ path: &str,
+ body: serde_json::Value,
+ opts: RequestOptions<'_>,
+ version: &str,
+) -> reqwest::Response {
+ let client = reqwest::Client::new();
+ let url = format!("http://{}{}?v={}", addr, path, version);
+ let mut req = client
+ .post(url)
+ .body(body.to_string())
+ .header(CONTENT_TYPE, "application/json");
+ if let Some(ua) = opts.user_agent {
+ req = req.header(USER_AGENT, ua);
+ }
+ if let Some(xff) = opts.forwarded_for {
+ req = req.header("X-Forwarded-For", xff);
+ }
+ if let Some(endpoint) = opts.original_endpoint {
+ req = req.header("X-Original-Endpoint", endpoint);
+ }
+ req.send().await.expect("failed to send request")
+}
+
+/// Server with one configured flag, so tests can tell a short-circuit
+/// (empty flags) apart from full evaluation (flag present).
+async fn setup_server_with_a_flag(
+ config: feature_flags::config::Config,
+) -> (ServerHandle, String /* token */) {
+ let client = setup_redis_client(Some(config.redis_url.clone())).await;
+ let team = insert_new_team_in_redis(client.clone()).await.unwrap();
+ let token = team.api_token.clone();
+ let context = TestContext::new(None).await;
+ context.insert_new_team(Some(team.id)).await.unwrap();
+ insert_flags_for_team_in_redis(client.clone(), team.id, None)
+ .await
+ .unwrap();
+ let server = ServerHandle::for_config(config).await;
+ (server, token)
+}
+
+/// Short-circuit path across /flags and /decide, with one UA per
+/// category plus a UA that only matches the generic `bot/` substring.
+#[rstest]
+#[case("/flags", GOOGLEBOT_UA)]
+#[case("/decide", GOOGLEBOT_UA)]
+#[case(
+ "/flags",
+ "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
+)]
+#[case(
+ "/flags",
+ "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)"
+)]
+#[case(
+ "/flags",
+ "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.0; +https://openai.com/gptbot)"
+)]
+#[case(
+ "/flags",
+ "Mozilla/5.0 (compatible; UnknownNewBot/1.0; +https://example.com/bot/)"
+)]
+#[tokio::test]
+async fn bot_user_agent_short_circuits_with_minimal_response(
+ #[case] path: &str,
+ #[case] bot_ua: &str,
+) -> Result<()> {
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags(server.addr, path, payload, Some(bot_ua)).await;
+ assert_eq!(
+ res.status(),
+ StatusCode::OK,
+ "{path} with UA {bot_ua:?} should get 200 OK"
+ );
+
+ let body: FlagsResponse = res.json().await?;
+ assert!(
+ body.flags.is_empty(),
+ "{path} with UA {bot_ua:?}: bot request must not evaluate any flags; got {:?}",
+ body.flags
+ );
+ assert!(!body.errors_while_computing_flags);
+ // `supportedCompression` is only present on the minimal response, so
+ // its presence distinguishes the short-circuit from a generic
+ // empty-flags success.
+ assert_eq!(
+ body.config.get("supportedCompression"),
+ Some(&json!(["gzip", "gzip-js"])),
+ "{path} with UA {bot_ua:?}: response should match the minimal/GET shape"
+ );
+
+ Ok(())
+}
+
+/// Real browser UAs and the no-UA case must reach evaluation. Uses the v1
+/// response shape to dodge `FlagDetails` deserialization quirks on success.
+#[rstest]
+#[case(Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"))]
+#[case(Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0"))]
+#[case(Some("Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1"))]
+#[case(Some("posthog-js/1.374.3"))]
+#[case(None)]
+#[tokio::test]
+async fn non_bot_user_agent_reaches_evaluation(#[case] user_agent: Option<&str>) -> Result<()> {
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags_v1(server.addr, "/flags", payload, user_agent).await;
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body: LegacyFlagsResponse = res.json().await?;
+ assert!(
+ !body.feature_flags.is_empty(),
+ "UA {user_agent:?}: non-bot request should reach evaluation; got empty response"
+ );
+
+ Ok(())
+}
+
+/// Customer scenario: CloudFront strips the UA so only the source IP is
+/// usable for classification. `X-Forwarded-For` carries the real client IP.
+#[rstest]
+#[case("/flags", GOOGLEBOT_FORWARDED_IP)]
+#[case("/decide", GOOGLEBOT_FORWARDED_IP)]
+#[case("/flags", "207.46.13.42")] // Bingbot
+#[case("/flags", "95.108.200.10")] // YandexBot
+#[tokio::test]
+async fn bot_ip_short_circuits_even_when_ua_is_benign(
+ #[case] path: &str,
+ #[case] forwarded_ip: &str,
+) -> Result<()> {
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags_with_options(
+ server.addr,
+ path,
+ payload,
+ RequestOptions {
+ user_agent: Some(CLOUDFRONT_UA),
+ forwarded_for: Some(forwarded_ip),
+ ..Default::default()
+ },
+ )
+ .await;
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body: FlagsResponse = res.json().await?;
+ assert!(
+ body.flags.is_empty(),
+ "{path} with XFF {forwarded_ip}: bot IP must short-circuit; got {:?}",
+ body.flags
+ );
+ assert_eq!(
+ body.config.get("supportedCompression"),
+ Some(&json!(["gzip", "gzip-js"])),
+ "{path} with XFF {forwarded_ip}: response should match minimal shape"
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn benign_ip_with_benign_ua_reaches_evaluation() -> Result<()> {
+ // Public-DNS IP + non-bot UA: both signals miss, so the request must
+ // run through the normal pipeline.
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags_v1_with_options(
+ server.addr,
+ "/flags",
+ payload,
+ RequestOptions {
+ user_agent: Some(
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X) Chrome/120.0.0.0 Safari/537.36",
+ ),
+ forwarded_for: Some(BENIGN_FORWARDED_IP),
+ ..Default::default()
+ },
+ )
+ .await;
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body: LegacyFlagsResponse = res.json().await?;
+ assert!(
+ !body.feature_flags.is_empty(),
+ "Benign UA + benign IP must reach evaluation"
+ );
+
+ Ok(())
+}
+
+/// In `Disabled` mode, neither signal short-circuits — bot-shaped requests
+/// must reach evaluation regardless of which signal would have fired.
+#[rstest]
+#[case::ua_signal(Some(GOOGLEBOT_UA), None)]
+#[case::ip_signal(Some(CLOUDFRONT_UA), Some(GOOGLEBOT_FORWARDED_IP))]
+#[tokio::test]
+async fn disabled_mode_skips_bot_filter_for_both_signals(
+ #[case] user_agent: Option<&'static str>,
+ #[case] forwarded_for: Option<&'static str>,
+) -> Result<()> {
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.bot_filter_mode = BotFilterMode::Disabled;
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags_v1_with_options(
+ server.addr,
+ "/flags",
+ payload,
+ RequestOptions {
+ user_agent,
+ forwarded_for,
+ ..Default::default()
+ },
+ )
+ .await;
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body: LegacyFlagsResponse = res.json().await?;
+ assert!(
+ !body.feature_flags.is_empty(),
+ "Disabled mode must let bot-shaped requests through the full pipeline (ua={user_agent:?}, xff={forwarded_for:?})"
+ );
+
+ Ok(())
+}
+
+/// When the IP rate-limiter has set the `rate_limit_warned` state for a
+/// bot UA, the bot short-circuit must still return the minimal response
+/// and must NOT surface the `X-PostHog-Rate-Limit-Warning` response
+/// header — bots do not read response headers, so the explicit decision
+/// at `endpoint::flags` is to keep the header off the bot path. This
+/// test pins that invariant.
+#[tokio::test]
+async fn bot_response_does_not_carry_rate_limit_warning_header() -> Result<()> {
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.flags_ip_rate_limit_enabled = FlexBool(true);
+ // log_only=true puts the IP limiter in warn-only mode: a request
+ // that would otherwise be Blocked instead returns Warned.
+ config.flags_ip_rate_limit_log_only = FlexBool(true);
+ // burst=1 + warn_ratio=0.5 → derived warn capacity = 0 → no separate
+ // warn limiter. The second request past the burst then hits the
+ // enforce-side block, which warn_only converts to Warned.
+ config.flags_ip_burst_size = 1;
+ config.flags_warn_capacity_ratio = 0.5;
+ // Slow refill so the second request is reliably past the cap.
+ config.flags_ip_replenish_rate = 0.1;
+
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ // Burn the burst token. Both requests use a Googlebot UA so both
+ // short-circuit through the bot path; the first is Allowed, the
+ // second triggers the rate-limit warn.
+ let first = post_flags(server.addr, "/flags", payload.clone(), Some(GOOGLEBOT_UA)).await;
+ assert_eq!(
+ first.status(),
+ StatusCode::OK,
+ "first bot request must be admitted by the IP limiter"
+ );
+ let res = post_flags(server.addr, "/flags", payload, Some(GOOGLEBOT_UA)).await;
+
+ assert_eq!(
+ res.status(),
+ StatusCode::OK,
+ "bot UA must still short-circuit to 200 even when IP warn fires"
+ );
+ assert!(
+ res.headers().get("X-PostHog-Rate-Limit-Warning").is_none(),
+ "bot short-circuit must NOT surface X-PostHog-Rate-Limit-Warning, got {:?}",
+ res.headers().get("X-PostHog-Rate-Limit-Warning"),
+ );
+ // Sanity-check: response is still the minimal bot envelope.
+ let body: FlagsResponse = res.json().await?;
+ assert!(body.flags.is_empty(), "bot path must not evaluate flags");
+ assert_eq!(
+ body.config.get("supportedCompression"),
+ Some(&json!(["gzip", "gzip-js"])),
+ "response should match the minimal-config marker"
+ );
+
+ Ok(())
+}
+
+/// Positive control for `bot_response_does_not_carry_rate_limit_warning_header`.
+/// Same limiter config, non-bot UA: the second request must surface
+/// `X-PostHog-Rate-Limit-Warning`.
+#[tokio::test]
+async fn non_bot_response_carries_rate_limit_warning_header() -> Result<()> {
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.flags_ip_rate_limit_enabled = FlexBool(true);
+ config.flags_ip_rate_limit_log_only = FlexBool(true);
+ config.flags_ip_burst_size = 1;
+ config.flags_warn_capacity_ratio = 0.5;
+ config.flags_ip_replenish_rate = 0.1;
+
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let benign_ua =
+ Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0.0.0 Safari/537.36");
+
+ // Burn the burst token; second request hits the IP warn.
+ let first = post_flags(server.addr, "/flags", payload.clone(), benign_ua).await;
+ assert_eq!(
+ first.status(),
+ StatusCode::OK,
+ "first non-bot request must be admitted by the IP limiter",
+ );
+ let res = post_flags(server.addr, "/flags", payload, benign_ua).await;
+ assert_eq!(res.status(), StatusCode::OK);
+ assert!(
+ res.headers().get("X-PostHog-Rate-Limit-Warning").is_some(),
+ "non-bot path must surface X-PostHog-Rate-Limit-Warning when IP warn fires",
+ );
+
+ Ok(())
+}
+
+/// A bot hit on the `X-Original-Endpoint: decide` path must return the
+/// Decide envelope (`featureFlags`), not the Flags envelope (`flags` +
+/// `featureFlagPayloads`). v=1 → array; v=2 → object.
+#[rstest]
+#[case("1")]
+#[case("2")]
+#[tokio::test]
+async fn bot_via_decide_proxy_returns_decide_envelope(#[case] version: &str) -> Result<()> {
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags_with_version(
+ server.addr,
+ "/flags",
+ payload,
+ RequestOptions {
+ user_agent: Some(GOOGLEBOT_UA),
+ original_endpoint: Some("decide"),
+ ..Default::default()
+ },
+ version,
+ )
+ .await;
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body: serde_json::Value = res.json().await?;
+
+ // Asserting raw keys rather than deserializing into Decide*Response
+ // pins down the envelope shape independently of the FlagValue layout.
+ assert!(
+ body.get("featureFlags").is_some(),
+ "v={version}: bot via decide proxy must return a Decide envelope (no `featureFlags` key in {body})",
+ );
+ assert!(
+ body.get("flags").is_none(),
+ "v={version}: bot via decide proxy must NOT return the Flags envelope (found `flags` key in {body})",
+ );
+
+ let feature_flags = body
+ .get("featureFlags")
+ .expect("featureFlags key already asserted present");
+ match version {
+ "1" => {
+ assert!(
+ feature_flags.is_array(),
+ "v=1 Decide envelope requires `featureFlags` to be an array, got {feature_flags}",
+ );
+ assert_eq!(
+ feature_flags.as_array().map(|a| a.len()),
+ Some(0),
+ "bot short-circuit must return zero flags",
+ );
+ }
+ "2" => {
+ assert!(
+ feature_flags.is_object(),
+ "v=2 Decide envelope requires `featureFlags` to be an object, got {feature_flags}",
+ );
+ assert_eq!(
+ feature_flags.as_object().map(|o| o.len()),
+ Some(0),
+ "bot short-circuit must return zero flags",
+ );
+ }
+ other => panic!("unexpected version case {other}"),
+ }
+
+ // `supportedCompression` is only present on the minimal-response
+ // payload, so it distinguishes the short-circuit from a full-eval
+ // empty-flags result.
+ assert_eq!(
+ body.get("supportedCompression"),
+ Some(&json!(["gzip", "gzip-js"])),
+ "v={version}: response should carry the minimal-config marker",
+ );
+
+ Ok(())
+}
+
+/// A Googlebot UA must not exempt a client from per-IP rate limiting:
+/// sending `burst_size + 1` requests from one IP returns 429 on the last.
+#[tokio::test]
+async fn ip_rate_limit_fires_before_bot_check_for_spoofed_ua() -> Result<()> {
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.flags_ip_rate_limit_enabled = FlexBool(true);
+ config.flags_ip_rate_limit_log_only = FlexBool(false);
+ config.flags_ip_burst_size = 3;
+ // Slow refill so the burst is effectively the cap for the test.
+ config.flags_ip_replenish_rate = 0.1;
+
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ for i in 1..=3 {
+ let res = post_flags(server.addr, "/flags", payload.clone(), Some(GOOGLEBOT_UA)).await;
+ assert_eq!(
+ res.status(),
+ StatusCode::OK,
+ "request {i} with Googlebot UA should be admitted by the IP limiter",
+ );
+ }
+
+ let res = post_flags(server.addr, "/flags", payload, Some(GOOGLEBOT_UA)).await;
+ assert_eq!(
+ res.status(),
+ StatusCode::TOO_MANY_REQUESTS,
+ "burst+1 request with Googlebot UA must hit the IP rate limit",
+ );
+ let body: serde_json::Value = res.json().await?;
+ assert_eq!(body["code"], "rate_limit_exceeded");
+
+ Ok(())
+}
+
+/// In `LogOnly` mode (the prod default), a bot UA must not short-circuit.
+/// The request continues through the normal pipeline and gets a real
+/// evaluation back — observability of the classification is via the
+/// `flags_bot_detected_total{mode="log_only"}` counter and the
+/// `is_bot`/`bot_category`/`bot_source` fields on the canonical log line,
+/// neither of which is asserted here (the response shape is the
+/// user-visible behavior worth pinning end-to-end).
+///
+/// Both UA-driven and IP-driven classifications are covered so both code
+/// paths in `bot_detection::classify_request` are exercised.
+#[rstest]
+#[case::ua_signal(Some(GOOGLEBOT_UA), None)]
+#[case::ip_signal(Some(CLOUDFRONT_UA), Some(GOOGLEBOT_FORWARDED_IP))]
+#[tokio::test]
+async fn log_only_mode_stamps_but_does_not_short_circuit(
+ #[case] user_agent: Option<&'static str>,
+ #[case] forwarded_for: Option<&'static str>,
+) -> Result<()> {
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.bot_filter_mode = BotFilterMode::LogOnly;
+ let (server, token) = setup_server_with_a_flag(config).await;
+
+ let payload = json!({
+ "token": token,
+ "distinct_id": "any-id",
+ });
+
+ let res = post_flags_v1_with_options(
+ server.addr,
+ "/flags",
+ payload,
+ RequestOptions {
+ user_agent,
+ forwarded_for,
+ ..Default::default()
+ },
+ )
+ .await;
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body: LegacyFlagsResponse = res.json().await?;
+ assert!(
+ !body.feature_flags.is_empty(),
+ "LogOnly mode must let bot-shaped requests reach evaluation (ua={user_agent:?}, xff={forwarded_for:?})"
+ );
+
+ Ok(())
+}