use super::mock::MockCacheDao;
use super::*;
use crate::error::GarrisonError;
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
use crate::strategy::hooks::{
GarrisonFirewallCheckHook, GarrisonFirewallCheckHookDefault, LoginContext,
};
use std::collections::HashMap;
struct MockInterface {
permissions: HashMap<String, Vec<String>>,
roles: HashMap<String, Vec<String>>,
}
impl MockInterface {
fn new() -> Self {
Self {
permissions: HashMap::new(),
roles: HashMap::new(),
}
}
fn set_permissions(&mut self, login_id: &str, perms: &[&str]) {
self.permissions.insert(
login_id.to_string(),
perms.iter().map(|s| s.to_string()).collect(),
);
}
fn set_roles(&mut self, login_id: &str, roles: &[&str]) {
self.roles.insert(
login_id.to_string(),
roles.iter().map(|s| s.to_string()).collect(),
);
}
}
#[async_trait]
impl GarrisonInterface for MockInterface {
async fn get_permission_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.permissions.get(login_id).cloned().unwrap_or_default())
}
async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.roles.get(login_id).cloned().unwrap_or_default())
}
}
fn make_firewall(interface: MockInterface) -> GarrisonPermissionStrategyDefault {
GarrisonPermissionStrategyDefault::new(Arc::new(interface))
}
#[tokio::test]
async fn check_permission_held_returns_true() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read", "user:write"]);
let fw = make_firewall(iface);
assert!(
fw.check_permission("1001", "user:read").await.unwrap(),
"持有权限应返回 true"
);
}
#[tokio::test]
async fn check_permission_not_held_returns_false() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read"]);
let fw = make_firewall(iface);
assert!(
!fw.check_permission("1001", "user:delete").await.unwrap(),
"未持有权限应返回 false"
);
}
#[tokio::test]
async fn check_permission_empty_string_errors() {
let iface = MockInterface::new();
let fw = make_firewall(iface);
let result = fw.check_permission("1001", "").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"空权限字符串应抛 InvalidParam"
);
}
#[tokio::test]
async fn check_permission_no_record_returns_false() {
let iface = MockInterface::new();
let fw = make_firewall(iface);
assert!(
!fw.check_permission("9999", "user:read").await.unwrap(),
"无权限记录的 login_id 应返回 false"
);
}
#[tokio::test]
async fn check_role_held_returns_true() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin", "user"]);
let fw = make_firewall(iface);
assert!(
fw.check_role("1001", "admin").await.unwrap(),
"持有角色应返回 true"
);
}
#[tokio::test]
async fn check_role_not_held_returns_false() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["user"]);
let fw = make_firewall(iface);
assert!(
!fw.check_role("1001", "admin").await.unwrap(),
"未持有角色应返回 false"
);
}
#[tokio::test]
async fn check_role_empty_string_errors() {
let iface = MockInterface::new();
let fw = make_firewall(iface);
let result = fw.check_role("1001", "").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"空角色字符串应抛 InvalidParam"
);
}
#[tokio::test]
async fn check_role_any_match_returns_true() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
let fw = make_firewall(iface);
assert!(
fw.check_role_any("1001", &["admin", "superadmin"])
.await
.unwrap(),
"持有任一角色应返回 true"
);
}
#[tokio::test]
async fn check_role_any_no_match_returns_false() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["user"]);
let fw = make_firewall(iface);
assert!(
!fw.check_role_any("1001", &["admin", "superadmin"])
.await
.unwrap(),
"不持有任一角色应返回 false"
);
}
#[tokio::test]
async fn check_role_all_all_held_returns_true() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin", "user"]);
let fw = make_firewall(iface);
assert!(
fw.check_role_all("1001", &["admin", "user"]).await.unwrap(),
"持有所有角色应返回 true"
);
}
#[tokio::test]
async fn check_role_all_partial_held_returns_false() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
let fw = make_firewall(iface);
assert!(
!fw.check_role_all("1001", &["admin", "user"]).await.unwrap(),
"仅持有部分角色应返回 false"
);
}
#[tokio::test]
async fn check_role_all_empty_roles_returns_true() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
let fw = make_firewall(iface);
assert!(
fw.check_role_all("1001", &[]).await.unwrap(),
"空 roles 切片应平凡返回 true"
);
}
#[tokio::test]
async fn get_permission_list_delegates_to_interface() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read", "user:write"]);
let fw = make_firewall(iface);
let perms = fw.get_permission_list("1001").await.unwrap();
assert_eq!(perms, vec!["user:read", "user:write"]);
}
#[tokio::test]
async fn get_role_list_delegates_to_interface() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin", "user"]);
let fw = make_firewall(iface);
let roles = fw.get_role_list("1001").await.unwrap();
assert_eq!(roles, vec!["admin", "user"]);
}
#[tokio::test]
async fn get_permission_list_unknown_login_id_returns_empty() {
let iface = MockInterface::new();
let fw = make_firewall(iface);
let perms = fw.get_permission_list("9999").await.unwrap();
assert!(perms.is_empty(), "未配置权限的 login_id 应返回空列表");
}
struct MockPermissionChecker {
perm_result: bool,
}
#[async_trait]
impl PermissionChecker for MockPermissionChecker {
async fn has_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<bool> {
Ok(self.perm_result)
}
async fn has_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(false)
}
async fn check_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<()> {
Ok(())
}
async fn has_any_permission(&self, _login_id: &str, _perms: &[&str]) -> bool {
false
}
async fn has_all_permissions(&self, _login_id: &str, _perms: &[&str]) -> bool {
false
}
}
#[tokio::test]
async fn check_permission_delegates_to_permission_checker() {
let iface = MockInterface::new();
let pc = Arc::new(MockPermissionChecker { perm_result: true });
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_permission_checker(pc);
assert!(
fw.check_permission("1001", "user:read").await.unwrap(),
"注入 PermissionChecker 后应委托校验,返回 true"
);
}
#[tokio::test]
async fn check_permission_delegates_returns_false() {
let iface = MockInterface::new();
let pc = Arc::new(MockPermissionChecker { perm_result: false });
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_permission_checker(pc);
assert!(
!fw.check_permission("1001", "user:read").await.unwrap(),
"PermissionChecker 返回 false 时应返回 false"
);
}
#[tokio::test]
async fn check_permission_without_checker_falls_back_to_interface() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read"]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));
assert!(
fw.check_permission("1001", "user:read").await.unwrap(),
"未注入 PermissionChecker 时应回退到 interface 查询"
);
}
fn make_firewall_with_hierarchy(
interface: MockInterface,
hierarchy: HashMap<String, Vec<String>>,
) -> GarrisonPermissionStrategyDefault {
GarrisonPermissionStrategyDefault::new(Arc::new(interface)).with_role_hierarchy(hierarchy)
}
#[tokio::test]
async fn check_role_hierarchy_admin_implies_user() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
let mut hierarchy = HashMap::new();
hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
let fw = make_firewall_with_hierarchy(iface, hierarchy);
assert!(
fw.check_role("1001", "user").await.unwrap(),
"admin 应隐含持有 user"
);
assert!(
!fw.check_role("1001", "superadmin").await.unwrap(),
"admin 不隐含 superadmin"
);
}
#[tokio::test]
async fn check_role_hierarchy_transitive() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["superadmin"]);
let mut hierarchy = HashMap::new();
hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
hierarchy.insert("superadmin".to_string(), vec!["admin".to_string()]);
let fw = make_firewall_with_hierarchy(iface, hierarchy);
assert!(
fw.check_role("1001", "user").await.unwrap(),
"superadmin 应多层传递隐含 user"
);
assert!(
fw.check_role("1001", "admin").await.unwrap(),
"superadmin 应隐含 admin"
);
}
#[tokio::test]
async fn check_role_without_hierarchy_keeps_legacy_behavior() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
let fw = make_firewall(iface);
assert!(
!fw.check_role("1001", "user").await.unwrap(),
"未配置 hierarchy 时 admin 不隐含 user(0.1.0 行为)"
);
}
#[tokio::test]
async fn check_role_any_all_with_hierarchy() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
let mut hierarchy = HashMap::new();
hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
let fw = make_firewall_with_hierarchy(iface, hierarchy);
assert!(
fw.check_role_any("1001", &["user", "guest"]).await.unwrap(),
"层级展开后应持有 user,check_role_any 应返回 true"
);
assert!(
!fw.check_role_all("1001", &["user", "superadmin"])
.await
.unwrap(),
"层级展开后不含 superadmin,check_role_all 应返回 false"
);
}
#[tokio::test]
async fn check_permission_triggers_plugin_hook() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read"]);
let pm = Arc::new(GarrisonPluginManager::new());
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_plugin_manager(pm);
assert!(
fw.check_permission("1001", "user:read").await.unwrap(),
"插件钩子不应影响校验结果"
);
}
#[tokio::test]
async fn check_permission_plugin_failure_does_not_interrupt() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read"]);
let pm = Arc::new(GarrisonPluginManager::new());
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_plugin_manager(pm);
assert!(
fw.check_permission("1001", "user:read").await.unwrap(),
"插件失败不应中断主流程,校验结果应正常返回 true"
);
}
#[tokio::test]
async fn cache_permission_writes_and_reads_back() {
let dao = Arc::new(MockCacheDao::new());
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());
fw.cache_permission("1001", "user:read", true, 300)
.await
.unwrap();
let cached = fw.get_cached_permission("1001", "user:read").await.unwrap();
assert_eq!(cached, Some(true), "缓存应命中并返回 true");
let key = "garrison:perm:cache:1001:user:read";
assert_eq!(
dao.get(key).await.unwrap(),
Some("true".to_string()),
"DAO 中应存储 key {}",
key
);
}
#[tokio::test]
async fn get_cached_permission_miss_returns_none() {
let dao = Arc::new(MockCacheDao::new());
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);
let cached = fw
.get_cached_permission("1001", "user:delete")
.await
.unwrap();
assert!(cached.is_none(), "未缓存的权限应返回 None");
}
#[tokio::test]
async fn cache_permission_overwrite() {
let dao = Arc::new(MockCacheDao::new());
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);
fw.cache_permission("1001", "user:read", true, 300)
.await
.unwrap();
assert_eq!(
fw.get_cached_permission("1001", "user:read").await.unwrap(),
Some(true)
);
fw.cache_permission("1001", "user:read", false, 300)
.await
.unwrap();
assert_eq!(
fw.get_cached_permission("1001", "user:read").await.unwrap(),
Some(false),
"覆盖后应返回 false"
);
}
#[tokio::test]
async fn check_permission_uses_cache_short_circuit() {
let dao = Arc::new(MockCacheDao::new());
let mut iface = MockInterface::new();
iface.set_permissions("1001", &[]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());
fw.cache_permission("1001", "user:read", true, 300)
.await
.unwrap();
assert!(
fw.check_permission("1001", "user:read").await.unwrap(),
"应优先返回缓存结果 true,而非查询 interface"
);
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_noop_without_hook() {
let iface = MockInterface::new();
let fw = make_firewall(iface);
let ctx = LoginContext::new("1001");
assert!(
fw.check_login_hooks("1001", &ctx).await.is_ok(),
"未注入 firewall_hook 时 check_login_hooks 应为 no-op"
);
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_passes_with_hook() {
let iface = MockInterface::new();
let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook);
let ctx = LoginContext::new("1001");
assert!(
fw.check_login_hooks("1001", &ctx).await.is_ok(),
"注入 hook 且无失败记录时 check_login_hooks 应返回 Ok"
);
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_blocks_on_frequency_exceeded() {
let iface = MockInterface::new();
let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
let fw =
GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook.clone());
let ctx = LoginContext::new("1001").with_ip("1.2.3.4");
for _ in 0..10 {
hook.record_failure(&ctx).await.unwrap();
}
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "登录频率超限时应被 check_login_hooks 阻断");
assert!(
matches!(result.unwrap_err(), GarrisonError::Session(_)),
"阻断错误应为 Session 类型"
);
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_blocks_on_brute_force_exceeded() {
let iface = MockInterface::new();
let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
let fw =
GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook.clone());
let ctx = LoginContext::new("1001");
for _ in 0..5 {
hook.record_failure(&ctx).await.unwrap();
}
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "暴力破解超限时应被 check_login_hooks 阻断");
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn with_firewall_hook_injects_hook() {
let iface = MockInterface::new();
let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
let fw =
GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook.clone());
let ctx = LoginContext::new("1001").with_ip("9.9.9.9");
for _ in 0..10 {
hook.record_failure(&ctx).await.unwrap();
}
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "注入 hook 后应能检测到频率超限并阻断");
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_calls_in_order() {
use std::sync::atomic::{AtomicU8, Ordering};
struct OrderTrackingHook {
order: Arc<AtomicU8>,
}
#[async_trait]
impl GarrisonFirewallCheckHook for OrderTrackingHook {
async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.order.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.order.fetch_add(2, Ordering::SeqCst);
Ok(())
}
async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.order.fetch_add(4, Ordering::SeqCst);
Ok(())
}
async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.order.fetch_add(8, Ordering::SeqCst);
Ok(())
}
async fn check_device_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.order.fetch_add(16, Ordering::SeqCst);
Ok(())
}
}
let order = Arc::new(AtomicU8::new(0));
let hook = Arc::new(OrderTrackingHook {
order: order.clone(),
});
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook);
let ctx = LoginContext::new("1001");
fw.check_login_hooks("1001", &ctx).await.unwrap();
assert_eq!(order.load(Ordering::SeqCst), 31, "5 个 hook 应全部按序调用");
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_short_circuits_on_err() {
use std::sync::atomic::{AtomicU8, Ordering};
struct ShortCircuitHook {
called: Arc<AtomicU8>,
}
#[async_trait]
impl GarrisonFirewallCheckHook for ShortCircuitHook {
async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.called.fetch_add(1, Ordering::SeqCst);
Err(GarrisonError::Session("frequency blocked".to_string()))
}
async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.called.fetch_add(2, Ordering::SeqCst);
Ok(())
}
async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.called.fetch_add(4, Ordering::SeqCst);
Ok(())
}
async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.called.fetch_add(8, Ordering::SeqCst);
Ok(())
}
async fn check_device_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
self.called.fetch_add(16, Ordering::SeqCst);
Ok(())
}
}
let called = Arc::new(AtomicU8::new(0));
let hook = Arc::new(ShortCircuitHook {
called: called.clone(),
});
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook);
let ctx = LoginContext::new("1001");
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "应在第一个 hook Err 时阻断");
assert_eq!(
called.load(Ordering::SeqCst),
1,
"第一个 hook Err 后应短路,后续 hook 不应被调用"
);
}
#[cfg(feature = "listener")]
#[test]
fn with_listener_manager_sets_field() {
use crate::listener::GarrisonListenerManager;
let lm = Arc::new(GarrisonListenerManager::new());
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(MockInterface::new()))
.with_listener_manager(lm);
assert!(
fw.listener_manager.is_some(),
"with_listener_manager 后 listener_manager 应为 Some"
);
}
#[tokio::test]
async fn check_permission_cache_write_failure_warns_but_returns_result() {
struct FailingDao;
#[async_trait]
impl crate::dao::GarrisonDao for FailingDao {
async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
async fn set(&self, _key: &str, _value: &str, _ttl: u64) -> GarrisonResult<()> {
Err(GarrisonError::Dao("simulated set failure".to_string()))
}
async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
Err(GarrisonError::Dao("simulated update failure".to_string()))
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Err(GarrisonError::Dao("simulated expire failure".to_string()))
}
async fn delete(&self, _key: &str) -> GarrisonResult<()> {
Ok(())
}
}
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read"]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(Arc::new(FailingDao));
let result = fw.check_permission("1001", "user:read").await;
assert!(
result.is_ok(),
"缓存写入失败不应中断 check_permission,实际: {:?}",
result
);
assert!(
result.unwrap(),
"持有权限应返回 true(缓存写入失败不影响结果)"
);
}
#[cfg(all(
feature = "listener",
any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
)
))]
#[tokio::test]
async fn check_login_hooks_geo_anomaly_failure_broadcasts_firewall_block() {
use crate::listener::GarrisonListenerManager;
let iface = MockInterface::new();
let lm = Arc::new(GarrisonListenerManager::new());
struct GeoFailHook;
#[async_trait]
impl crate::strategy::GarrisonFirewallCheckHook for GeoFailHook {
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<()> {
Err(GarrisonError::Session("geo blocked".to_string()))
}
}
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
.with_firewall_hook(Arc::new(GeoFailHook))
.with_listener_manager(lm);
let ctx = LoginContext::new("1001");
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "geo_anomaly 失败应阻断");
assert!(
matches!(result.unwrap_err(), GarrisonError::Session(_)),
"应返回 Session 错误"
);
}
#[cfg(all(
feature = "listener",
any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
)
))]
#[tokio::test]
async fn check_login_hooks_token_reuse_failure_broadcasts() {
use crate::listener::GarrisonListenerManager;
let iface = MockInterface::new();
let lm = Arc::new(GarrisonListenerManager::new());
struct TokenReuseFailHook;
#[async_trait]
impl crate::strategy::GarrisonFirewallCheckHook for TokenReuseFailHook {
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<()> {
Err(GarrisonError::Session("token reuse blocked".to_string()))
}
}
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
.with_firewall_hook(Arc::new(TokenReuseFailHook))
.with_listener_manager(lm);
let ctx = LoginContext::new("1001");
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "token_reuse 失败应阻断");
}
#[cfg(all(
feature = "listener",
any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
)
))]
#[tokio::test]
async fn check_login_hooks_device_anomaly_failure_broadcasts() {
use crate::listener::GarrisonListenerManager;
let iface = MockInterface::new();
let lm = Arc::new(GarrisonListenerManager::new());
struct DeviceFailHook;
#[async_trait]
impl crate::strategy::GarrisonFirewallCheckHook for DeviceFailHook {
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<()> {
Err(GarrisonError::Session("device anomaly blocked".to_string()))
}
}
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
.with_firewall_hook(Arc::new(DeviceFailHook))
.with_listener_manager(lm);
let ctx = LoginContext::new("1001");
let result = fw.check_login_hooks("1001", &ctx).await;
assert!(result.is_err(), "device_anomaly 失败应阻断");
}