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_uses_flat_matching() {
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:v0:_:1001:user%3Aread";
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 cache_permission_isolated_by_tenant() {
let dao = Arc::new(MockCacheDao::new());
let iface_a = MockInterface::new();
let iface_b = MockInterface::new();
let fw_tenant_a = GarrisonPermissionStrategyDefault::new(Arc::new(iface_a))
.with_dao(dao.clone())
.with_tenant_id(1);
let fw_tenant_b = GarrisonPermissionStrategyDefault::new(Arc::new(iface_b))
.with_dao(dao.clone())
.with_tenant_id(2);
fw_tenant_a
.cache_permission("1001", "user:read", true, 300)
.await
.unwrap();
let b = fw_tenant_b
.get_cached_permission("1001", "user:read")
.await
.unwrap();
assert!(b.is_none(), "租户 B 不应读到租户 A 的缓存");
assert_eq!(
dao.get("garrison:perm:cache:v0:1:1001:user%3Aread")
.await
.unwrap(),
Some("true".to_string())
);
assert_eq!(
dao.get("garrison:perm:cache:v0:2:1001:user%3Aread")
.await
.unwrap(),
None
);
}
#[tokio::test]
async fn invalidate_permission_cache_reflects_revocation_immediately() {
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"
);
fw.invalidate_permission_cache("1001").await.unwrap();
assert!(
!fw.check_permission("1001", "user:read").await.unwrap(),
"失效后应立即回源返回 false,而非读取已回收的缓存"
);
}
#[tokio::test]
async fn invalidate_login_cache_reflects_revocation_immediately() {
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"
);
fw.invalidate_login_cache("1001").await.unwrap();
assert!(
!fw.check_permission("1001", "user:read").await.unwrap(),
"invalidate_login_cache 后应立即回源返回 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"
);
}
#[tokio::test]
async fn perm_cache_key_components_do_not_collide_after_encoding() {
let dao = Arc::new(MockCacheDao::new());
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());
fw.cache_permission("a:b", "c", true, 300).await.unwrap();
assert_eq!(
fw.get_cached_permission("a:b", "c").await.unwrap(),
Some(true)
);
assert_eq!(
fw.get_cached_permission("a", "b:c").await.unwrap(),
None,
"编码后 (a:b, c) 与 (a, b:c) 不得共享缓存键"
);
let fw2 = GarrisonPermissionStrategyDefault::new(Arc::new(MockInterface::new()))
.with_dao(dao.clone());
assert!(
!fw2.check_permission("a", "b:c").await.unwrap(),
"组合 2 回源应为 false,不得被组合 1 的缓存污染"
);
}
#[tokio::test]
async fn perm_cache_key_encoded_format_never_hits_legacy_key() {
let dao = Arc::new(MockCacheDao::new());
dao.set("garrison:perm:cache:1:1001:user:read", "true", 300)
.await
.unwrap();
let mut iface = MockInterface::new();
iface.set_permissions("1001", &[]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
.with_dao(dao)
.with_tenant_id(1);
assert_eq!(
fw.get_cached_permission("1001", "user:read").await.unwrap(),
None,
"旧版裸拼接键残留不得被新版编码键读到"
);
assert!(
!fw.check_permission("1001", "user:read").await.unwrap(),
"回源判定应为 false(旧键 Allow 不得越权)"
);
}
#[tokio::test]
async fn invalidate_login_cache_clears_request_tenant_segments() {
let dao = Arc::new(MockCacheDao::new());
let mut iface = MockInterface::new();
iface.set_permissions("u1", &[]); let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());
fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
.await
.unwrap();
assert!(
fw.check_permission_in_tenant(7, "u1", "doc:read")
.await
.unwrap(),
"预置条件:回收前缓存命中 Allow"
);
fw.invalidate_login_cache("u1").await.unwrap();
assert_eq!(
fw.get_cached_permission_with(Some(7), "u1", "doc:read")
.await
.unwrap(),
None,
"失效后其他租户段的旧 Allow 必须清除"
);
assert!(
!fw.check_permission_in_tenant(7, "u1", "doc:read")
.await
.unwrap(),
"失效后应立即回源返回 false,而非读取已回收的缓存"
);
}
#[tokio::test]
async fn invalidate_permission_cache_clears_all_tenant_segments() {
let dao = Arc::new(MockCacheDao::new());
let mut iface = MockInterface::new();
iface.set_permissions("u1", &[]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
.with_dao(dao)
.with_tenant_id(1);
fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
.await
.unwrap();
assert_eq!(
fw.get_cached_permission_with(Some(7), "u1", "doc:read")
.await
.unwrap(),
Some(true)
);
fw.invalidate_permission_cache("u1").await.unwrap();
assert_eq!(
fw.get_cached_permission_with(Some(7), "u1", "doc:read")
.await
.unwrap(),
None,
"失效端必须跨租户清除,而非只清 builder 配置租户段"
);
}
#[tokio::test]
async fn invalidate_permission_cache_scopes_to_target_login_id() {
let dao = Arc::new(MockCacheDao::new());
let mut iface = MockInterface::new();
iface.set_permissions("u1", &[]);
iface.set_permissions("u2", &["doc:read"]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);
fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
.await
.unwrap();
fw.cache_permission_with(Some(7), "u2", "doc:read", true, 300)
.await
.unwrap();
fw.invalidate_permission_cache("u1").await.unwrap();
assert_eq!(
fw.get_cached_permission_with(Some(7), "u1", "doc:read")
.await
.unwrap(),
None,
"目标 login_id 的缓存应失效"
);
assert_eq!(
fw.get_cached_permission_with(Some(7), "u2", "doc:read")
.await
.unwrap(),
Some(true),
"其他主体的缓存不得被误伤"
);
}
#[tokio::test]
async fn invalidation_epoch_is_fresh_uuid_per_call_and_old_keys_unreachable() {
let dao = Arc::new(MockCacheDao::new());
let mut iface = MockInterface::new();
iface.set_permissions("u1", &[]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());
fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
.await
.unwrap();
let v0_key = "garrison:perm:cache:v0:7:u1:doc%3Aread";
assert_eq!(dao.get(v0_key).await.unwrap().as_deref(), Some("true"));
fw.invalidate_permission_cache("u1").await.unwrap();
let epoch_a = dao
.get("garrison:decision:ver:u1")
.await
.unwrap()
.expect("首次失效后纪元键应存在");
fw.invalidate_permission_cache("u1").await.unwrap();
let epoch_b = dao
.get("garrison:decision:ver:u1")
.await
.unwrap()
.expect("二次失效后纪元键应存在");
assert_ne!(epoch_a, epoch_b, "每次失效必须生成全新纪元标签");
for epoch in [&epoch_a, &epoch_b] {
assert_eq!(epoch.len(), 32, "纪元标签应为 UUID simple(32 hex)");
assert!(
epoch.bytes().all(|b| b.is_ascii_hexdigit()),
"纪元标签应为 hex:{epoch}"
);
}
assert_eq!(
dao.get(v0_key).await.unwrap().as_deref(),
Some("true"),
"旧纪元键残留为存储垃圾(TTL 兜底),属预期"
);
assert_eq!(
fw.get_cached_permission_with(Some(7), "u1", "doc:read")
.await
.unwrap(),
None,
"旧纪元 Allow 键物理在场时也必须不可达(失效结构性生效)"
);
}
struct TenantAwareMockInterface {
roles: HashMap<(i64, String), Vec<String>>,
permissions: HashMap<(i64, String), Vec<String>>,
global_roles: HashMap<String, Vec<String>>,
}
#[async_trait]
impl GarrisonInterface for TenantAwareMockInterface {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(Vec::new())
}
async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.global_roles.get(login_id).cloned().unwrap_or_default())
}
async fn get_role_list_in_tenant(
&self,
tenant_id: i64,
login_id: &str,
) -> GarrisonResult<Vec<String>> {
Ok(self
.roles
.get(&(tenant_id, login_id.to_string()))
.cloned()
.unwrap_or_default())
}
async fn get_permission_list_in_tenant(
&self,
tenant_id: i64,
login_id: &str,
) -> GarrisonResult<Vec<String>> {
Ok(self
.permissions
.get(&(tenant_id, login_id.to_string()))
.cloned()
.unwrap_or_default())
}
}
#[tokio::test]
async fn check_role_in_tenant_queries_tenant_scoped_data_source() {
let mut iface = TenantAwareMockInterface {
roles: HashMap::new(),
permissions: HashMap::new(),
global_roles: HashMap::new(),
};
iface
.roles
.insert((1, "admin".to_string()), vec!["tenant-a-root".to_string()]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));
assert!(
fw.check_role_in_tenant(1, "admin", "tenant-a-root")
.await
.unwrap(),
"租户 1 的 admin 应持有租户 1 授予的角色"
);
assert!(
!fw.check_role_in_tenant(2, "admin", "tenant-a-root")
.await
.unwrap(),
"租户 2 的重名 admin 不得继承租户 1 的角色(互染回归)"
);
}
#[tokio::test]
async fn check_role_in_tenant_fills_decision_cache() {
let mut iface = MockInterface::new();
iface.set_roles("u-cache", &["admin"]);
let dao = Arc::new(MockCacheDao::new());
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());
assert!(
fw.check_role_in_tenant(1, "u-cache", "admin")
.await
.unwrap(),
"数据源持有角色应判定 true"
);
assert_eq!(
dao.get("garrison:role:cache:v0:1:u-cache:admin")
.await
.unwrap(),
Some("true".to_string()),
"true 判定应回填缓存键"
);
assert!(
!fw.check_role_in_tenant(1, "u-cache", "auditor")
.await
.unwrap(),
"数据源未持有角色应判定 false"
);
assert_eq!(
dao.get("garrison:role:cache:v0:1:u-cache:auditor")
.await
.unwrap(),
Some("false".to_string()),
"false 判定同样回填缓存键"
);
}
#[tokio::test]
async fn check_role_in_tenant_serves_cached_decision() {
let iface = MockInterface::new();
let dao = Arc::new(MockCacheDao::new());
dao.set("garrison:role:cache:v0:1:u-hit:admin", "true", 300)
.await
.unwrap();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);
assert!(
fw.check_role_in_tenant(1, "u-hit", "admin").await.unwrap(),
"缓存命中应返回缓存值 true(数据源为空)"
);
assert!(
!fw.check_role_in_tenant(1, "u-hit", "auditor")
.await
.unwrap(),
"缓存未命中且数据源为空应判定 false"
);
}
#[tokio::test]
async fn check_role_in_tenant_empty_role_errors() {
let iface = MockInterface::new();
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));
assert!(
matches!(
fw.check_role_in_tenant(1, "1001", "").await,
Err(GarrisonError::InvalidParam(_))
),
"空角色名应抛 InvalidParam"
);
}
#[tokio::test]
async fn check_role_in_tenant_hierarchy_with_cache_dao() {
let mut iface = MockInterface::new();
iface.set_roles("u-hier", &["admin"]);
let mut hierarchy = HashMap::new();
hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
let dao = Arc::new(MockCacheDao::new());
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
.with_dao(dao)
.with_role_hierarchy(hierarchy);
assert!(
fw.check_role_in_tenant(1, "u-hier", "user").await.unwrap(),
"admin 应隐含 user(层级展开生效)"
);
}
#[tokio::test]
async fn check_permission_in_tenant_queries_tenant_scoped_data_source() {
let mut iface = TenantAwareMockInterface {
roles: HashMap::new(),
permissions: HashMap::new(),
global_roles: HashMap::new(),
};
iface
.permissions
.insert((1, "admin".to_string()), vec!["doc:delete".to_string()]);
let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));
assert!(
fw.check_permission_in_tenant(1, "admin", "doc:delete")
.await
.unwrap(),
"租户 1 的 admin 应持有租户 1 授予的权限"
);
assert!(
!fw.check_permission_in_tenant(2, "admin", "doc:delete")
.await
.unwrap(),
"租户 2 的重名 admin 不得继承租户 1 的权限(互染回归)"
);
}
#[tokio::test]
async fn interface_tenant_aware_defaults_delegate_to_global() {
let mut iface = MockInterface::new();
iface.set_roles("1001", &["admin"]);
iface.set_permissions("1001", &["user:read"]);
let roles = iface.get_role_list_in_tenant(7, "1001").await.unwrap();
assert_eq!(
roles,
vec!["admin"],
"默认实现应委托 get_role_list(忽略租户)"
);
let perms = iface
.get_permission_list_in_tenant(7, "1001")
.await
.unwrap();
assert_eq!(
perms,
vec!["user:read"],
"默认实现应委托 get_permission_list(忽略租户)"
);
}
#[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(())
}
crate::atomic_test_fallback!();
}
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read"]);
{
let d = FailingDao;
let _ = d.set_if_absent("a", "v", 60).await;
let _ = d.get_and_delete("a").await;
let _ = d.incr("c", 60).await;
let _ = d.decr("c").await;
let _ = d.rename("a", "b").await;
let _ = d.compare_and_swap("b", None, "v", 60).await;
let _ = d.set_permanent("p", "v").await;
let _ = d.get_timeout("k").await;
let _ = d.get_with_ttl("k").await;
let _ = d.keys("*").await;
let _ = d.find_social_binding(0, "w", "o").await;
let _ = d.insert_social_binding(0, "u", "w", "o", None, 0).await;
let _ = d.compare_and_update_if_greater("k", 1, 60).await;
let _ = d.eval_lua("r", vec![], vec![]).await;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
{
let _ = d.insert_credit_consumption(0, "r", 1, 1, 1, 0).await;
let _ = d.query_credit_consumption(0, 0, 0).await;
let _ = d.query_role_hierarchy_edges(0).await;
let _ = d.insert_role_hierarchy_edge(0, "c", "p").await;
let _ = d.delete_role_hierarchy_edge(0, "c", "p").await;
}
}
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 失败应阻断");
}
#[tokio::test]
async fn mock_interface_default_methods_with_type_coverage() {
let mut iface = MockInterface::new();
iface.set_permissions("1001", &["user:read", "user:write"]);
iface.set_roles("1001", &["admin", "user"]);
let perms = iface
.get_permission_list_with_type("1001", "user")
.await
.unwrap();
assert_eq!(perms, vec!["user:read", "user:write"]);
let roles = iface
.get_role_list_with_type("1001", "admin")
.await
.unwrap();
assert_eq!(roles, vec!["admin", "user"]);
}
#[tokio::test]
async fn failing_dao_atomic_methods_coverage() {
use crate::dao::GarrisonDao;
struct SimpleDao;
#[async_trait]
impl crate::dao::GarrisonDao for SimpleDao {
async fn get(&self, key: &str) -> crate::error::GarrisonResult<Option<String>> {
Ok(Some(key.to_string()))
}
async fn set(
&self,
_key: &str,
_value: &str,
_ttl: u64,
) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn update(&self, _key: &str, _value: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
crate::atomic_test_fallback!();
}
let dao = SimpleDao;
let _ = dao.set_if_absent("k1", "v1", 60).await;
let _ = dao.get_and_delete("k1").await;
let _ = dao.incr("counter", 60).await;
let _ = dao.decr("counter").await;
let _ = dao.rename("old", "new").await;
let _ = dao.compare_and_swap("k2", Some("old"), "new", 60).await;
}