use std::sync::Arc;
use crate::core::permission::{AuthRequest, Decision, DecisionReason};
use crate::error::{GarrisonError, GarrisonResult};
use crate::manager::builder::TaskHandles;
use crate::stp::{GarrisonLogicDefault, PermissionLogic};
pub struct Manager {
pub(crate) logic: Arc<GarrisonLogicDefault>,
task_handles: TaskHandles,
}
impl Manager {
pub fn new(logic: Arc<GarrisonLogicDefault>) -> Self {
Self {
logic,
task_handles: TaskHandles::empty(),
}
}
pub(crate) fn with_task_handles(
logic: Arc<GarrisonLogicDefault>,
task_handles: TaskHandles,
) -> Self {
Self {
logic,
task_handles,
}
}
pub async fn authorize(&self, req: &AuthRequest) -> GarrisonResult<Decision> {
let trace_id = Some(uuid::Uuid::now_v7().to_string());
match self.logic.check_permission(&req.action).await {
Ok(()) => Ok(Decision {
trace_id,
..Decision::allow()
}),
Err(GarrisonError::NotPermission(_)) => Ok(Decision {
trace_id,
..Decision::deny(DecisionReason::NoMatchingPermission)
}),
Err(e) => Err(e),
}
}
pub async fn check_permission(&self, login_id: &str, permission: &str) -> GarrisonResult<bool> {
let _ = login_id;
match self.logic.check_permission(permission).await {
Ok(()) => Ok(true),
Err(GarrisonError::NotPermission(_)) => Ok(false),
Err(e) => Err(e),
}
}
}
impl Drop for Manager {
fn drop(&mut self) {
if let Some(handle) = self.task_handles.cleanup.take() {
handle.abort();
}
#[cfg(feature = "anomalous-detector-dual")]
{
if let Some(handle) = self.task_handles.anomalous.take() {
handle.abort();
}
self.task_handles.anomalous_shutdown.take();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GarrisonConfig;
use crate::context::tenant::with_default_tenant;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::manager::GarrisonManager;
use crate::session::GarrisonSession;
use crate::stp::{
with_current_token, GarrisonInterface, GarrisonLogicDefault, GarrisonUtil, LoginParams,
SessionLogic,
};
use crate::strategy::{GarrisonPermissionStrategy, GarrisonPermissionStrategyDefault};
use async_trait::async_trait;
use serial_test::serial;
use std::collections::HashMap;
use std::future::Future;
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 with_permission(mut self, login_id: &str, perms: &[&str]) -> Self {
self.permissions.insert(
login_id.to_string(),
perms.iter().map(|s| s.to_string()).collect(),
);
self
}
}
#[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_config() -> GarrisonConfig {
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
config.throw_on_not_login = false;
config
}
fn make_logic(interface: Arc<dyn GarrisonInterface>) -> Arc<GarrisonLogicDefault> {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = Arc::new(make_config());
let timeout = u64::try_from(config.timeout).unwrap();
let session = Arc::new(GarrisonSession::new(dao.clone(), timeout, timeout, 0));
let firewall: Arc<dyn GarrisonPermissionStrategy> =
Arc::new(GarrisonPermissionStrategyDefault::new(interface));
Arc::new(GarrisonLogicDefault::new(
session,
config,
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
))
}
async fn with_token<R>(token: String, f: impl Future<Output = R>) -> R {
with_current_token(token, f).await
}
#[tokio::test]
async fn manager_new_construction_succeeds() {
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
let logic = make_logic(interface);
let strong_count_before = Arc::strong_count(&logic);
let manager = Manager::new(Arc::clone(&logic));
assert_eq!(
Arc::strong_count(&logic),
strong_count_before + 1,
"Manager::new 应增加 logic 引用计数"
);
drop(manager);
assert_eq!(
Arc::strong_count(&logic),
strong_count_before,
"Drop Manager 后引用计数应恢复"
);
}
#[tokio::test]
async fn manager_authorize_returns_decision() {
let interface: Arc<dyn GarrisonInterface> =
Arc::new(MockInterface::new().with_permission("1001", &["user:read"]));
let logic = make_logic(interface);
let manager = Manager::new(Arc::clone(&logic));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let req = AuthRequest::new("1001", "user:read");
let result = with_token(token, async {
with_default_tenant(async { manager.authorize(&req).await }).await
})
.await;
assert!(result.is_ok(), "authorize 应返回 Ok: {:?}", result.err());
let decision = result.unwrap();
let _ = decision.allowed;
let _ = decision.reason;
}
#[tokio::test]
async fn manager_authorize_with_allowed_returns_true() {
let interface: Arc<dyn GarrisonInterface> =
Arc::new(MockInterface::new().with_permission("1001", &["user:read"]));
let logic = make_logic(interface);
let manager = Manager::new(Arc::clone(&logic));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let req = AuthRequest::new("1001", "user:read");
let decision = with_token(token, async {
with_default_tenant(async { manager.authorize(&req).await }).await
})
.await
.expect("authorize ok");
assert!(decision.allowed, "持有权限应 allowed=true");
assert_eq!(
decision.reason,
DecisionReason::ExplicitAllow,
"持有权限 reason 应为 ExplicitAllow"
);
}
#[tokio::test]
async fn manager_authorize_with_denied_returns_false() {
let interface: Arc<dyn GarrisonInterface> =
Arc::new(MockInterface::new().with_permission("1001", &["user:read"]));
let logic = make_logic(interface);
let manager = Manager::new(Arc::clone(&logic));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let req = AuthRequest::new("1001", "user:delete");
let decision = with_token(token, async {
with_default_tenant(async { manager.authorize(&req).await }).await
})
.await
.expect("authorize 应返回 Ok(Decision deny) 而非 Err");
assert!(!decision.allowed, "未持有权限应 allowed=false");
assert_eq!(
decision.reason,
DecisionReason::NoMatchingPermission,
"未持有权限 reason 应为 NoMatchingPermission"
);
}
#[serial]
#[tokio::test]
async fn manager_check_permission_delegates_to_logic() {
let interface: Arc<dyn GarrisonInterface> =
Arc::new(MockInterface::new().with_permission("1001", &["user:read"]));
let logic = make_logic(interface);
let manager = Manager::new(Arc::clone(&logic));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let logic_held = with_token(token.clone(), async {
with_default_tenant(async { logic.check_permission("user:read").await }).await
})
.await;
let mgr_held = with_token(token.clone(), async {
with_default_tenant(async { manager.check_permission("1001", "user:read").await }).await
})
.await;
assert!(logic_held.is_ok(), "logic 持有权限应 Ok(())");
assert!(
mgr_held.expect("manager check_permission ok"),
"manager 持有权限应 Ok(true)"
);
let logic_denied = with_token(token.clone(), async {
with_default_tenant(async { logic.check_permission("user:delete").await }).await
})
.await;
let mgr_denied = with_token(token.clone(), async {
with_default_tenant(async { manager.check_permission("1001", "user:delete").await })
.await
})
.await;
assert!(
matches!(logic_denied, Err(GarrisonError::NotPermission(_))),
"logic 未持有应 Err(NotPermission)"
);
assert!(
!mgr_denied.expect("manager check_permission ok"),
"manager 未持有应 Ok(false)"
);
}
#[tokio::test]
#[serial]
async fn manager_drop_does_not_affect_global_singleton() {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = Arc::new(make_config());
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
GarrisonManager::builder()
.dao(dao)
.config(config)
.interface(interface)
.build()
.await
.unwrap();
assert!(GarrisonManager::is_initialized());
let logic = GarrisonManager::logic().unwrap();
let strong_count_before = Arc::strong_count(&logic);
{
let _manager = Manager::new(Arc::clone(&logic));
assert_eq!(
Arc::strong_count(&logic),
strong_count_before + 1,
"Manager 构造后引用计数 +1"
);
}
assert_eq!(
Arc::strong_count(&logic),
strong_count_before,
"Drop Manager 后引用计数应恢复"
);
assert!(
GarrisonManager::is_initialized(),
"Drop Manager 后全局单例应仍初始化"
);
let token = GarrisonUtil::login_simple("2002").await.unwrap();
assert!(!token.is_empty(), "全局单例 login 仍应正常工作");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[cfg(feature = "anomalous-detector-dual")]
async fn build_explicit_drop_aborts_tasks() {
let mut config = make_config();
config.token_map_cleanup_interval_secs = 1;
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface::new());
let manager = GarrisonManager::builder()
.dao(dao)
.config(Arc::new(config))
.interface(interface)
.build_explicit()
.await
.expect("build_explicit ok");
let cleanup_handle = manager
.task_handles
.cleanup
.clone()
.expect("cleanup handle");
let anomalous_handle = manager
.task_handles
.anomalous
.clone()
.expect("anomalous handle");
drop(manager);
for _ in 0..100 {
if cleanup_handle.is_finished() && anomalous_handle.is_finished() {
break;
}
tokio::task::yield_now().await;
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert!(
cleanup_handle.is_finished(),
"build_explicit 路径 Manager Drop 后 cleanup task 应被 abort"
);
assert!(
anomalous_handle.is_finished(),
"build_explicit 路径 Manager Drop 后 anomalous task 应被 abort"
);
}
}