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): add geoip subdivision properties to flag evaluation (#116663)

Thiago Salvatore2a2cf784eb91
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.md
index afdfde40aef3..194996479294 100644
--- a/docs/internal/feature-flags/rust-service-overview.md
+++ b/docs/internal/feature-flags/rust-service-overview.md
@@ -176,6 +176,8 @@ pub struct FlagRequest {
Unless `geoip_disable: true` is set in the body, `handler::properties::get_person_property_overrides` looks up the request IP in MaxMind and merges the resulting `$geoip_*` properties into `person_properties` before evaluation.
+The lookup also fills `$geoip_subdivision_1_code`, `$geoip_subdivision_1_name`, `$geoip_subdivision_2_code` and `$geoip_subdivision_2_name`. A team listed in `GEOIP_SUBDIVISIONS_EXCLUDED_TEAM_IDS` gets no subdivision values from the lookup.
+
GeoIP only fills gaps. A `$geoip_*` key present in the request body is left alone, and a JSON null counts as absent, since callers clear a property with `$unset`, so a null is a gap to fill.
This matters for server-side evaluation: the IP we geolocate is whoever made the HTTP request, so a call from a backend or an SSR render resolves the server's own location, not the end user's.
A caller that resolved geo itself (from `CF-IPCountry`, `X-Forwarded-For`, or similar) is the authority for those keys.
@@ -333,11 +335,12 @@ See [Behavioral cohorts](#behavioral-cohorts) for cohort membership cache settin
### Other
-| Variable | Default | Purpose |
-| ---------------------------------------- | -------------------------- | -------------------------------------- |
-| `MAXMIND_DB_PATH` | `share/GeoLite2-City.mmdb` | GeoIP database path |
-| `OPTIMIZE_EXPERIENCE_CONTINUITY_LOOKUPS` | `true` | Skip DB lookups for 100%-rollout flags |
-| `FLAGS_SESSION_REPLAY_QUOTA_CHECK` | `false` | Check session replay quota |
+| Variable | Default | Purpose |
+| ---------------------------------------- | -------------------------- | ------------------------------------------------------------------ |
+| `MAXMIND_DB_PATH` | `share/GeoLite2-City.mmdb` | GeoIP database path |
+| `GEOIP_SUBDIVISIONS_EXCLUDED_TEAM_IDS` | `none` | Teams that get no `$geoip_subdivision_*` values from the IP lookup |
+| `OPTIMIZE_EXPERIENCE_CONTINUITY_LOOKUPS` | `true` | Skip DB lookups for 100%-rollout flags |
+| `FLAGS_SESSION_REPLAY_QUOTA_CHECK` | `false` | Check session replay quota |
## Cache invalidation
diff --git a/rust/common/geoip/src/lib.rs b/rust/common/geoip/src/lib.rs
index 7fb27a4b86d4..2a105137bb67 100644
--- a/rust/common/geoip/src/lib.rs
+++ b/rust/common/geoip/src/lib.rs
@@ -52,29 +52,28 @@ impl GeoIpClient {
}
}
-const GEOIP_FIELDS: [(&str, &[&str]); 7] = [
- ("$geoip_country_name", &["country", "names", "en"]),
- ("$geoip_city_name", &["city", "names", "en"]),
- ("$geoip_country_code", &["country", "iso_code"]),
- ("$geoip_continent_name", &["continent", "names", "en"]),
- ("$geoip_continent_code", &["continent", "code"]),
- ("$geoip_postal_code", &["postal", "code"]),
- ("$geoip_time_zone", &["location", "time_zone"]),
+const GEOIP_FIELDS: [(&str, &str); 11] = [
+ ("$geoip_country_name", "/country/names/en"),
+ ("$geoip_city_name", "/city/names/en"),
+ ("$geoip_country_code", "/country/iso_code"),
+ ("$geoip_continent_name", "/continent/names/en"),
+ ("$geoip_continent_code", "/continent/code"),
+ ("$geoip_postal_code", "/postal/code"),
+ ("$geoip_time_zone", "/location/time_zone"),
+ // MaxMind orders `subdivisions` from the largest region to the smallest, so index 0 is level 1.
+ ("$geoip_subdivision_1_code", "/subdivisions/0/iso_code"),
+ ("$geoip_subdivision_1_name", "/subdivisions/0/names/en"),
+ ("$geoip_subdivision_2_code", "/subdivisions/1/iso_code"),
+ ("$geoip_subdivision_2_name", "/subdivisions/1/names/en"),
];
-fn get_nested_value<'a>(data: &'a Value, path: &[&str]) -> Option<&'a str> {
- let mut current = data;
- for &key in path {
- current = current.get(key)?;
- }
- current.as_str()
-}
-
fn extract_properties(city: &Value) -> HashMap<String, String> {
GEOIP_FIELDS
.iter()
- .filter_map(|&(field, path)| {
- get_nested_value(city, path).map(|value| (field.to_string(), value.to_string()))
+ .filter_map(|&(field, pointer)| {
+ city.pointer(pointer)
+ .and_then(Value::as_str)
+ .map(|value| (field.to_string(), value.to_string()))
})
.collect()
}
@@ -176,40 +175,9 @@ mod tests {
assert!(result.is_none());
}
- #[test]
- fn test_get_nested_value() {
- let data = json!({
- "country": {
- "names": {
- "en": "United States"
- }
- },
- "city": {
- "names": {
- "en": "New York"
- }
- },
- "postal": {
- "code": "10001"
- }
- });
-
- assert_eq!(
- get_nested_value(&data, &["country", "names", "en"]),
- Some("United States")
- );
- assert_eq!(
- get_nested_value(&data, &["city", "names", "en"]),
- Some("New York")
- );
- assert_eq!(get_nested_value(&data, &["postal", "code"]), Some("10001"));
- assert_eq!(get_nested_value(&data, &["country", "code"]), None);
- assert_eq!(get_nested_value(&data, &["nonexistent", "path"]), None);
- }
-
#[test]
fn test_extract_properties() {
- let city_data = json!({
+ let mut city_data = json!({
"country": {
"names": {
"en": "United States"
@@ -218,7 +186,7 @@ mod tests {
},
"city": {
"names": {
- "en": "New York"
+ "en": "Brooklyn"
}
},
"continent": {
@@ -232,7 +200,21 @@ mod tests {
},
"location": {
"time_zone": "America/New_York"
- }
+ },
+ "subdivisions": [
+ {
+ "iso_code": "NY",
+ "names": {
+ "en": "New York"
+ }
+ },
+ {
+ "iso_code": "KGS",
+ "names": {
+ "en": "Kings County"
+ }
+ }
+ ]
});
let properties = extract_properties(&city_data);
@@ -243,7 +225,7 @@ mod tests {
);
assert_eq!(
properties.get("$geoip_city_name"),
- Some(&"New York".to_string())
+ Some(&"Brooklyn".to_string())
);
assert_eq!(
properties.get("$geoip_country_code"),
@@ -265,6 +247,40 @@ mod tests {
properties.get("$geoip_time_zone"),
Some(&"America/New_York".to_string())
);
- assert_eq!(properties.len(), 7);
+ assert_eq!(
+ properties.get("$geoip_subdivision_1_code"),
+ Some(&"NY".to_string())
+ );
+ assert_eq!(
+ properties.get("$geoip_subdivision_1_name"),
+ Some(&"New York".to_string())
+ );
+ assert_eq!(
+ properties.get("$geoip_subdivision_2_code"),
+ Some(&"KGS".to_string())
+ );
+ assert_eq!(
+ properties.get("$geoip_subdivision_2_name"),
+ Some(&"Kings County".to_string())
+ );
+ assert_eq!(properties.len(), 11);
+
+ city_data["subdivisions"]
+ .as_array_mut()
+ .unwrap()
+ .truncate(1);
+ let properties = extract_properties(&city_data);
+
+ assert_eq!(
+ properties.get("$geoip_subdivision_1_code"),
+ Some(&"NY".to_string())
+ );
+ assert_eq!(
+ properties.get("$geoip_subdivision_1_name"),
+ Some(&"New York".to_string())
+ );
+ assert!(!properties.contains_key("$geoip_subdivision_2_code"));
+ assert!(!properties.contains_key("$geoip_subdivision_2_name"));
+ assert_eq!(properties.len(), 9);
}
}
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 333071adfd88..6b366b95fdea 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -628,6 +628,12 @@ pub struct Config {
#[envconfig(from = "MAXMIND_DB_PATH", default = "")]
pub maxmind_db_path: String,
+ // A server-side SDK that doesn't forward the end user's IP resolves its own server's
+ // region, and that value replaces the stored person property that a region flag would
+ // otherwise match on.
+ #[envconfig(from = "GEOIP_SUBDIVISIONS_EXCLUDED_TEAM_IDS", default = "none")]
+ pub geoip_subdivisions_excluded_team_ids: TeamIdCollection,
+
#[envconfig(default = "false")]
pub enable_metrics: bool,
@@ -1189,6 +1195,7 @@ impl Config {
billing_limiter_cache_ttl_secs: 5,
otel_export_timeout_secs: 3,
maxmind_db_path: "".to_string(),
+ geoip_subdivisions_excluded_team_ids: TeamIdCollection::None,
enable_metrics: false,
team_ids_to_track: TeamIdCollection::All,
cohort_cache_capacity_bytes: 268_435_456, // 256 MB
@@ -1281,6 +1288,12 @@ impl Config {
}
}
+ pub fn geoip_subdivisions_enabled_for(&self, team_id: i32) -> bool {
+ !self
+ .geoip_subdivisions_excluded_team_ids
+ .includes_team(team_id)
+ }
+
pub fn get_redis_reader_url(&self) -> &str {
if self.redis_reader_url.is_empty() {
&self.redis_url
@@ -1427,6 +1440,7 @@ mod tests {
// every legacy token without a mirror row while CI stays green, because the
// integration tests build their config from default_test_config() instead.
assert_eq!(config.accept_team_secret_tokens, FlexBool(true));
+ assert!(config.geoip_subdivisions_enabled_for(1));
}
#[test]
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index 6ff4be534ae5..4123a7de849b 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -253,7 +253,8 @@ async fn process_request_inner(
tracing::debug!("Flags filtered: {} flags found", filtered_flags.flags.len());
- let property_overrides = properties::prepare_overrides(&context, &request)?;
+ let property_overrides =
+ properties::prepare_overrides(&context, &request, team.id)?;
// Evaluate flags (this will return empty if is_flags_disabled is true)
let response = {
diff --git a/rust/feature-flags/src/handler/properties.rs b/rust/feature-flags/src/handler/properties.rs
index d74252ea8d89..683796abc86f 100644
--- a/rust/feature-flags/src/handler/properties.rs
+++ b/rust/feature-flags/src/handler/properties.rs
@@ -13,13 +13,18 @@ use std::{
use super::canonical_log::with_canonical_log;
use super::types::{RequestContext, RequestPropertyOverrides};
+const GEOIP_SUBDIVISION_PREFIX: &str = "$geoip_subdivision_";
+
pub fn prepare_overrides(
context: &RequestContext,
request: &FlagRequest,
+ team_id: i32,
) -> Result<RequestPropertyOverrides, FlagError> {
let geoip_disabled = request.geoip_disable.unwrap_or(false);
+ let include_subdivisions = context.state.config.geoip_subdivisions_enabled_for(team_id);
let person_property_overrides = get_person_property_overrides(
geoip_disabled,
+ include_subdivisions,
request.person_properties.clone(),
&context.ip,
&context.state.geoip,
@@ -66,6 +71,7 @@ fn record_geoip_divergence(
/// is the authority for those keys.
pub fn get_person_property_overrides(
geoip_disabled: bool,
+ include_subdivisions: bool,
person_properties: Option<HashMap<String, Value>>,
ip: &IpAddr,
geoip_service: &GeoIpClient,
@@ -74,9 +80,12 @@ pub fn get_person_property_overrides(
return person_properties;
}
- let geoip_props = geoip_service
+ let mut geoip_props = geoip_service
.get_geoip_properties(&ip.to_string())
.unwrap_or_default();
+ if !include_subdivisions {
+ geoip_props.retain(|key, _| !key.starts_with(GEOIP_SUBDIVISION_PREFIX));
+ }
if geoip_props.is_empty() {
return person_properties;
}
diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rs
index 21b903e277e1..ecae060d532d 100644
--- a/rust/feature-flags/src/handler/tests.rs
+++ b/rust/feature-flags/src/handler/tests.rs
@@ -162,6 +162,7 @@ fn test_geoip_person_property_overrides(
let result = properties::get_person_property_overrides(
geoip_disabled,
+ true,
person_properties,
&ip,
&geoip_service,
@@ -188,6 +189,55 @@ fn test_geoip_person_property_overrides(
}
}
+#[rstest]
+#[case::included(true)]
+#[case::excluded(false)]
+#[tokio::test]
+async fn test_geoip_subdivisions_follow_team_exclusion(#[case] include_subdivisions: bool) {
+ let geoip_service = create_test_geoip_service();
+ let ip = IpAddr::V4(Ipv4Addr::new(31, 28, 64, 3));
+ let lookup = geoip_service
+ .get_geoip_properties(&ip.to_string())
+ .unwrap_or_default();
+ assert!(
+ lookup.contains_key("$geoip_subdivision_1_code")
+ && lookup.contains_key("$geoip_subdivision_1_name"),
+ "the test needs an IP that resolves a subdivision"
+ );
+
+ let supplied = json!("XX");
+ let person_properties =
+ HashMap::from([("$geoip_subdivision_1_code".to_string(), supplied.clone())]);
+
+ let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), ip.to_string());
+ let (result, final_log) = run_with_canonical_log(log, async {
+ properties::get_person_property_overrides(
+ false,
+ include_subdivisions,
+ Some(person_properties),
+ &ip,
+ &geoip_service,
+ )
+ })
+ .await;
+ let result = result.expect("expected property overrides");
+
+ assert_eq!(result.get("$geoip_subdivision_1_code"), Some(&supplied));
+ // An excluded team's lookup value is dropped before the comparison, so it cannot diverge.
+ assert_eq!(
+ final_log.geoip_properties_differ_from_lookup,
+ include_subdivisions
+ );
+ for (key, value) in lookup
+ .iter()
+ .filter(|(key, _)| *key != "$geoip_subdivision_1_code")
+ {
+ let expected = (include_subdivisions || !key.starts_with("$geoip_subdivision_"))
+ .then(|| Value::String(value.clone()));
+ assert_eq!(result.get(key), expected.as_ref(), "{key}");
+ }
+}
+
#[test]
// A supplied null survives only when the IP resolves nothing: the fill loop at
// properties.rs only visits keys MaxMind returns. That leftover null reads as
@@ -206,6 +256,7 @@ fn test_supplied_geoip_null_survives_unresolvable_ip() {
let result = properties::get_person_property_overrides(
false,
+ true,
Some(person_properties),
&ip,
&geoip_service,
@@ -258,6 +309,7 @@ async fn test_canonical_log_records_geoip_divergence(
let (result, final_log) = run_with_canonical_log(log, async {
properties::get_person_property_overrides(
geoip_disabled,
+ true,
person_properties,
&ip,
&geoip_service,
@@ -518,6 +570,7 @@ fn test_get_person_property_overrides_ipv4() {
let geoip_service = create_test_geoip_service();
let result = properties::get_person_property_overrides(
false,
+ true,
Some(HashMap::new()),
&IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
&geoip_service,
@@ -532,6 +585,7 @@ fn test_get_person_property_overrides_ipv6() {
let geoip_service = create_test_geoip_service();
let result = properties::get_person_property_overrides(
false,
+ true,
Some(HashMap::new()),
&IpAddr::V6(Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888)),
&geoip_service,