use super::{CountryLookup, GeoCoord, GeoLookup};
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use maxminddb::geoip2;
use std::net::IpAddr;
pub struct MaxMindDbGeoLookup {
reader: maxminddb::Reader<Vec<u8>>,
}
impl std::fmt::Debug for MaxMindDbGeoLookup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MaxMindDbGeoLookup").finish_non_exhaustive()
}
}
impl MaxMindDbGeoLookup {
pub fn open(path: &str) -> GarrisonResult<Self> {
let reader = maxminddb::Reader::open_readfile(path).map_err(|e| {
GarrisonError::Internal(format!("strategy-maxmind-open::{}::{}", path, e))
})?;
Ok(Self { reader })
}
pub fn from_bytes(data: Vec<u8>) -> GarrisonResult<Self> {
let reader = maxminddb::Reader::from_source(data)
.map_err(|e| GarrisonError::Internal(format!("strategy-maxmind-from-bytes::{}", e)))?;
Ok(Self { reader })
}
}
#[async_trait]
impl GeoLookup for MaxMindDbGeoLookup {
async fn lookup(&self, ip: &str) -> GarrisonResult<Option<GeoCoord>> {
let ip_addr: IpAddr = ip
.parse()
.map_err(|_| GarrisonError::InvalidParam(format!("strategy-invalid-ip::{}", ip)))?;
let result = self.reader.lookup(ip_addr).map_err(|e| {
GarrisonError::Internal(format!("strategy-maxmind-query::{}::{}", ip, e))
})?;
match result.decode::<geoip2::City>() {
Ok(Some(city)) => {
let lat = city.location.latitude;
let lon = city.location.longitude;
match (lat, lon) {
(Some(lat), Some(lon)) => Ok(Some(GeoCoord::new(lat, lon))),
_ => Ok(None),
}
},
Ok(None) => Ok(None),
Err(e) => Err(GarrisonError::Internal(format!(
"MaxMindDb 解码 City 记录失败 (IP={}): {}",
ip, e
))),
}
}
}
pub struct MaxMindDbCountryLookup {
reader: maxminddb::Reader<Vec<u8>>,
}
impl std::fmt::Debug for MaxMindDbCountryLookup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MaxMindDbCountryLookup")
.finish_non_exhaustive()
}
}
impl MaxMindDbCountryLookup {
pub fn open(path: &str) -> GarrisonResult<Self> {
let reader = maxminddb::Reader::open_readfile(path).map_err(|e| {
GarrisonError::Internal(format!("strategy-maxmind-open::{}::{}", path, e))
})?;
Ok(Self { reader })
}
pub fn from_bytes(data: Vec<u8>) -> GarrisonResult<Self> {
let reader = maxminddb::Reader::from_source(data)
.map_err(|e| GarrisonError::Internal(format!("strategy-maxmind-from-bytes::{}", e)))?;
Ok(Self { reader })
}
}
#[async_trait]
impl CountryLookup for MaxMindDbCountryLookup {
async fn lookup_country(&self, ip: &str) -> GarrisonResult<Option<String>> {
let ip_addr: IpAddr = ip
.parse()
.map_err(|_| GarrisonError::InvalidParam(format!("strategy-invalid-ip::{}", ip)))?;
let result = self.reader.lookup(ip_addr).map_err(|e| {
GarrisonError::Internal(format!("strategy-maxmind-query::{}::{}", ip, e))
})?;
match result.decode::<geoip2::Country>() {
Ok(Some(country)) => {
let iso_code = country.country.iso_code.map(|s| s.to_string());
Ok(iso_code)
},
Ok(None) => Ok(None),
Err(e) => Err(GarrisonError::Internal(format!(
"MaxMindDb 解码 Country 记录失败 (IP={}): {}",
ip, e
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
const CITY_TEST_DB: &str = "tests/data/GeoLite2-City-Test.mmdb";
const COUNTRY_TEST_DB: &str = "tests/data/GeoLite2-Country-Test.mmdb";
#[test]
fn maxminddb_geo_open_success() {
let result = MaxMindDbGeoLookup::open(CITY_TEST_DB);
assert!(
result.is_ok(),
"打开 City 测试数据库应成功: {:?}",
result.err()
);
}
#[test]
fn maxminddb_geo_open_file_not_found() {
let result = MaxMindDbGeoLookup::open("tests/data/nonexistent.mmdb");
assert!(result.is_err(), "打开不存在的文件应返回 Err");
let err = result.unwrap_err();
assert!(
matches!(err, GarrisonError::Internal(_)),
"错误类型应为 Internal,实际: {:?}",
err
);
}
#[test]
fn maxminddb_geo_from_bytes_success() {
let bytes = std::fs::read(CITY_TEST_DB).expect("读取测试数据库文件失败");
let result = MaxMindDbGeoLookup::from_bytes(bytes);
assert!(result.is_ok(), "从字节构造应成功: {:?}", result.err());
}
#[tokio::test]
async fn maxminddb_geo_lookup_known_ip() {
let lookup = MaxMindDbGeoLookup::open(CITY_TEST_DB).expect("打开数据库失败");
let result = lookup.lookup("81.2.69.142").await;
assert!(result.is_ok(), "查询已知 IP 应成功: {:?}", result.err());
let coord = result.unwrap();
assert!(coord.is_some(), "已知 IP 应返回 Some(GeoCoord)");
let coord = coord.unwrap();
assert!(
coord.lat > 50.0 && coord.lat < 52.0,
"伦敦纬度应在 50-52 之间,实际: {}",
coord.lat
);
assert!(
coord.lon > -1.0 && coord.lon < 1.0,
"伦敦经度应在 -1~1 之间,实际: {}",
coord.lon
);
}
#[tokio::test]
async fn maxminddb_geo_lookup_private_ip() {
let lookup = MaxMindDbGeoLookup::open(CITY_TEST_DB).expect("打开数据库失败");
let result = lookup.lookup("192.168.1.1").await;
assert!(result.is_ok(), "查询私有 IP 应成功: {:?}", result.err());
assert!(
result.unwrap().is_none(),
"私有 IP 应返回 None(数据库无记录)"
);
}
#[tokio::test]
async fn maxminddb_geo_lookup_invalid_ip() {
let lookup = MaxMindDbGeoLookup::open(CITY_TEST_DB).expect("打开数据库失败");
let result = lookup.lookup("invalid").await;
assert!(result.is_err(), "无效 IP 应返回 Err");
let err = result.unwrap_err();
assert!(
matches!(err, GarrisonError::InvalidParam(_)),
"无效 IP 错误类型应为 InvalidParam,实际: {:?}",
err
);
}
#[test]
fn maxminddb_country_open_success() {
let result = MaxMindDbCountryLookup::open(COUNTRY_TEST_DB);
assert!(
result.is_ok(),
"打开 Country 测试数据库应成功: {:?}",
result.err()
);
}
#[test]
fn maxminddb_country_open_file_not_found() {
let result = MaxMindDbCountryLookup::open("tests/data/nonexistent.mmdb");
assert!(result.is_err(), "打开不存在的文件应返回 Err");
}
#[test]
fn maxminddb_country_from_bytes_success() {
let bytes = std::fs::read(COUNTRY_TEST_DB).expect("读取测试数据库文件失败");
let result = MaxMindDbCountryLookup::from_bytes(bytes);
assert!(result.is_ok(), "从字节构造应成功: {:?}", result.err());
}
#[tokio::test]
async fn maxminddb_country_lookup_known_ip() {
let lookup = MaxMindDbCountryLookup::open(COUNTRY_TEST_DB).expect("打开数据库失败");
let result = lookup.lookup_country("81.2.69.142").await;
assert!(result.is_ok(), "查询已知 IP 应成功: {:?}", result.err());
let country = result.unwrap();
assert!(country.is_some(), "已知 IP 应返回 Some(国家码)");
let country = country.unwrap();
assert!(
country == "GB" || country == "gb",
"81.2.69.142 国家码应为 GB,实际: {}",
country
);
}
#[tokio::test]
async fn maxminddb_country_lookup_private_ip() {
let lookup = MaxMindDbCountryLookup::open(COUNTRY_TEST_DB).expect("打开数据库失败");
let result = lookup.lookup_country("192.168.1.1").await;
assert!(result.is_ok(), "查询私有 IP 应成功: {:?}", result.err());
assert!(
result.unwrap().is_none(),
"私有 IP 应返回 None(数据库无记录)"
);
}
#[tokio::test]
async fn maxminddb_country_lookup_invalid_ip() {
let lookup = MaxMindDbCountryLookup::open(COUNTRY_TEST_DB).expect("打开数据库失败");
let result = lookup.lookup_country("invalid").await;
assert!(result.is_err(), "无效 IP 应返回 Err");
let err = result.unwrap_err();
assert!(
matches!(err, GarrisonError::InvalidParam(_)),
"无效 IP 错误类型应为 InvalidParam,实际: {:?}",
err
);
}
#[tokio::test]
async fn geoip_strategy_with_maxminddb() {
use crate::strategy::firewall::{FirewallContext, GarrisonFirewallStrategy};
use crate::strategy::firewall::{GeoIPConfig, GeoIPStrategy};
let country_lookup: Arc<dyn CountryLookup> =
Arc::new(MaxMindDbCountryLookup::open(COUNTRY_TEST_DB).expect("打开数据库失败"));
let config = GeoIPConfig {
allowed_countries: vec!["CN".into()],
blocked_countries: vec![],
};
let strategy = GeoIPStrategy::new(config, country_lookup);
let ctx = FirewallContext::new("81.2.69.142");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"GB 不在白名单 [CN] 应拦截,实际: {:?}",
result
);
}
#[tokio::test]
async fn anomalous_strategy_with_maxminddb() {
use crate::dao::tests::MockDao;
use crate::strategy::firewall::{AnomalousConfig, AnomalousLoginStrategy};
use crate::strategy::firewall::{FirewallContext, GarrisonFirewallStrategy};
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(MockDao::new());
let geo_lookup: Arc<dyn GeoLookup> =
Arc::new(MaxMindDbGeoLookup::open(CITY_TEST_DB).expect("打开数据库失败"));
let config = AnomalousConfig {
known_geo_threshold: 500,
};
let strategy = AnomalousLoginStrategy::new(config, dao, geo_lookup);
let ctx_first = FirewallContext::new("81.2.69.142").with_login_id("1001");
let result_first = strategy.check(&ctx_first).await;
assert!(
result_first.is_ok(),
"首次登录应放行(无历史记录),实际: {:?}",
result_first.err()
);
let ctx_second = FirewallContext::new("81.2.69.142").with_login_id("1001");
let result_second = strategy.check(&ctx_second).await;
assert!(
result_second.is_ok(),
"同地登录(伦敦→伦敦)应放行,实际: {:?}",
result_second.err()
);
}
}