use super::geo::CountryLookup;
use crate::error::{GarrisonError, GarrisonResult};
use crate::strategy::firewall::{FirewallContext, GarrisonFirewallStrategy};
use async_trait::async_trait;
use std::sync::Arc;
#[derive(Debug, Clone, Default)]
pub struct GeoIPConfig {
pub allowed_countries: Vec<String>,
pub blocked_countries: Vec<String>,
}
pub struct GeoIPStrategy {
config: GeoIPConfig,
country_lookup: Arc<dyn CountryLookup>,
}
impl GeoIPStrategy {
pub fn new(config: GeoIPConfig, country_lookup: Arc<dyn CountryLookup>) -> Self {
Self {
config,
country_lookup,
}
}
fn is_in_list(country: &str, list: &[String]) -> bool {
list.iter().any(|c| c.eq_ignore_ascii_case(country))
}
}
fn mask_ip(ip: &str) -> String {
if ip.contains(':') {
let parts: Vec<&str> = ip.split(':').collect();
if parts.len() >= 3 {
format!("{}:{}:{}:*", parts[0], parts[1], parts[2])
} else {
"*:*:*".to_string()
}
} else {
let parts: Vec<&str> = ip.split('.').collect();
if parts.len() >= 2 {
format!("{}.{}.*.*", parts[0], parts[1])
} else {
"*.*.*.*".to_string()
}
}
}
#[async_trait]
impl GarrisonFirewallStrategy for GeoIPStrategy {
async fn check(&self, ctx: &FirewallContext) -> GarrisonResult<()> {
let country = self.country_lookup.lookup_country(&ctx.ip).await?;
if !self.config.allowed_countries.is_empty() {
match country.as_deref() {
Some(c) if Self::is_in_list(c, &self.config.allowed_countries) => Ok(()),
Some(c) => {
let detail = format!("{} not in {:?}", c, self.config.allowed_countries);
Err(GarrisonError::FirewallBlocked(format!(
"firewall-geoip-not-in-whitelist::{}::{}",
mask_ip(&ctx.ip),
detail
)))
},
None => {
let detail = format!("{:?}", self.config.allowed_countries);
Err(GarrisonError::FirewallBlocked(format!(
"firewall-geoip-no-country::{}::{}",
mask_ip(&ctx.ip),
detail
)))
},
}
} else if !self.config.blocked_countries.is_empty() {
match country.as_deref() {
Some(c) if Self::is_in_list(c, &self.config.blocked_countries) => {
let detail = format!("{} in {:?}", c, self.config.blocked_countries);
Err(GarrisonError::FirewallBlocked(format!(
"firewall-geoip-in-blacklist::{}::{}",
mask_ip(&ctx.ip),
detail
)))
},
_ => Ok(()),
}
} else {
Ok(())
}
}
}
inventory::submit! {
crate::strategy::firewall::StrategyRegistration {
name: "geoip",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::strategy::firewall::CountryLookup;
use async_trait::async_trait;
use std::collections::HashMap;
struct MockCountryLookup {
map: HashMap<String, String>,
}
impl MockCountryLookup {
fn new() -> Self {
Self {
map: HashMap::new(),
}
}
fn with(mut self, ip: &str, country: &str) -> Self {
self.map.insert(ip.to_string(), country.to_string());
self
}
}
#[async_trait]
impl CountryLookup for MockCountryLookup {
async fn lookup_country(&self, ip: &str) -> GarrisonResult<Option<String>> {
Ok(self.map.get(ip).cloned())
}
}
#[tokio::test]
async fn geoip_blocks_when_not_in_allowed_countries() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "US"));
let config = GeoIPConfig {
allowed_countries: vec!["CN".into()],
blocked_countries: vec![],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"US 不在白名单 [CN] 应拦截,实际: {:?}",
result
);
}
#[tokio::test]
async fn geoip_blocks_when_in_blocked_countries() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "XX"));
let config = GeoIPConfig {
allowed_countries: vec![],
blocked_countries: vec!["XX".into()],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"XX 在黑名单 [XX] 应拦截,实际: {:?}",
result
);
}
#[tokio::test]
async fn geoip_allows_when_in_allowed_countries() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "CN"));
let config = GeoIPConfig {
allowed_countries: vec!["CN".into()],
blocked_countries: vec![],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
assert!(
strategy.check(&ctx).await.is_ok(),
"CN 在白名单 [CN] 应放行"
);
}
#[tokio::test]
async fn geoip_allows_when_not_in_blocked_countries() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "CN"));
let config = GeoIPConfig {
allowed_countries: vec![],
blocked_countries: vec!["XX".into()],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
assert!(
strategy.check(&ctx).await.is_ok(),
"CN 不在黑名单 [XX] 应放行"
);
}
#[tokio::test]
async fn geoip_allows_when_both_lists_empty() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "US"));
let config = GeoIPConfig {
allowed_countries: vec![],
blocked_countries: vec![],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
assert!(
strategy.check(&ctx).await.is_ok(),
"两个列表均为空时应全部放行"
);
}
#[tokio::test]
async fn geoip_whitelist_takes_priority_over_blacklist() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "CN"));
let config = GeoIPConfig {
allowed_countries: vec!["CN".into()],
blocked_countries: vec!["CN".into()],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
assert!(
strategy.check(&ctx).await.is_ok(),
"白名单非空时仅检查白名单,CN 在白名单应放行"
);
}
#[tokio::test]
async fn geoip_blocks_unknown_ip_in_whitelist_mode() {
let lookup: Arc<dyn CountryLookup> = Arc::new(MockCountryLookup::new());
let config = GeoIPConfig {
allowed_countries: vec!["CN".into()],
blocked_countries: vec![],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("192.168.1.1");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"白名单模式下无法定位的 IP 应拦截,实际: {:?}",
result
);
}
#[tokio::test]
async fn geoip_allows_unknown_ip_in_blacklist_mode() {
let lookup: Arc<dyn CountryLookup> = Arc::new(MockCountryLookup::new());
let config = GeoIPConfig {
allowed_countries: vec![],
blocked_countries: vec!["XX".into()],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("192.168.1.1");
assert!(
strategy.check(&ctx).await.is_ok(),
"黑名单模式下无法定位的 IP 应放行"
);
}
#[tokio::test]
async fn geoip_country_code_case_insensitive() {
let lookup: Arc<dyn CountryLookup> =
Arc::new(MockCountryLookup::new().with("1.2.3.4", "CN"));
let config = GeoIPConfig {
allowed_countries: vec!["cn".into()],
blocked_countries: vec![],
};
let strategy = GeoIPStrategy::new(config, lookup);
let ctx = FirewallContext::new("1.2.3.4");
assert!(
strategy.check(&ctx).await.is_ok(),
"国家码大小写不敏感,cn 应匹配 CN"
);
}
}