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 flags requests from blocked domains and IPs (#121648)

Gustavo H. Strassburgerc80525c2f5ee
diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rs
index 715692451926..ef2c714eb5f6 100644
--- a/rust/feature-flags/src/api/endpoint.rs
+++ b/rust/feature-flags/src/api/endpoint.rs
@@ -5,8 +5,7 @@ use crate::{
errors::{ClientFacingError, FlagError},
flags_rate_limiter::RateLimitResult,
types::{
- ConfigResponse, FlagsQueryParams, FlagsResponse, FlagsResponseV4, LegacyFlagsResponse,
- ServiceResponse,
+ FlagsQueryParams, FlagsResponse, FlagsResponseV4, LegacyFlagsResponse, ServiceResponse,
},
},
config::BotFilterMode,
@@ -18,7 +17,8 @@ use crate::{
FLAG_BOT_DETECTED_COUNTER, FLAG_RATE_LIMIT_CHECK_TIME_MS, FLAG_TOKEN_EXTRACT_TIME_MS,
},
router,
- utils::{bot_detection, user_agent::UserAgentInfo},
+ team::request_blocklist,
+ utils::{bot_detection, forwarded_for, user_agent::UserAgentInfo},
};
// TODO: stream this instead
use axum::extract::{Extension, MatchedPath, Query, State};
@@ -28,8 +28,6 @@ use axum::Json;
use axum_client_ip::InsecureClientIp;
use bytes::Bytes;
use governor::clock;
-use serde_json;
-use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, OnceLock};
use tracing::Instrument;
@@ -48,56 +46,12 @@ fn extract_request_id(headers: &HeaderMap) -> Uuid {
/// Extracts client IP address from request headers, checking X-Forwarded-For first
/// then falling back to the direct client IP. Matches Python's get_ip_address function.
fn extract_client_ip(headers: &HeaderMap, fallback_ip: IpAddr) -> IpAddr {
- // Check X-Forwarded-For header first (case-insensitive)
- if let Some(forwarded_for) = headers.get("X-Forwarded-For") {
- if let Ok(forwarded_str) = forwarded_for.to_str() {
- // Take the first IP from the comma-separated list
- if let Some(first_ip) = forwarded_str.split(',').next() {
- let trimmed = first_ip.trim();
-
- // Strip port from IP address if present (Azure gateway compatibility)
- let ip_without_port = if trimmed.starts_with('[') {
- // IPv6 with port (e.g., "[::1]:8080")
- trimmed
- .split(']')
- .next()
- .and_then(|s| s.strip_prefix('['))
- .unwrap_or(trimmed)
- } else if trimmed.contains('.') {
- // Likely IPv4 - check for port after the last dot
- if let Some(colon_idx) = trimmed.rfind(':') {
- if let Some(last_dot_idx) = trimmed.rfind('.') {
- if colon_idx > last_dot_idx {
- // Port comes after the last dot, so this is IPv4:port
- &trimmed[..colon_idx]
- } else {
- // Colon before last dot? Malformed, return as-is
- trimmed
- }
- } else {
- // Has colon but no dot? Shouldn't happen for IPv4
- trimmed
- }
- } else {
- // No colon, just return the IP
- trimmed
- }
- } else {
- // No dots and no brackets - assume IPv6 without port
- // IPv6 can have colons as part of the address, so don't strip
- trimmed
- };
-
- // Try to parse the IP address
- if let Ok(parsed_ip) = ip_without_port.parse::<IpAddr>() {
- return parsed_ip;
- }
- }
- }
- }
-
- // Fall back to the direct client IP
- fallback_ip
+ headers
+ .get("X-Forwarded-For")
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| value.split(',').next())
+ .and_then(forwarded_for::parse_entry)
+ .unwrap_or(fallback_ip)
}
/// Updates the canonical log with rate limit info and returns the error for early return.
@@ -175,21 +129,7 @@ fn get_minimal_flags_response(
// decide/non-decide defaults.
let version_num = version.map(parse_version);
- let mut config = ConfigResponse::new();
- config.set(
- "supportedCompression",
- serde_json::json!(["gzip", "gzip-js"]),
- );
- config.set(
- "config",
- serde_json::json!({"enable_collect_everything": true}),
- );
- config.set("toolbarParams", serde_json::json!({}));
- config.set("isAuthenticated", serde_json::json!(false));
- config.set("sessionRecording", serde_json::json!(false));
-
- let mut response = FlagsResponse::new(false, HashMap::new(), None, request_id);
- response.config = config;
+ let response = FlagsResponse::minimal(request_id);
let (service_response, _) =
get_versioned_response(is_from_legacy_decide, version_num, v4_enabled, response).expect(
@@ -402,6 +342,8 @@ where
.map(|v| v == "decide")
.unwrap_or(false);
+ let origin_host = request_blocklist::origin_host(&headers);
+
// 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
@@ -410,6 +352,7 @@ where
request_id,
ip: ip_string.clone(),
user_agent: user_agent.map(|s| s.to_string()),
+ origin_host: origin_host.clone(),
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),
@@ -498,6 +441,7 @@ where
request_entered_at,
state: state.clone(),
ip,
+ origin_host,
headers: headers.clone(),
meta: modified_query_params,
body,
@@ -717,6 +661,7 @@ fn parse_request_start_ms(value: &str) -> Option<i64> {
mod tests {
use crate::api::types::Compression;
use rstest::rstest;
+ use std::collections::HashMap;
use super::*;
use axum::{
diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rs
index b605479df781..97c9d56f0758 100644
--- a/rust/feature-flags/src/api/types.rs
+++ b/rust/feature-flags/src/api/types.rs
@@ -367,6 +367,27 @@ impl FlagsResponse {
}
}
+ /// Empty flags with the minimal config that `posthog-js` needs to boot. Served to GET
+ /// requests and to requests the service refuses to evaluate (bots, blocked callers).
+ pub fn minimal(request_id: Uuid) -> Self {
+ let mut config = ConfigResponse::new();
+ config.set(
+ "supportedCompression",
+ serde_json::json!(["gzip", "gzip-js"]),
+ );
+ config.set(
+ "config",
+ serde_json::json!({"enable_collect_everything": true}),
+ );
+ config.set("toolbarParams", serde_json::json!({}));
+ config.set("isAuthenticated", serde_json::json!(false));
+ config.set("sessionRecording", serde_json::json!(false));
+
+ let mut response = Self::new(false, HashMap::new(), None, request_id);
+ response.config = config;
+ response
+ }
+
/// Test helper to create a FlagsResponse with a specific evaluated_at timestamp
#[cfg(test)]
pub fn with_evaluated_at(
diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rs
index 596057edbf99..2877fdb2a8bb 100644
--- a/rust/feature-flags/src/handler/canonical_log.rs
+++ b/rust/feature-flags/src/handler/canonical_log.rs
@@ -6,6 +6,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::team::request_blocklist::BlockReason;
use crate::utils::bot_detection::{BotCategory, BotSource};
use std::cell::RefCell;
use std::future::Future;
@@ -184,6 +185,9 @@ pub struct FlagsCanonicalLogLine {
// Request metadata (useful for SDK debugging)
pub user_agent: Option<String>,
+ /// Host of the `Origin` header, or of `Referer` without one. Shows support which site
+ /// calls `/flags` with a team's token. Log only: it is unbounded, so never a metric label.
+ pub origin_host: Option<String>,
pub lib: Option<String>,
pub lib_version: Option<String>,
pub api_version: Option<String>,
@@ -322,6 +326,10 @@ pub struct FlagsCanonicalLogLine {
pub bot_category: Option<BotCategory>,
/// Which signal fired (UA or IP), set iff `is_bot` is true.
pub bot_source: Option<BotSource>,
+
+ /// Set when the team's request blocklist refused the request before billing and
+ /// evaluation.
+ pub request_blocked_by: Option<BlockReason>,
}
impl Default for FlagsCanonicalLogLine {
@@ -331,6 +339,7 @@ impl Default for FlagsCanonicalLogLine {
ip: String::new(),
start_time: Instant::now(),
user_agent: None,
+ origin_host: None,
lib: None,
lib_version: None,
api_version: None,
@@ -376,6 +385,7 @@ impl Default for FlagsCanonicalLogLine {
is_bot: false,
bot_category: None,
bot_source: None,
+ request_blocked_by: None,
}
}
}
@@ -396,6 +406,10 @@ impl FlagsCanonicalLogLine {
// Truncate user_agent to prevent log bloat from very long headers (some bots send KB+).
// Note: distinct_id is already truncated at request parsing time (see MAX_DISTINCT_ID_LEN).
let user_agent = self.user_agent.as_deref().map(|ua| truncate_chars(ua, 512));
+ let origin_host = self
+ .origin_host
+ .as_deref()
+ .map(|host| truncate_chars(host, 512));
tracing::info!(
request_id = %self.request_id,
@@ -405,6 +419,7 @@ impl FlagsCanonicalLogLine {
anon_distinct_id = self.anon_distinct_id.as_deref(),
ip = %self.ip,
user_agent = user_agent,
+ origin_host = origin_host,
lib = self.lib.as_deref(),
lib_version = self.lib_version.as_deref(),
api_version = self.api_version.as_deref(),
@@ -451,6 +466,7 @@ impl FlagsCanonicalLogLine {
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()),
+ request_blocked_by = self.request_blocked_by.map(|r| r.as_str()),
"canonical_log_line"
);
}
@@ -730,6 +746,8 @@ 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.origin_host = Some("app.example.com".to_string());
+ log.request_blocked_by = Some(BlockReason::Host);
log.lib = Some("posthog-python".to_string());
log.lib_version = Some("1.0.0".to_string());
log.api_version = Some("3".to_string());
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index 9eb9057d9cd2..fc5471e62102 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -22,8 +22,12 @@ use crate::{
api::{errors::FlagError, types::FlagsResponse},
flags::{flag_matching::EvaluationType, flag_service::FlagService},
handler::phases::{Phase, PhaseGuard},
- metrics::consts::{FLAG_REQUESTS_COUNTER, FLAG_REQUESTS_LATENCY, FLAG_REQUEST_FAULTS_COUNTER},
+ metrics::consts::{
+ FLAG_REQUESTS_COUNTER, FLAG_REQUESTS_LATENCY, FLAG_REQUEST_BLOCKED_COUNTER,
+ FLAG_REQUEST_FAULTS_COUNTER,
+ },
team::team_models::Team,
+ utils::forwarded_for,
};
use std::collections::HashMap;
use tracing::{debug, instrument};
@@ -196,6 +200,32 @@ async fn process_request_inner(
tracing::debug!("Team fetched: team_id={}", team.id);
+ // Compute auth status once to avoid repeated header parsing and allocation.
+ let is_internal = authentication::is_internal_request(&context);
+
+ // Before billing, so a blocked caller never counts toward the team's flags usage.
+ // Internal requests skip the check. Django calls from a private pod IP without an
+ // `Origin`, so a team that blocks a private range would see every flag off in its own
+ // PostHog app.
+ // `context.ip` is the leftmost `X-Forwarded-For` entry, which the caller controls.
+ let block_reason = if is_internal {
+ None
+ } else {
+ team.request_block_reason(
+ context.origin_host.as_deref(),
+ forwarded_for::addresses(&context.headers).chain(std::iter::once(context.ip)),
+ )
+ };
+ if let Some(reason) = block_reason {
+ with_canonical_log(|log| log.request_blocked_by = Some(reason));
+ inc(
+ FLAG_REQUEST_BLOCKED_COUNTER,
+ &[("reason".to_string(), reason.as_str().to_string())],
+ 1,
+ );
+ return Ok(FlagsResponse::minimal(context.request_id));
+ }
+
// Early exit if flags are disabled
let flags_response = if request.is_flags_disabled() {
with_canonical_log(|log| log.flags_disabled = true);
@@ -228,9 +258,6 @@ async fn process_request_inner(
tracing::debug!("Distinct ID resolved: {}", distinct_id);
- // Compute auth status once to avoid repeated header parsing and allocation.
- let is_internal = authentication::is_internal_request(&context);
-
let override_defs = if is_internal {
request.override_flags_definitions.as_ref()
} else {
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index 09eaffe49f51..2bb53d4f685c 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -30,6 +30,9 @@ pub struct RequestContext {
/// Client IP
pub ip: IpAddr,
+ /// Host of the `Origin` header, or of `Referer` without one.
+ pub origin_host: Option<String>,
+
/// HTTP headers
pub headers: HeaderMap,
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index ffa69370793c..1ab75901a638 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -417,6 +417,11 @@ pub const LEGACY_TOKEN_MIRROR_SHADOW_COUNTER: &str = "flags_legacy_token_mirror_
// Loki.
pub const FLAG_BOT_DETECTED_COUNTER: &str = "flags_bot_detected_total";
+// Requests refused by the team's request blocklist. Labeled only by `reason`
+// (`host` or `ip`). The blocked host and IP are unbounded, so they go to the
+// canonical log line, never to a label.
+pub const FLAG_REQUEST_BLOCKED_COUNTER: &str = "flags_request_blocked_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/team/mod.rs b/rust/feature-flags/src/team/mod.rs
index 4e6fe1869f01..e5d116bf914a 100644
--- a/rust/feature-flags/src/team/mod.rs
+++ b/rust/feature-flags/src/team/mod.rs
@@ -1,2 +1,3 @@
+pub mod request_blocklist;
pub mod team_models;
pub mod team_operations;
diff --git a/rust/feature-flags/src/team/request_blocklist.rs b/rust/feature-flags/src/team/request_blocklist.rs
new file mode 100644
index 000000000000..edecb5530c2d
--- /dev/null
+++ b/rust/feature-flags/src/team/request_blocklist.rs
@@ -0,0 +1,242 @@
+//! A team's blocklist for `/flags` and `/decide` callers, matched by caller host or client IP.
+//!
+//! Django validates and normalizes both lists on write and puts them in the team metadata
+//! cache. This module parses the lists each time a team is deserialized, which happens on
+//! every request, so the matchers themselves do no parsing.
+
+use crate::utils::cidr::{parse_cidr, ParsedCidr};
+use axum::http::HeaderMap;
+use serde::{Deserialize, Serialize};
+use std::net::IpAddr;
+
+/// Why the blocklist refused a request. It is a metric label, so the set stays closed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BlockReason {
+ Host,
+ Ip,
+}
+
+impl BlockReason {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ BlockReason::Host => "host",
+ BlockReason::Ip => "ip",
+ }
+ }
+}
+
+/// The host of the `Origin` header, or of `Referer` when `Origin` is missing or opaque
+/// (browsers send `Origin: null` from sandboxed frames and `file://` pages).
+pub fn origin_host(headers: &HeaderMap) -> Option<String> {
+ ["origin", "referer"].into_iter().find_map(|name| {
+ let value = headers.get(name)?.to_str().ok()?;
+ let url = url::Url::parse(value).ok()?;
+ let host = url.host_str()?.trim_end_matches('.');
+ (!host.is_empty()).then(|| host.to_ascii_lowercase())
+ })
+}
+
+/// Hostnames. An entry blocks the host itself and all of its subdomains.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(from = "Vec<String>", into = "Vec<String>")]
+pub struct BlockedHosts(Vec<String>);
+
+impl From<Vec<String>> for BlockedHosts {
+ fn from(entries: Vec<String>) -> Self {
+ Self(
+ entries
+ .into_iter()
+ .map(|entry| entry.trim().trim_end_matches('.').to_ascii_lowercase())
+ .filter(|entry| !entry.is_empty())
+ .collect(),
+ )
+ }
+}
+
+impl From<BlockedHosts> for Vec<String> {
+ fn from(hosts: BlockedHosts) -> Self {
+ hosts.0
+ }
+}
+
+impl BlockedHosts {
+ /// `host` must already be lowercase, as [`origin_host`] returns it.
+ pub fn matches(&self, host: &str) -> bool {
+ self.0.iter().any(|entry| {
+ host == entry
+ || (host.len() > entry.len()
+ && host.ends_with(entry.as_str())
+ && host.as_bytes()[host.len() - entry.len() - 1] == b'.')
+ })
+ }
+}
+
+/// Single addresses or CIDR ranges. `entries` keeps the stored strings so the team
+/// serializes back to the cache shape it came from.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(from = "Vec<String>", into = "Vec<String>")]
+pub struct BlockedIps {
+ entries: Vec<String>,
+ ranges: Vec<ParsedCidr>,
+}
+
+impl From<Vec<String>> for BlockedIps {
+ fn from(entries: Vec<String>) -> Self {
+ let ranges = entries
+ .iter()
+ .filter_map(|entry| {
+ let parsed = parse_ip_entry(entry.trim());
+ if parsed.is_none() {
+ // Django rejects invalid entries on write, so this is a row written by
+ // another path. One bad entry must not disable the rest of the list.
+ // The list is parsed on every request, so a warning would repeat for
+ // every request while the bad entry stays stored.
+ tracing::debug!(entry = %entry, "skipping invalid blocked IP entry");
+ }
+ parsed
+ })
+ .collect();
+ Self { entries, ranges }
+ }
+}
+
+impl From<BlockedIps> for Vec<String> {
+ fn from(ips: BlockedIps) -> Self {
+ ips.entries
+ }
+}
+
+impl BlockedIps {
+ pub fn matches(&self, ip: IpAddr) -> bool {
+ self.ranges.iter().any(|range| range.contains(ip))
+ }
+
+ /// Consumes `ips` only when the list has a range, so a team without IP entries does
+ /// not pay for parsing the caller's addresses.
+ pub fn matches_any(&self, ips: impl IntoIterator<Item = IpAddr>) -> bool {
+ !self.ranges.is_empty() && ips.into_iter().any(|ip| self.matches(ip))
+ }
+}
+
+fn parse_ip_entry(entry: &str) -> Option<ParsedCidr> {
+ if entry.contains('/') {
+ return parse_cidr(entry);
+ }
+ entry.parse().ok().map(ParsedCidr::single)
+}
+
+/// Host first: when both match, `host` is the more specific answer for support.
+/// `client_ips` are all the addresses the request carries. The caller can add addresses
+/// but cannot remove the one our edge appended, so a match on any of them blocks.
+pub fn check(
+ hosts: &BlockedHosts,
+ ips: &BlockedIps,
+ origin_host: Option<&str>,
+ client_ips: impl IntoIterator<Item = IpAddr>,
+) -> Option<BlockReason> {
+ if origin_host.is_some_and(|host| hosts.matches(host)) {
+ return Some(BlockReason::Host);
+ }
+ if ips.matches_any(client_ips) {
+ return Some(BlockReason::Ip);
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::http::HeaderValue;
+ use rstest::rstest;
+
+ fn headers(pairs: &[(&'static str, &'static str)]) -> HeaderMap {
+ let mut map = HeaderMap::new();
+ for (name, value) in pairs {
+ map.insert(*name, HeaderValue::from_static(value));
+ }
+ map
+ }
+
+ fn hosts(entries: &[&str]) -> BlockedHosts {
+ BlockedHosts::from(entries.iter().map(|e| e.to_string()).collect::<Vec<_>>())
+ }
+
+ fn ips(entries: &[&str]) -> BlockedIps {
+ BlockedIps::from(entries.iter().map(|e| e.to_string()).collect::<Vec<_>>())
+ }
+
+ #[rstest]
+ #[case(&[("origin", "https://App.Example.com:8443")], Some("app.example.com"))]
+ #[case(&[("origin", "null"), ("referer", "https://example.com/page?q=1")], Some("example.com"))]
+ #[case(&[("referer", "https://www.example.org/")], Some("www.example.org"))]
+ #[case(&[("origin", "https://example.com"), ("referer", "https://example.org/")], Some("example.com"))]
+ #[case(&[("origin", "http://[2001:db8::1]:8000")], Some("[2001:db8::1]"))]
+ #[case(&[("origin", "not a url")], None)]
+ #[case(&[], None)]
+ fn origin_host_reads_origin_then_referer(
+ #[case] pairs: &[(&'static str, &'static str)],
+ #[case] expected: Option<&str>,
+ ) {
+ assert_eq!(origin_host(&headers(pairs)).as_deref(), expected);
+ }
+
+ #[rstest]
+ #[case("example.com", true)]
+ #[case("app.example.com", true)]
+ #[case("a.b.example.com", true)]
+ #[case("notexample.com", false)]
+ #[case("example.com.evil.test", false)]
+ #[case("example.org", false)]
+ fn host_entry_blocks_itself_and_subdomains(#[case] host: &str, #[case] blocked: bool) {
+ assert_eq!(hosts(&["Example.com."]).matches(host), blocked);
+ }
+
+ #[rstest]
+ #[case("203.0.113.7", "203.0.113.7", true)]
+ #[case("203.0.113.7", "203.0.113.8", false)]
+ #[case("198.51.100.0/24", "198.51.100.255", true)]
+ #[case("198.51.100.0/24", "198.51.101.0", false)]
+ #[case("2001:db8::1", "2001:db8::1", true)]
+ #[case("2001:db8::1", "2001:db8::2", false)]
+ #[case("2001:db8:abcd::/48", "2001:db8:abcd:12::1", true)]
+ #[case("2001:db8:abcd::/48", "2001:db8:abce::1", false)]
+ #[case("203.0.113.7", "::ffff:203.0.113.7", true)]
+ #[case("198.51.100.0/24", "2001:db8::1", false)]
+ fn ip_entry_matches_addresses_and_ranges(
+ #[case] entry: &str,
+ #[case] client_ip: &str,
+ #[case] blocked: bool,
+ ) {
+ assert_eq!(ips(&[entry]).matches(client_ip.parse().unwrap()), blocked);
+ }
+
+ #[test]
+ fn invalid_ip_entry_is_skipped_and_the_rest_still_match() {
+ let list = ips(&["not-an-ip", "203.0.113.0/40", "198.51.100.9"]);
+
+ assert!(list.matches("198.51.100.9".parse().unwrap()));
+ assert!(!list.matches("203.0.113.1".parse().unwrap()));
+ }
+
+ #[rstest]
+ #[case(Some("app.example.com"), &["203.0.113.7"], Some(BlockReason::Host))]
+ #[case(Some("example.org"), &["203.0.113.7"], Some(BlockReason::Ip))]
+ #[case(None, &["203.0.113.7"], Some(BlockReason::Ip))]
+ #[case(None, &["192.0.2.1", "203.0.113.7"], Some(BlockReason::Ip))]
+ #[case(Some("example.org"), &["198.51.100.1"], None)]
+ #[case(None, &["198.51.100.1", "192.0.2.1"], None)]
+ fn check_reports_host_before_ip(
+ #[case] host: Option<&str>,
+ #[case] client_ips: &[&str],
+ #[case] expected: Option<BlockReason>,
+ ) {
+ let reason = check(
+ &hosts(&["example.com"]),
+ &ips(&["203.0.113.7"]),
+ host,
+ client_ips.iter().map(|ip| ip.parse().unwrap()),
+ );
+
+ assert_eq!(reason, expected);
+ }
+}
diff --git a/rust/feature-flags/src/team/team_models.rs b/rust/feature-flags/src/team/team_models.rs
index 885ec52e2a8e..882449d06bd9 100644
--- a/rust/feature-flags/src/team/team_models.rs
+++ b/rust/feature-flags/src/team/team_models.rs
@@ -1,7 +1,9 @@
+use crate::team::request_blocklist::{self, BlockReason, BlockedHosts, BlockedIps};
use common_types::{TeamId, TeamIdentifier};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use sqlx::types::{Json, Uuid};
+use std::net::IpAddr;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, sqlx::Type)]
#[serde(transparent)]
@@ -78,6 +80,31 @@ pub struct Team {
// Cache entries written before this field existed retain legacy matching.
#[serde(default)]
pub property_matching_version: PropertyMatchingVersion,
+ // Sourced from the customer-editable TeamFeatureFlagPolicyConfig extension. Cache entries
+ // written before these fields existed deserialize to empty lists, which block nothing.
+ #[serde(default)]
+ #[sqlx(try_from = "Vec<String>")]
+ pub flags_blocked_hosts: BlockedHosts,
+ #[serde(default)]
+ #[sqlx(try_from = "Vec<String>")]
+ pub flags_blocked_ips: BlockedIps,
+}
+
+impl Team {
+ /// The reason this team's request blocklist refuses a caller with this host and these
+ /// client IPs, or `None` when the caller is allowed.
+ pub fn request_block_reason(
+ &self,
+ origin_host: Option<&str>,
+ client_ips: impl IntoIterator<Item = IpAddr>,
+ ) -> Option<BlockReason> {
+ request_blocklist::check(
+ &self.flags_blocked_hosts,
+ &self.flags_blocked_ips,
+ origin_host,
+ client_ips,
+ )
+ }
}
fn default_timezone() -> String {
@@ -136,5 +163,36 @@ mod tests {
team.property_matching_version,
PropertyMatchingVersion::LEGACY
);
+ assert_eq!(
+ team.request_block_reason(Some("example.com"), ["203.0.113.7".parse().unwrap()]),
+ None
+ );
+ }
+
+ #[test]
+ fn test_blocklist_survives_a_cache_round_trip() {
+ let cached = serde_json::json!({
+ "id": 1,
+ "name": "test team",
+ "api_token": "test_token",
+ "uuid": Uuid::new_v4().to_string(),
+ "flags_blocked_hosts": ["example.com"],
+ "flags_blocked_ips": ["203.0.113.0/24", "not-an-ip"],
+ });
+
+ let team: Team = serde_json::from_value(cached).expect("cache blob must deserialize");
+ let reserialized: Team =
+ serde_json::from_value(serde_json::to_value(&team).unwrap()).unwrap();
+
+ assert_eq!(reserialized.flags_blocked_ips, team.flags_blocked_ips);
+ assert_eq!(
+ reserialized
+ .request_block_reason(Some("app.example.com"), ["198.51.100.1".parse().unwrap()]),
+ Some(BlockReason::Host)
+ );
+ assert_eq!(
+ reserialized.request_block_reason(None, ["203.0.113.9".parse().unwrap()]),
+ Some(BlockReason::Ip)
+ );
}
}
diff --git a/rust/feature-flags/src/team/team_operations.rs b/rust/feature-flags/src/team/team_operations.rs
index 1e46b435ae97..077c3ce95bf0 100644
--- a/rust/feature-flags/src/team/team_operations.rs
+++ b/rust/feature-flags/src/team/team_operations.rs
@@ -51,7 +51,15 @@ const TEAM_COLUMNS: &str = "
COALESCE(
(SELECT property_matching_version FROM feature_flags_teamfeatureflagsconfig WHERE team_id = posthog_team.id),
1
- )::smallint AS property_matching_version
+ )::smallint AS property_matching_version,
+ COALESCE(
+ (SELECT blocked_hosts FROM feature_flags_teamfeatureflagpolicyconfig WHERE team_id = posthog_team.id),
+ '{}'
+ )::text[] AS flags_blocked_hosts,
+ COALESCE(
+ (SELECT blocked_ips FROM feature_flags_teamfeatureflagpolicyconfig WHERE team_id = posthog_team.id),
+ '{}'
+ )::text[] AS flags_blocked_ips
";
impl Team {
@@ -115,6 +123,7 @@ impl Team {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::team::request_blocklist::BlockReason;
use crate::team::team_models::PropertyMatchingVersion;
use crate::utils::test_utils::{
insert_new_team_in_redis, setup_redis_client, setup_team_hypercache_reader, TestContext,
@@ -363,4 +372,50 @@ mod tests {
PropertyMatchingVersion::EXPLICIT
);
}
+
+ #[tokio::test]
+ async fn test_fetch_team_reflects_feature_flag_policy_blocklist() {
+ let context = TestContext::new(None).await;
+ let team = context
+ .insert_new_team(None)
+ .await
+ .expect("Failed to insert team in pg");
+
+ let mut conn = get_connection_with_metrics(
+ &context.non_persons_reader,
+ "non_persons_reader",
+ "test_insert_team_feature_flag_policy_config",
+ )
+ .await
+ .expect("Failed to get connection");
+
+ sqlx::query(
+ "INSERT INTO feature_flags_teamfeatureflagpolicyconfig \
+ (team_id, require_tags, blocked_hosts, blocked_ips) \
+ VALUES ($1, false, ARRAY['example.com'], ARRAY['203.0.113.0/24'])",
+ )
+ .bind(team.id)
+ .execute(&mut *conn)
+ .await
+ .expect("Failed to insert TeamFeatureFlagPolicyConfig row");
+
+ let by_token = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
+ .await
+ .expect("Failed to fetch team by token from pg");
+ let by_id = Team::from_pg_by_id(context.non_persons_reader.clone(), team.id)
+ .await
+ .expect("Failed to fetch team by id from pg");
+
+ for team_from_pg in [by_token, by_id] {
+ assert_eq!(
+ team_from_pg
+ .request_block_reason(Some("app.example.com"), ["192.0.2.1".parse().unwrap()]),
+ Some(BlockReason::Host)
+ );
+ assert_eq!(
+ team_from_pg.request_block_reason(None, ["203.0.113.9".parse().unwrap()]),
+ Some(BlockReason::Ip)
+ );
+ }
+ }
}
diff --git a/rust/feature-flags/src/utils/bot_detection.rs b/rust/feature-flags/src/utils/bot_detection.rs
index 2d2934cb39c0..ad4f91f75bab 100644
--- a/rust/feature-flags/src/utils/bot_detection.rs
+++ b/rust/feature-flags/src/utils/bot_detection.rs
@@ -3,6 +3,7 @@
//! covers the case where an upstream proxy (e.g. CloudFront) rewrites the
//! User-Agent and only the source IP is usable.
+use crate::utils::cidr::{normalize, parse_cidr};
use aho_corasick::{AhoCorasick, MatchKind};
use std::net::IpAddr;
use std::sync::LazyLock;
@@ -374,68 +375,6 @@ fn build_ranges(cidrs: &[(String, BotCategory)]) -> BotIpRanges {
}
}
-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> {
@@ -768,31 +707,6 @@ mod tests {
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
diff --git a/rust/feature-flags/src/utils/cidr.rs b/rust/feature-flags/src/utils/cidr.rs
new file mode 100644
index 000000000000..3e7d27175402
--- /dev/null
+++ b/rust/feature-flags/src/utils/cidr.rs
@@ -0,0 +1,130 @@
+use std::net::IpAddr;
+
+/// An inclusive `[start, end]` range. IPv4 ranges widen to `u128` so both families share
+/// one representation.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct ParsedCidr {
+ pub(crate) start: u128,
+ pub(crate) end: u128,
+ pub(crate) is_v4: bool,
+}
+
+impl ParsedCidr {
+ pub(crate) fn single(ip: IpAddr) -> Self {
+ match ip {
+ IpAddr::V4(v4) => {
+ let value = u128::from(u32::from(v4));
+ Self {
+ start: value,
+ end: value,
+ is_v4: true,
+ }
+ }
+ IpAddr::V6(v6) => {
+ let value = u128::from(v6);
+ Self {
+ start: value,
+ end: value,
+ is_v4: false,
+ }
+ }
+ }
+ }
+
+ /// IPv4-mapped IPv6 addresses match IPv4 ranges, the same as the bot lookup.
+ pub(crate) fn contains(&self, ip: IpAddr) -> bool {
+ let value = match normalize(ip) {
+ IpAddr::V4(v4) if self.is_v4 => u128::from(u32::from(v4)),
+ IpAddr::V6(v6) if !self.is_v4 => u128::from(v6),
+ _ => return false,
+ };
+ self.start <= value && value <= self.end
+ }
+}
+
+pub(crate) 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.
+pub(crate) fn normalize(ip: IpAddr) -> IpAddr {
+ match ip {
+ IpAddr::V6(v6) => v6
+ .to_ipv4_mapped()
+ .map(IpAddr::V4)
+ .unwrap_or(IpAddr::V6(v6)),
+ v4 => v4,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rstest::rstest;
+
+ #[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());
+ }
+}
diff --git a/rust/feature-flags/src/utils/forwarded_for.rs b/rust/feature-flags/src/utils/forwarded_for.rs
new file mode 100644
index 000000000000..3ff830f34cc6
--- /dev/null
+++ b/rust/feature-flags/src/utils/forwarded_for.rs
@@ -0,0 +1,114 @@
+//! Addresses in the `X-Forwarded-For` header.
+//!
+//! Each proxy appends the address of its peer, so the entries on the right come from our
+//! edge and the entries on the left come from the caller, who can write any value there.
+
+use axum::http::{HeaderMap, HeaderName};
+use std::net::IpAddr;
+
+const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
+
+/// The chains that reach the flags service have a few entries, and a caller can send any number.
+pub const MAX_FORWARDED_ADDRESSES: usize = 20;
+
+/// Parses one entry. An entry can carry a port (`203.0.113.7:8080`, `[2001:db8::1]:8080`),
+/// which some gateways (Azure) add.
+pub fn parse_entry(entry: &str) -> Option<IpAddr> {
+ let trimmed = entry.trim();
+
+ let ip_without_port = if trimmed.starts_with('[') {
+ // IPv6 with port (e.g., "[::1]:8080")
+ trimmed
+ .split(']')
+ .next()
+ .and_then(|s| s.strip_prefix('['))
+ .unwrap_or(trimmed)
+ } else if trimmed.contains('.') {
+ // Likely IPv4 - check for port after the last dot
+ match (trimmed.rfind(':'), trimmed.rfind('.')) {
+ // Port comes after the last dot, so this is IPv4:port
+ (Some(colon_idx), Some(last_dot_idx)) if colon_idx > last_dot_idx => {
+ &trimmed[..colon_idx]
+ }
+ _ => trimmed,
+ }
+ } else {
+ // No dots and no brackets - assume IPv6 without port
+ // IPv6 can have colons as part of the address, so don't strip
+ trimmed
+ };
+
+ ip_without_port.parse().ok()
+}
+
+/// Right to left, so that padding on the left cannot push the entries our edge appended
+/// past [`MAX_FORWARDED_ADDRESSES`]. The header lookup waits for the first `next`, so a
+/// caller that never reads the addresses pays nothing.
+pub fn addresses(headers: &HeaderMap) -> impl Iterator<Item = IpAddr> + '_ {
+ std::iter::once_with(|| headers.get_all(X_FORWARDED_FOR))
+ .flat_map(|values| values.into_iter().rev())
+ // Split the bytes, not a `str`, because a caller can add non-ASCII bytes to the
+ // value that our edge appends to, and `to_str` would reject the whole value.
+ .flat_map(|value| value.as_bytes().rsplit(|&byte| byte == b','))
+ .take(MAX_FORWARDED_ADDRESSES)
+ .filter_map(|entry| parse_entry(std::str::from_utf8(entry).ok()?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::http::HeaderValue;
+ use rstest::rstest;
+
+ fn ips(entries: &[&str]) -> Vec<IpAddr> {
+ entries.iter().map(|e| e.parse().unwrap()).collect()
+ }
+
+ #[rstest]
+ #[case::single(&["203.0.113.7"], &["203.0.113.7"])]
+ #[case::right_to_left(&["192.0.2.1, 203.0.113.7,10.0.0.1"], &["10.0.0.1", "203.0.113.7", "192.0.2.1"])]
+ #[case::later_header_first(&["192.0.2.1", "203.0.113.7"], &["203.0.113.7", "192.0.2.1"])]
+ #[case::ports(&["[2001:db8::1]:8080, 203.0.113.7:443"], &["203.0.113.7", "2001:db8::1"])]
+ #[case::invalid_entries_skipped(&["junk, , 203.0.113.7"], &["203.0.113.7"])]
+ #[case::empty(&[""], &[])]
+ fn addresses_reads_entries_from_the_right(
+ #[case] values: &[&'static str],
+ #[case] expected: &[&str],
+ ) {
+ let mut headers = HeaderMap::new();
+ for value in values {
+ headers.append("x-forwarded-for", HeaderValue::from_static(value));
+ }
+
+ assert_eq!(addresses(&headers).collect::<Vec<_>>(), ips(expected));
+ }
+
+ #[test]
+ fn addresses_keeps_appended_entries_when_the_left_side_is_padded() {
+ let padding = vec!["192.0.2.1"; 100].join(", ");
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "x-forwarded-for",
+ HeaderValue::from_str(&format!("{padding}, 203.0.113.7,10.0.0.1")).unwrap(),
+ );
+
+ let read = addresses(&headers).collect::<Vec<_>>();
+
+ assert_eq!(read.len(), MAX_FORWARDED_ADDRESSES);
+ assert_eq!(read[..2], ips(&["10.0.0.1", "203.0.113.7"]));
+ }
+
+ #[test]
+ fn addresses_reads_entries_next_to_non_ascii_bytes() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "x-forwarded-for",
+ HeaderValue::from_bytes(b"\xff\xfe, 203.0.113.7").unwrap(),
+ );
+
+ assert_eq!(
+ addresses(&headers).collect::<Vec<_>>(),
+ ips(&["203.0.113.7"])
+ );
+ }
+}
diff --git a/rust/feature-flags/src/utils/mod.rs b/rust/feature-flags/src/utils/mod.rs
index 9ac56c80408d..2a6f97a4bce9 100644
--- a/rust/feature-flags/src/utils/mod.rs
+++ b/rust/feature-flags/src/utils/mod.rs
@@ -1,6 +1,8 @@
pub mod bot_detection;
pub mod bounded_json5;
+pub mod cidr;
pub mod deadline;
+pub mod forwarded_for;
pub mod graph_utils;
pub mod json_size;
#[cfg(test)]
diff --git a/rust/feature-flags/tests/test_request_blocklist.rs b/rust/feature-flags/tests/test_request_blocklist.rs
new file mode 100644
index 000000000000..e9c33285decc
--- /dev/null
+++ b/rust/feature-flags/tests/test_request_blocklist.rs
@@ -0,0 +1,190 @@
+use anyhow::Result;
+use reqwest::header::CONTENT_TYPE;
+use reqwest::StatusCode;
+use rstest::rstest;
+use serde_json::{json, Value};
+
+use feature_flags::config::DEFAULT_TEST_CONFIG;
+use feature_flags::flags::flag_analytics::{current_bucket, get_team_request_key};
+use feature_flags::flags::flag_request::FlagRequestType;
+use feature_flags::team::request_blocklist::{BlockedHosts, BlockedIps};
+use feature_flags::team::team_models::Team;
+use feature_flags::utils::test_utils::{
+ insert_config_in_hypercache, insert_flags_for_team_in_redis, insert_new_team_in_redis,
+ setup_redis_client, update_team_in_hypercache, TestContext,
+};
+
+use crate::common::*;
+
+pub mod common;
+
+const INTERNAL_TOKEN: &str = "internal-test-token";
+
+/// Server with one flag for a team that blocks `example.com` and a mix of IPv4 and IPv6
+/// entries, so a test can tell the blocked response (no flags) from evaluation (the flag).
+/// The cached remote config enables session recording, so a `config=true` response built
+/// from it differs from the minimal response.
+async fn setup_server_with_blocklist() -> Result<(ServerHandle, Team)> {
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.internal_request_token = Some(INTERNAL_TOKEN.to_string());
+ let client = setup_redis_client(Some(config.redis_url.clone())).await;
+ let mut team = insert_new_team_in_redis(client.clone()).await.unwrap();
+ team.flags_blocked_hosts = BlockedHosts::from(vec!["example.com".to_string()]);
+ team.flags_blocked_ips = BlockedIps::from(vec![
+ "203.0.113.7".to_string(),
+ "198.51.100.0/24".to_string(),
+ "2001:db8:abcd::/48".to_string(),
+ ]);
+ update_team_in_hypercache(client.clone(), &team).await?;
+ 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();
+ insert_config_in_hypercache(
+ client.clone(),
+ &team.api_token,
+ json!({
+ "supportedCompression": ["gzip", "gzip-js"],
+ "sessionRecording": {"endpoint": "/s/"},
+ }),
+ )
+ .await?;
+ let server = ServerHandle::for_config(config).await;
+ Ok((server, team))
+}
+
+async fn post(
+ server: &ServerHandle,
+ path: &str,
+ token: &str,
+ version: &str,
+ headers: &[(&str, &str)],
+) -> reqwest::Response {
+ let mut req = reqwest::Client::new()
+ .post(format!("http://{}{}?v={}", server.addr, path, version))
+ .header(CONTENT_TYPE, "application/json")
+ .body(json!({"token": token, "distinct_id": "any-id"}).to_string());
+ for (name, value) in headers {
+ req = req.header(*name, *value);
+ }
+ req.send().await.expect("failed to send request")
+}
+
+fn assert_minimal_response(body: &Value, flags_key: &str) {
+ assert_eq!(
+ body[flags_key],
+ json!({}),
+ "blocked request evaluated flags"
+ );
+ // An unblocked response either omits `sessionRecording` or copies the enabled object
+ // from the cached remote config. Only the minimal response sets it to `false`.
+ assert_eq!(body["sessionRecording"], json!(false));
+ assert_eq!(body["supportedCompression"], json!(["gzip", "gzip-js"]));
+}
+
+#[rstest]
+#[case::origin_host("/flags", &[("Origin", "https://example.com")])]
+#[case::origin_subdomain("/flags", &[("Origin", "https://app.example.com:8443")])]
+#[case::referer_fallback("/flags", &[("Origin", "null"), ("Referer", "https://www.example.com/page")])]
+#[case::ipv4_address("/flags", &[("X-Forwarded-For", "203.0.113.7")])]
+#[case::ipv4_cidr("/flags", &[("X-Forwarded-For", "198.51.100.42")])]
+#[case::ipv6_cidr("/flags", &[("X-Forwarded-For", "2001:db8:abcd:12::1")])]
+#[case::blocked_ip_behind_spoofed_entry("/flags", &[("X-Forwarded-For", "192.0.2.1, 203.0.113.7")])]
+#[case::decide_host("/decide", &[("Origin", "https://example.com")])]
+#[case::decide_ip("/decide", &[("X-Forwarded-For", "203.0.113.7")])]
+#[tokio::test]
+async fn blocked_caller_gets_minimal_response(
+ #[case] path: &str,
+ #[case] headers: &[(&str, &str)],
+) -> Result<()> {
+ let (server, team) = setup_server_with_blocklist().await?;
+
+ let res = post(&server, path, &team.api_token, "2", headers).await;
+
+ assert_eq!(res.status(), StatusCode::OK);
+ assert_minimal_response(&res.json().await?, "flags");
+ Ok(())
+}
+
+#[tokio::test]
+async fn blocked_caller_through_legacy_decide_proxy_gets_minimal_response() -> Result<()> {
+ let (server, team) = setup_server_with_blocklist().await?;
+
+ let res = post(
+ &server,
+ "/decide",
+ &team.api_token,
+ "2",
+ &[
+ ("X-Original-Endpoint", "decide"),
+ ("Origin", "https://example.com"),
+ ],
+ )
+ .await;
+
+ assert_eq!(res.status(), StatusCode::OK);
+ assert_minimal_response(&res.json().await?, "featureFlags");
+ Ok(())
+}
+
+#[rstest]
+#[case::other_host(&[("Origin", "https://example.org"), ("X-Forwarded-For", "192.0.2.1")])]
+#[case::lookalike_host(&[("Origin", "https://notexample.com"), ("X-Forwarded-For", "192.0.2.1")])]
+#[case::ipv4_outside_cidr(&[("X-Forwarded-For", "198.51.101.1")])]
+#[case::ipv6_outside_cidr(&[("X-Forwarded-For", "2001:db8:abce::1")])]
+#[case::no_origin(&[])]
+#[case::internal_request_from_blocked_ip(&[("Authorization", "Bearer internal-test-token"), ("X-Forwarded-For", "203.0.113.7")])]
+#[tokio::test]
+async fn unblocked_caller_reaches_evaluation(#[case] headers: &[(&str, &str)]) -> Result<()> {
+ let (server, team) = setup_server_with_blocklist().await?;
+
+ let res = post(&server, "/flags", &team.api_token, "1", headers).await;
+
+ assert_eq!(res.status(), StatusCode::OK);
+ let body: Value = res.json().await?;
+ assert!(
+ body["featureFlags"].get("flag1").is_some(),
+ "unblocked request should evaluate flags; got {body}"
+ );
+ Ok(())
+}
+
+#[rstest]
+#[case::blocked(&[("Origin", "https://example.com")], false)]
+#[case::unblocked(&[("Origin", "https://example.org")], true)]
+#[tokio::test]
+async fn only_unblocked_caller_is_billed(
+ #[case] headers: &[(&str, &str)],
+ #[case] billed: bool,
+) -> Result<()> {
+ let (server, team) = setup_server_with_blocklist().await?;
+ let client = setup_redis_client(Some(DEFAULT_TEST_CONFIG.redis_url.clone())).await;
+ let billing_key = get_team_request_key(team.id, FlagRequestType::Decide);
+ client.del(billing_key.clone()).await.unwrap();
+
+ // Bracket the request: the record lands in whichever 2-minute bucket it crosses.
+ let bucket_before = current_bucket();
+ let res = post(&server, "/flags", &team.api_token, "2", headers).await;
+ assert_eq!(res.status(), StatusCode::OK);
+ let bucket_after = current_bucket();
+
+ if billed {
+ let counter = poll_for_billing_counter_across_buckets(
+ &client,
+ &billing_key,
+ bucket_before,
+ bucket_after,
+ )
+ .await;
+ assert_eq!(counter, "1");
+ } else {
+ // Wait ~5 flush windows so a delayed first tick cannot hide an erroneous `record()`.
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ for bucket in bucket_before..=bucket_after {
+ let counter = client.hget(billing_key.clone(), bucket.to_string()).await;
+ assert!(counter.is_err(), "blocked request was billed: {counter:?}");
+ }
+ }
+ Ok(())
+}