use crate::constants::DaoKeyPrefix;
use crate::dao::{GarrisonDao, InMemoryDao};
use crate::error::{GarrisonError, GarrisonResult};
use crate::limiteron::{LimiterBackend, LimiterRuntime};
#[cfg(feature = "listener")]
use crate::listener::{GarrisonEvent, GarrisonListenerManager};
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug, Clone, Default)]
pub struct LoginContext {
pub login_id: String,
pub ip: Option<String>,
pub device_fingerprint: Option<String>,
pub geo: Option<String>,
}
impl LoginContext {
pub fn new(login_id: impl Into<String>) -> Self {
Self {
login_id: login_id.into(),
ip: None,
device_fingerprint: None,
geo: None,
}
}
pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
self.ip = Some(ip.into());
self
}
pub fn with_device(mut self, device: impl Into<String>) -> Self {
self.device_fingerprint = Some(device.into());
self
}
pub fn with_geo(mut self, geo: impl Into<String>) -> Self {
self.geo = Some(geo.into());
self
}
}
#[async_trait]
pub trait GarrisonFirewallCheckHook: Send + Sync {
async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
Ok(())
}
async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
Ok(())
}
async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
Ok(())
}
async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
Ok(())
}
async fn check_device_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
Ok(())
}
}
pub const LOGIN_FREQUENCY_THRESHOLD: u32 = 10;
pub const LOGIN_FREQUENCY_WINDOW: Duration = Duration::from_secs(3600);
pub const BRUTE_FORCE_THRESHOLD: u32 = 5;
pub const BRUTE_FORCE_WINDOW: Duration = Duration::from_secs(3600);
const FW_IP_KEY_PREFIX: &str = "fw:ip:";
const FW_ACCT_KEY_PREFIX: &str = "fw:acct:";
pub struct GarrisonFirewallCheckHookDefault {
limiter: Arc<dyn LimiterBackend>,
dao: Arc<dyn GarrisonDao>,
#[cfg(feature = "listener")]
listener_manager: Option<Arc<GarrisonListenerManager>>,
}
impl GarrisonFirewallCheckHookDefault {
#[doc(hidden)]
pub fn new() -> Self {
Self::with_memory_default()
}
pub fn with_memory_default() -> Self {
let dao: Arc<dyn GarrisonDao> = Arc::new(InMemoryDao::new());
let limiter = LimiterRuntime::dao(dao.clone()).limiter();
Self {
limiter,
dao,
#[cfg(feature = "listener")]
listener_manager: None,
}
}
pub fn with_dao(mut self, dao: Arc<dyn GarrisonDao>) -> Self {
self.limiter = LimiterRuntime::dao(dao.clone()).limiter();
self.dao = dao;
self
}
pub fn with_limiter_backend(mut self, limiter: Arc<dyn LimiterBackend>) -> Self {
self.limiter = limiter;
self
}
#[cfg(feature = "listener")]
pub fn with_listener_manager(mut self, lm: Arc<GarrisonListenerManager>) -> Self {
self.listener_manager = Some(lm);
self
}
pub async fn record_failure(&self, ctx: &LoginContext) -> GarrisonResult<()> {
if let Some(ip) = &ctx.ip {
let key = format!("{}{}", FW_IP_KEY_PREFIX, ip);
self.limiter
.incr_with_ttl(&key, 1, LOGIN_FREQUENCY_WINDOW)
.await
.map_err(map_limiteron_err)?;
}
let acct_key = format!("{}{}", FW_ACCT_KEY_PREFIX, ctx.login_id);
self.limiter
.incr_with_ttl(&acct_key, 1, BRUTE_FORCE_WINDOW)
.await
.map_err(map_limiteron_err)?;
Ok(())
}
pub async fn reset(&self) -> GarrisonResult<()> {
self.limiter
.reset_prefix(FW_IP_KEY_PREFIX)
.await
.map_err(map_limiteron_err)?;
self.limiter
.reset_prefix(FW_ACCT_KEY_PREFIX)
.await
.map_err(map_limiteron_err)?;
Ok(())
}
pub async fn ip_failure_count(&self, ip: &str) -> u32 {
let key = format!("{}{}", FW_IP_KEY_PREFIX, ip);
match self.limiter.get_count(&key).await {
Ok(c) => c as u32,
Err(e) => {
tracing::warn!("ip_failure_count get_count failed: {}", e);
0
},
}
}
pub async fn account_failure_count(&self, login_id: &str) -> u32 {
let key = format!("{}{}", FW_ACCT_KEY_PREFIX, login_id);
match self.limiter.get_count(&key).await {
Ok(c) => c as u32,
Err(e) => {
tracing::warn!("account_failure_count get_count failed: {}", e);
0
},
}
}
}
fn map_limiteron_err(e: limiteron::error::LimiteronError) -> GarrisonError {
GarrisonError::Dao(format!("strategy-limiteron-op::{}", e))
}
impl Default for GarrisonFirewallCheckHookDefault {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl GarrisonFirewallCheckHook for GarrisonFirewallCheckHookDefault {
async fn check_login_frequency(&self, ctx: &LoginContext) -> GarrisonResult<()> {
let Some(ip) = &ctx.ip else {
return Ok(()); };
let key = format!("{}{}", FW_IP_KEY_PREFIX, ip);
let count = self
.limiter
.get_count(&key)
.await
.map_err(map_limiteron_err)?;
if count >= LOGIN_FREQUENCY_THRESHOLD as u64 {
return Err(GarrisonError::Session(format!(
"strategy-login-frequency-exceeded::{}",
ip
)));
}
Ok(())
}
async fn check_brute_force(&self, ctx: &LoginContext) -> GarrisonResult<()> {
let key = format!("{}{}", FW_ACCT_KEY_PREFIX, ctx.login_id);
let count = self
.limiter
.get_count(&key)
.await
.map_err(map_limiteron_err)?;
if count >= BRUTE_FORCE_THRESHOLD as u64 {
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::AccountLocked {
login_id: ctx.login_id.clone(),
reason: format!("brute_force: {} failures in 1h", count),
request_context: None,
})
.await;
}
return Err(GarrisonError::Session(format!(
"strategy-account-locked::{}",
ctx.login_id
)));
}
Ok(())
}
async fn check_geo_anomaly(&self, ctx: &LoginContext) -> GarrisonResult<()> {
let Some(ctx_geo) = &ctx.geo else {
return Ok(()); };
let key = format!("fw:geo:{}", ctx.login_id);
match self.dao.get(&key).await? {
Some(stored_geo) if stored_geo != *ctx_geo => Err(GarrisonError::Session(format!(
"strategy-geo-anomaly::{}::{}|{}",
ctx.login_id, stored_geo, ctx_geo
))),
_ => Ok(()), }
}
async fn check_token_reuse(&self, ctx: &LoginContext) -> GarrisonResult<()> {
let key = format!("{}blacklist:{}", DaoKeyPrefix::Token, ctx.login_id);
if self.dao.get(&key).await?.is_some() {
return Err(GarrisonError::Session(format!(
"strategy-token-reuse-blocked::{}",
ctx.login_id
)));
}
Ok(())
}
async fn check_device_anomaly(&self, ctx: &LoginContext) -> GarrisonResult<()> {
let Some(fp) = &ctx.device_fingerprint else {
return Ok(()); };
let key = format!("fw:device:{}", ctx.login_id);
match self.dao.get(&key).await? {
Some(known_list) => {
let known: Vec<&str> = known_list.split(',').map(|s| s.trim()).collect();
if !known.contains(&fp.as_str()) {
return Err(GarrisonError::Session(format!(
"strategy-device-anomaly::{}::{}",
ctx.login_id, fp
)));
}
Ok(())
},
None => Ok(()), }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn login_context_new_has_only_login_id() {
let ctx = LoginContext::new("1001");
assert_eq!(ctx.login_id, "1001");
assert!(ctx.ip.is_none());
assert!(ctx.device_fingerprint.is_none());
assert!(ctx.geo.is_none());
}
#[test]
fn login_context_builder_sets_fields() {
let ctx = LoginContext::new("1001")
.with_ip("192.168.1.1")
.with_device("dev-fp-abc")
.with_geo("Beijing");
assert_eq!(ctx.login_id, "1001");
assert_eq!(ctx.ip.as_deref(), Some("192.168.1.1"));
assert_eq!(ctx.device_fingerprint.as_deref(), Some("dev-fp-abc"));
assert_eq!(ctx.geo.as_deref(), Some("Beijing"));
}
#[tokio::test]
async fn default_hook_impl_all_pass() {
struct NoOpHook;
#[async_trait]
impl GarrisonFirewallCheckHook for NoOpHook {}
let hook = NoOpHook;
let ctx = LoginContext::new("1001");
assert!(hook.check_login_frequency(&ctx).await.is_ok());
assert!(hook.check_brute_force(&ctx).await.is_ok());
assert!(hook.check_geo_anomaly(&ctx).await.is_ok());
assert!(hook.check_token_reuse(&ctx).await.is_ok());
assert!(hook.check_device_anomaly(&ctx).await.is_ok());
}
#[tokio::test]
async fn check_login_frequency_passes_without_ip() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001"); assert!(hook.check_login_frequency(&ctx).await.is_ok());
}
#[tokio::test]
async fn check_login_frequency_passes_below_threshold() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
for _ in 0..9 {
hook.record_failure(&ctx).await.unwrap();
}
assert_eq!(hook.ip_failure_count("1.2.3.4").await, 9);
assert!(hook.check_login_frequency(&ctx).await.is_ok());
}
#[tokio::test]
async fn check_login_frequency_blocks_at_threshold() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
for _ in 0..10 {
hook.record_failure(&ctx).await.unwrap();
}
assert_eq!(hook.ip_failure_count("1.2.3.4").await, 10);
let result = hook.check_login_frequency(&ctx).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, GarrisonError::Session(_)));
}
#[tokio::test]
async fn check_brute_force_passes_below_threshold() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001");
for _ in 0..4 {
hook.record_failure(&ctx).await.unwrap();
}
assert_eq!(hook.account_failure_count("1001").await, 4);
assert!(hook.check_brute_force(&ctx).await.is_ok());
}
#[tokio::test]
async fn check_brute_force_blocks_at_threshold() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001");
for _ in 0..5 {
hook.record_failure(&ctx).await.unwrap();
}
assert_eq!(hook.account_failure_count("1001").await, 5);
let result = hook.check_brute_force(&ctx).await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), GarrisonError::Session(_)));
}
#[tokio::test]
async fn reset_clears_all_counters() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
hook.record_failure(&ctx).await.unwrap();
hook.record_failure(&ctx).await.unwrap();
assert_eq!(hook.ip_failure_count("1.2.3.4").await, 2);
assert_eq!(hook.account_failure_count("1001").await, 2);
hook.reset().await.unwrap();
assert_eq!(hook.ip_failure_count("1.2.3.4").await, 0);
assert_eq!(hook.account_failure_count("1001").await, 0);
}
#[tokio::test]
async fn ip_counters_are_independent() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx1 = LoginContext::new("1001").with_ip("1.1.1.1");
let ctx2 = LoginContext::new("1002").with_ip("2.2.2.2");
hook.record_failure(&ctx1).await.unwrap();
hook.record_failure(&ctx1).await.unwrap();
hook.record_failure(&ctx2).await.unwrap();
assert_eq!(hook.ip_failure_count("1.1.1.1").await, 2);
assert_eq!(hook.ip_failure_count("2.2.2.2").await, 1);
}
#[tokio::test]
async fn account_counters_are_independent() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx1 = LoginContext::new("1001");
let ctx2 = LoginContext::new("1002");
hook.record_failure(&ctx1).await.unwrap();
hook.record_failure(&ctx1).await.unwrap();
hook.record_failure(&ctx1).await.unwrap();
hook.record_failure(&ctx2).await.unwrap();
assert_eq!(hook.account_failure_count("1001").await, 3);
assert_eq!(hook.account_failure_count("1002").await, 1);
}
#[tokio::test]
async fn other_hooks_pass_by_default() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001").with_geo("Shanghai");
assert!(hook.check_geo_anomaly(&ctx).await.is_ok());
assert!(hook.check_token_reuse(&ctx).await.is_ok());
assert!(hook.check_device_anomaly(&ctx).await.is_ok());
}
#[tokio::test]
async fn record_failure_increments_both_counters() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
hook.record_failure(&ctx).await.unwrap();
assert_eq!(hook.ip_failure_count("1.2.3.4").await, 1);
assert_eq!(hook.account_failure_count("1001").await, 1);
}
#[test]
fn default_equals_new() {
let _hook1 = GarrisonFirewallCheckHookDefault::new();
let _hook2 = GarrisonFirewallCheckHookDefault::default();
}
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use std::sync::Arc;
fn make_dao_hook() -> (GarrisonFirewallCheckHookDefault, Arc<MockDao>) {
let dao = Arc::new(InMemoryDao::new());
let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao.clone());
(hook, dao)
}
#[tokio::test]
async fn with_dao_creates_distributed_mode() {
let dao = Arc::new(InMemoryDao::new());
let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao.clone());
let ctx = LoginContext::new("1001").with_ip("9.9.9.9");
hook.record_failure(&ctx).await.unwrap();
assert_eq!(hook.ip_failure_count("9.9.9.9").await, 1);
assert_eq!(hook.account_failure_count("1001").await, 1);
assert_eq!(
dao.get("fw:ip:9.9.9.9").await.unwrap().as_deref(),
Some("1")
);
assert_eq!(dao.get("fw:acct:1001").await.unwrap().as_deref(), Some("1"));
}
#[tokio::test]
async fn with_limiter_backend_overrides_dao_limiter() {
let dao = Arc::new(InMemoryDao::new());
let limiter_dao = Arc::new(InMemoryDao::new());
let hook = GarrisonFirewallCheckHookDefault::new()
.with_dao(dao.clone())
.with_limiter_backend(LimiterRuntime::dao(limiter_dao.clone()).limiter());
let ctx = LoginContext::new("2002").with_ip("8.8.8.8");
hook.record_failure(&ctx).await.unwrap();
assert!(
dao.get("fw:ip:8.8.8.8").await.unwrap().is_none(),
"默认 DAO 不应收到计数写入"
);
assert_eq!(
limiter_dao.get("fw:ip:8.8.8.8").await.unwrap().as_deref(),
Some("1"),
"计数应写入注入的限流后端"
);
assert_eq!(hook.ip_failure_count("8.8.8.8").await, 1);
}
#[tokio::test]
async fn record_failure_dao_mode_increments_counter() {
let (hook, dao) = make_dao_hook();
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
for _ in 0..3 {
hook.record_failure(&ctx).await.unwrap();
}
let ip_count = dao.get("fw:ip:1.2.3.4").await.unwrap();
assert_eq!(ip_count.as_deref(), Some("3"));
let acct_count = dao.get("fw:acct:1001").await.unwrap();
assert_eq!(acct_count.as_deref(), Some("3"));
}
#[tokio::test]
async fn check_login_frequency_dao_mode_blocks_at_threshold() {
let (hook, _dao) = make_dao_hook();
let ctx = LoginContext::new("1001").with_ip("5.6.7.8");
for _ in 0..10 {
hook.record_failure(&ctx).await.unwrap();
}
let result = hook.check_login_frequency(&ctx).await;
assert!(result.is_err(), "DAO 模式下 IP 失败 ≥ 阈值应阻断");
assert!(matches!(result.unwrap_err(), GarrisonError::Session(_)));
}
#[tokio::test]
async fn check_brute_force_dao_mode_blocks_at_threshold() {
let (hook, _dao) = make_dao_hook();
let ctx = LoginContext::new("1001");
for _ in 0..5 {
hook.record_failure(&ctx).await.unwrap();
}
let result = hook.check_brute_force(&ctx).await;
assert!(result.is_err(), "DAO 模式下账号失败 ≥ 阈值应阻断");
assert!(matches!(result.unwrap_err(), GarrisonError::Session(_)));
}
#[tokio::test]
async fn check_token_reuse_dao_mode_blocks_blacklisted() {
let (hook, dao) = make_dao_hook();
dao.set("token:blacklist:1001", "revoked", 3600)
.await
.unwrap();
let ctx = LoginContext::new("1001");
let result = hook.check_token_reuse(&ctx).await;
assert!(result.is_err(), "Token 在黑名单中应阻断");
assert!(matches!(result.unwrap_err(), GarrisonError::Session(_)));
}
#[tokio::test]
async fn check_token_reuse_passes_without_blacklist() {
let (hook, _dao) = make_dao_hook();
let ctx = LoginContext::new("1001");
assert!(
hook.check_token_reuse(&ctx).await.is_ok(),
"无黑名单时应通过"
);
}
#[tokio::test]
async fn check_geo_anomaly_dao_mode_blocks_different_geo() {
let (hook, dao) = make_dao_hook();
dao.set("fw:geo:1001", "Beijing", 3600).await.unwrap();
let ctx = LoginContext::new("1001").with_geo("Shanghai");
let result = hook.check_geo_anomaly(&ctx).await;
assert!(result.is_err(), "异地登录应阻断");
assert!(matches!(result.unwrap_err(), GarrisonError::Session(_)));
}
#[tokio::test]
async fn check_geo_anomaly_passes_without_geo_data() {
let (hook, _dao) = make_dao_hook();
let ctx = LoginContext::new("1001").with_geo("Shanghai");
assert!(
hook.check_geo_anomaly(&ctx).await.is_ok(),
"无 geo 记录时应通过(首次登录)"
);
}
#[tokio::test]
async fn check_device_anomaly_dao_mode_blocks_unknown_device() {
let (hook, dao) = make_dao_hook();
dao.set("fw:device:1001", "dev-known-1,dev-known-2", 3600)
.await
.unwrap();
let ctx = LoginContext::new("1001").with_device("dev-unknown");
let result = hook.check_device_anomaly(&ctx).await;
assert!(result.is_err(), "未知设备应阻断");
assert!(matches!(result.unwrap_err(), GarrisonError::Session(_)));
}
#[tokio::test]
async fn check_device_anomaly_passes_without_device_data() {
let (hook, _dao) = make_dao_hook();
let ctx = LoginContext::new("1001").with_device("dev-new");
assert!(
hook.check_device_anomaly(&ctx).await.is_ok(),
"无设备记录时应通过(首次登录)"
);
}
#[cfg(feature = "listener")]
#[test]
fn with_listener_manager_sets_field() {
use crate::listener::GarrisonListenerManager;
let lm = Arc::new(GarrisonListenerManager::new());
let hook = GarrisonFirewallCheckHookDefault::new().with_listener_manager(lm);
assert!(
hook.listener_manager.is_some(),
"with_listener_manager 后 listener_manager 应为 Some"
);
}
#[tokio::test]
async fn record_failure_resets_ip_count_when_window_expired() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001").with_ip("10.0.0.1");
hook.record_failure(&ctx).await.unwrap();
assert_eq!(hook.ip_failure_count("10.0.0.1").await, 1);
let ip_key = format!("{}{}", FW_IP_KEY_PREFIX, "10.0.0.1");
hook.dao.delete(&ip_key).await.unwrap();
hook.record_failure(&ctx).await.unwrap();
assert_eq!(
hook.ip_failure_count("10.0.0.1").await,
1,
"窗口过期后 IP 计数应重置为 1"
);
}
#[tokio::test]
async fn record_failure_resets_account_count_when_window_expired() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001");
hook.record_failure(&ctx).await.unwrap();
assert_eq!(hook.account_failure_count("1001").await, 1);
let acct_key = format!("{}{}", FW_ACCT_KEY_PREFIX, "1001");
hook.dao.delete(&acct_key).await.unwrap();
hook.record_failure(&ctx).await.unwrap();
assert_eq!(
hook.account_failure_count("1001").await,
1,
"窗口过期后账号计数应重置为 1"
);
}
#[tokio::test]
async fn check_brute_force_returns_err_on_dirty_count() {
let dao = Arc::new(InMemoryDao::new());
dao.set("fw:acct:1001", "not-a-number", 3600).await.unwrap();
let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao);
let ctx = LoginContext::new("1001");
let result = hook.check_brute_force(&ctx).await;
assert!(
result.is_err(),
"脏计数器数据应导致 check_brute_force 返回 Err,实际: {:?}",
result
);
let err = result.unwrap_err();
assert!(
matches!(err, GarrisonError::Dao(_)),
"应为 GarrisonError::Dao 错误,实际: {:?}",
err
);
}
#[tokio::test]
async fn check_login_frequency_dao_mode_passes_below_threshold() {
let dao = Arc::new(InMemoryDao::new());
dao.set("fw:ip:1.2.3.4", "9", 3600).await.unwrap();
let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao);
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
let result = hook.check_login_frequency(&ctx).await;
assert!(result.is_ok(), "9 次失败 < 阈值 10,应通过");
}
#[tokio::test]
async fn check_brute_force_dao_mode_passes_below_threshold() {
let dao = Arc::new(InMemoryDao::new());
dao.set("fw:acct:1001", "4", 3600).await.unwrap();
let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao);
let ctx = LoginContext::new("1001");
let result = hook.check_brute_force(&ctx).await;
assert!(result.is_ok(), "4 次失败 < 阈值 5,应通过");
}
#[cfg(feature = "listener")]
#[tokio::test]
async fn check_brute_force_dao_mode_broadcasts_account_locked() {
let dao = Arc::new(InMemoryDao::new());
dao.set("fw:acct:1001", "5", 3600).await.unwrap();
let lm = Arc::new(GarrisonListenerManager::new());
let hook = GarrisonFirewallCheckHookDefault::new()
.with_dao(dao)
.with_listener_manager(lm);
let ctx = LoginContext::new("1001");
let result = hook.check_brute_force(&ctx).await;
assert!(result.is_err(), "5 次失败 ≥ 阈值 5,应阻断");
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("1001"), "错误信息应包含 login_id=1001");
}
#[cfg(feature = "listener")]
#[tokio::test]
async fn check_brute_force_in_memory_mode_broadcasts_account_locked() {
use crate::listener::GarrisonListenerManager;
let lm = Arc::new(GarrisonListenerManager::new());
let hook = GarrisonFirewallCheckHookDefault::new().with_listener_manager(lm);
let ctx = LoginContext::new("1001");
for _ in 0..5 {
hook.record_failure(&ctx).await.unwrap();
}
let result = hook.check_brute_force(&ctx).await;
assert!(result.is_err(), "5 次失败 ≥ 阈值 5,应阻断");
}
#[tokio::test]
async fn check_geo_anomaly_in_memory_mode_passes_without_ctx_geo() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001");
let result = hook.check_geo_anomaly(&ctx).await;
assert!(result.is_ok(), "内存模式无 ctx_geo 时应返回 Ok");
}
#[tokio::test]
async fn check_device_anomaly_in_memory_mode_passes_without_fingerprint() {
let hook = GarrisonFirewallCheckHookDefault::new();
let ctx = LoginContext::new("1001");
let result = hook.check_device_anomaly(&ctx).await;
assert!(result.is_ok(), "内存模式无 device_fingerprint 时应返回 Ok");
}
#[tokio::test]
async fn check_device_anomaly_dao_mode_passes_with_known_device() {
let (hook, dao) = make_dao_hook();
dao.set("fw:device:1001", "dev-known-1,dev-known-2", 3600)
.await
.unwrap();
let ctx = LoginContext::new("1001").with_device("dev-known-1");
let result = hook.check_device_anomaly(&ctx).await;
assert!(result.is_ok(), "已知设备指纹应通过");
}
}