use crate::account::disable::{DefaultDisableRepository, DisableRepository};
use crate::config::GarrisonConfig;
use crate::core::auth::{AuthLogic, AuthLogicDefault};
use crate::core::permission::{PermissionChecker, PermissionCheckerDefault};
use crate::core::token::TokenStyleFactory;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
#[cfg(feature = "listener")]
use crate::listener::GarrisonListenerManager;
#[cfg(feature = "manager-explicit")]
use crate::manager::explicit::Manager;
use crate::manager::factory::{GarrisonLogicFactoryContext, GarrisonLogicFactoryEntry};
use crate::manager::{GarrisonManager, GARRISON_MANAGER};
use crate::plugin::GarrisonPluginManager;
use crate::session::GarrisonSession;
use crate::stp::util::spawn_cleanup_task;
use crate::stp::{GarrisonInterface, GarrisonLogicDefault};
#[cfg(feature = "anomalous-detector-dual")]
use crate::strategy::firewall::{AnomalousAnalyzerConfig, AnomalousLoginAnalyzer};
use crate::strategy::{GarrisonPermissionStrategy, GarrisonPermissionStrategyDefault, Strategy};
use parking_lot::RwLock;
use std::sync::Arc;
#[cfg(feature = "anomalous-detector-dual")]
use tokio::sync::watch;
use tokio::task::JoinHandle;
pub(crate) struct TaskHandles {
pub(crate) cleanup: Option<Arc<JoinHandle<()>>>,
#[cfg(feature = "anomalous-detector-dual")]
pub(crate) anomalous: Option<Arc<JoinHandle<()>>>,
#[cfg(feature = "anomalous-detector-dual")]
pub(crate) anomalous_shutdown: Option<watch::Sender<bool>>,
}
impl TaskHandles {
#[cfg(feature = "manager-explicit")]
pub(crate) fn empty() -> Self {
Self {
cleanup: None,
#[cfg(feature = "anomalous-detector-dual")]
anomalous: None,
#[cfg(feature = "anomalous-detector-dual")]
anomalous_shutdown: None,
}
}
}
pub struct GarrisonManagerBuilder {
dao: Option<Arc<dyn GarrisonDao>>,
config: Option<Arc<GarrisonConfig>>,
interface: Option<Arc<dyn GarrisonInterface>>,
plugin_manager: Option<Arc<GarrisonPluginManager>>,
#[cfg(feature = "listener")]
listener_manager: Option<Arc<GarrisonListenerManager>>,
auth_logic: Option<Arc<dyn AuthLogic>>,
permission_checker: Option<Arc<dyn PermissionChecker>>,
disable_repository: Option<Arc<dyn DisableRepository>>,
#[cfg(feature = "firewall")]
limiter_runtime: Option<crate::limiteron::LimiterRuntime>,
#[cfg(feature = "three-tier-cache")]
user_cache_service: Option<Arc<crate::cache::UserCacheService>>,
factory: Option<&'static GarrisonLogicFactoryEntry>,
}
impl Default for GarrisonManagerBuilder {
fn default() -> Self {
Self::new()
}
}
static BUILD_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
impl GarrisonManagerBuilder {
pub fn new() -> Self {
Self {
dao: None,
config: None,
interface: None,
plugin_manager: None,
#[cfg(feature = "listener")]
listener_manager: None,
auth_logic: None,
permission_checker: None,
disable_repository: None,
#[cfg(feature = "firewall")]
limiter_runtime: None,
#[cfg(feature = "three-tier-cache")]
user_cache_service: None,
factory: None,
}
}
#[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
async fn prepare_limiter_runtime(&mut self) -> GarrisonResult<()> {
use crate::strategy::rate_limiter_backend::RateLimitBackend;
let (Some(dao), Some(config)) = (self.dao.clone(), self.config.clone()) else {
return Ok(());
};
match &config.rate_limit_backend {
RateLimitBackend::Memory => Ok(()),
RateLimitBackend::Redis { .. } => {
config.validate()?;
let runtime = crate::limiteron::LimiterRuntime::from_config(&config, dao).await?;
self.limiter_runtime = Some(runtime);
tracing::info!(
backend = "redis",
"{}",
crate::i18n::translate_detail("logs-config-rate-limit-redis-active", &[])
);
Ok(())
},
}
}
pub fn dao(mut self, dao: Arc<dyn GarrisonDao>) -> Self {
self.dao = Some(dao);
self
}
pub fn config(mut self, config: Arc<GarrisonConfig>) -> Self {
self.config = Some(config);
self
}
pub fn interface(mut self, interface: Arc<dyn GarrisonInterface>) -> Self {
self.interface = Some(interface);
self
}
pub fn with_plugin_manager(mut self, pm: Arc<GarrisonPluginManager>) -> Self {
self.plugin_manager = Some(pm);
self
}
#[cfg(feature = "listener")]
pub fn with_listener_manager(mut self, lm: Arc<GarrisonListenerManager>) -> Self {
self.listener_manager = Some(lm);
self
}
pub fn with_auth_logic(mut self, al: Arc<dyn AuthLogic>) -> Self {
self.auth_logic = Some(al);
self
}
pub fn with_permission_checker(mut self, pc: Arc<dyn PermissionChecker>) -> Self {
self.permission_checker = Some(pc);
self
}
pub fn with_disable_repository(mut self, dr: Arc<dyn DisableRepository>) -> Self {
self.disable_repository = Some(dr);
self
}
#[cfg(feature = "three-tier-cache")]
pub fn with_user_cache_service(mut self, ucs: Arc<crate::cache::UserCacheService>) -> Self {
self.user_cache_service = Some(ucs);
self
}
pub fn with_factory(mut self, entry: &'static GarrisonLogicFactoryEntry) -> Self {
self.factory = Some(entry);
self
}
#[allow(unused_mut)]
pub async fn build(mut self) -> GarrisonResult<()> {
#[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
self.prepare_limiter_runtime().await?;
let _build_guard = BUILD_LOCK.lock();
let (logic, task_handles) = self.build_logic()?;
let strategy = Arc::new(RwLock::new(Strategy::new(logic.clone())));
GARRISON_MANAGER.logic.store(Some(logic));
GARRISON_MANAGER.strategy.store(Some(strategy));
if let Some(old) = GARRISON_MANAGER.cleanup_task_handle.write().take() {
old.abort();
}
*GARRISON_MANAGER.cleanup_task_handle.write() = task_handles.cleanup;
#[cfg(feature = "anomalous-detector-dual")]
{
if let Some(old) = GARRISON_MANAGER.anomalous_analyzer_handle.write().take() {
old.abort();
}
GARRISON_MANAGER
.anomalous_analyzer_shutdown_tx
.write()
.take();
*GARRISON_MANAGER.anomalous_analyzer_handle.write() = task_handles.anomalous;
*GARRISON_MANAGER.anomalous_analyzer_shutdown_tx.write() =
task_handles.anomalous_shutdown;
}
Ok(())
}
#[cfg(feature = "manager-explicit")]
#[allow(unused_mut)]
pub async fn build_explicit(mut self) -> GarrisonResult<Manager> {
#[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
self.prepare_limiter_runtime().await?;
let (logic, task_handles) = self.build_logic()?;
Ok(Manager::with_task_handles(logic, task_handles))
}
#[allow(unused_variables)]
#[cfg_attr(not(feature = "firewall"), allow(unused_mut))]
fn build_logic(mut self) -> GarrisonResult<(Arc<GarrisonLogicDefault>, TaskHandles)> {
#[cfg(feature = "firewall")]
let limiter_runtime = self.limiter_runtime.take();
let dao = self
.dao
.ok_or_else(|| GarrisonError::Config("builder-dao-missing".to_string()))?;
let config = self
.config
.ok_or_else(|| GarrisonError::Config("builder-config-missing".to_string()))?;
let interface = self
.interface
.ok_or_else(|| GarrisonError::Config("builder-interface-missing".to_string()))?;
config.validate()?;
let timeout = u64::try_from(config.timeout).map_err(|_| {
GarrisonError::Config(format!("manager-timeout-overflow::{}", config.timeout))
})?;
let active_timeout = if config.active_timeout < 0 {
timeout
} else {
u64::try_from(config.active_timeout).map_err(|_| {
GarrisonError::Config(format!(
"manager-active-timeout-overflow::{}",
config.active_timeout
))
})?
};
let remember_me_timeout = config.remember_me_timeout.max(0) as u64;
let session = Arc::new(GarrisonSession::new(
dao.clone(),
timeout,
active_timeout,
remember_me_timeout,
));
let permission_checker: Arc<dyn PermissionChecker> = match self.permission_checker {
Some(pc) => pc,
None => Arc::new(PermissionCheckerDefault::new(interface.clone())),
};
let plugin_manager = match self.plugin_manager {
Some(pm) => pm,
None => Arc::new(GarrisonPluginManager::new()),
};
#[cfg(feature = "listener")]
let listener_manager = match self.listener_manager {
Some(lm) => lm,
None => Arc::new(GarrisonListenerManager::new()),
};
let token_handler: Arc<dyn crate::core::token::Token> =
Arc::from(TokenStyleFactory::new_with_jwt_keys(
&config.token_style,
config.jwt_secret.as_str(),
Some(&config.jwt_algorithm),
config.jwt_rsa_private_key_pem.as_deref(),
config.jwt_ec_private_key_pem.as_deref(),
config.jwt_ed_private_key_pem.as_deref(),
)?);
let auth_logic: Arc<dyn AuthLogic> = match self.auth_logic {
Some(al) => al,
None => Arc::new(
AuthLogicDefault::new(session.clone(), token_handler, config.timeout)
.with_seed_primary_amr(config.seed_primary_amr),
),
};
let firewall_builder = GarrisonPermissionStrategyDefault::new(interface)
.with_permission_checker(permission_checker.clone())
.with_plugin_manager(plugin_manager.clone());
#[cfg(feature = "firewall")]
let firewall_builder = {
use crate::strategy::hooks::GarrisonFirewallCheckHookDefault;
let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao.clone());
#[cfg(feature = "rate-limit-redis")]
let hook = match limiter_runtime {
Some(runtime) => hook.with_limiter_backend(runtime.limiter()),
None => hook,
};
firewall_builder.with_firewall_hook(std::sync::Arc::new(hook))
};
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(firewall_builder);
let disable_repo = match self.disable_repository {
Some(dr) => dr,
None => Arc::new(DefaultDisableRepository::new(dao.clone())),
};
#[cfg(feature = "three-tier-cache")]
let user_cache_service = match self.user_cache_service {
Some(ucs) => ucs,
None => Arc::new(crate::cache::UserCacheService::new_with_capacity(
dao.clone(),
firewall.clone(),
config.l1_cache_ttl_secs,
config.l1_cache_capacity,
config.l2_cache_ttl_secs,
)?),
};
#[cfg(feature = "listener")]
let factory_ctx = GarrisonLogicFactoryContext {
plugin_manager: Some(plugin_manager.clone()),
listener_manager: Some(listener_manager.clone()),
auth_logic: Some(auth_logic.clone()),
permission_checker: Some(permission_checker.clone()),
disable_repository: Some(disable_repo.clone()),
#[cfg(feature = "three-tier-cache")]
user_cache_service: Some(user_cache_service.clone()),
};
#[cfg(not(feature = "listener"))]
let factory_ctx = GarrisonLogicFactoryContext {
plugin_manager: Some(plugin_manager.clone()),
auth_logic: Some(auth_logic.clone()),
permission_checker: Some(permission_checker.clone()),
disable_repository: Some(disable_repo.clone()),
#[cfg(feature = "three-tier-cache")]
user_cache_service: Some(user_cache_service.clone()),
};
#[cfg(feature = "anomalous-detector-dual")]
let (
analyzer_listener_manager,
analyzer_dao,
analyzer_interval_secs,
analyzer_burst_threshold,
) = (
listener_manager.clone(),
dao.clone(),
config.anomalous_analyzer_interval_secs,
config.anomalous_analyzer_burst_threshold,
);
let factory_entry = self.factory.or_else(default_factory_selector);
let logic: Arc<GarrisonLogicDefault> = match factory_entry {
Some(entry) => (entry.factory)(
session.clone(),
config.clone(),
firewall.clone(),
&factory_ctx,
)?,
None => Self::build_logic_via_builder_chain(
session.clone(),
config.clone(),
firewall.clone(),
plugin_manager,
auth_logic,
permission_checker,
disable_repo,
#[cfg(feature = "listener")]
listener_manager,
#[cfg(feature = "three-tier-cache")]
user_cache_service,
),
};
let cleanup_handle =
spawn_cleanup_task(session, config.token_map_cleanup_interval_secs).map(Arc::new);
#[cfg(feature = "anomalous-detector-dual")]
let (anomalous_handle, anomalous_shutdown) = {
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let analyzer_config = AnomalousAnalyzerConfig {
interval_secs: analyzer_interval_secs,
burst_threshold: analyzer_burst_threshold,
..AnomalousAnalyzerConfig::default()
};
let analyzer = AnomalousLoginAnalyzer::new(
analyzer_dao,
analyzer_config,
shutdown_rx,
Some(analyzer_listener_manager),
);
let analyzer_handle = Arc::new(analyzer.start());
(analyzer_handle, shutdown_tx)
};
let task_handles = TaskHandles {
cleanup: cleanup_handle,
#[cfg(feature = "anomalous-detector-dual")]
anomalous: Some(anomalous_handle),
#[cfg(feature = "anomalous-detector-dual")]
anomalous_shutdown: Some(anomalous_shutdown),
};
Ok((logic, task_handles))
}
#[allow(clippy::too_many_arguments)]
#[cfg_attr(
not(any(feature = "listener", feature = "three-tier-cache")),
allow(unused_mut)
)]
fn build_logic_via_builder_chain(
session: Arc<GarrisonSession>,
config: Arc<GarrisonConfig>,
firewall: Arc<dyn GarrisonPermissionStrategy>,
plugin_manager: Arc<GarrisonPluginManager>,
auth_logic: Arc<dyn AuthLogic>,
permission_checker: Arc<dyn PermissionChecker>,
disable_repo: Arc<dyn DisableRepository>,
#[cfg(feature = "listener")] listener_manager: Arc<GarrisonListenerManager>,
#[cfg(feature = "three-tier-cache")] user_cache_service: Arc<
crate::cache::UserCacheService,
>,
) -> Arc<GarrisonLogicDefault> {
#[cfg(feature = "session-hijack-detection")]
let hijack_mode = config.session_hijack_mode;
let mut builder =
GarrisonLogicDefault::new(session.clone(), config, firewall, disable_repo)
.with_plugin_manager(plugin_manager)
.with_auth_logic(auth_logic)
.with_permission_checker(permission_checker);
#[cfg(feature = "listener")]
{
builder = builder.with_listener_manager(listener_manager);
}
#[cfg(feature = "three-tier-cache")]
{
builder = builder.with_user_cache_service(user_cache_service);
}
#[cfg(feature = "session-hijack-detection")]
{
builder = builder.with_anomaly_detector(Arc::new(
crate::strategy::alert::SessionHijackDetector::new(session, hijack_mode),
));
}
Arc::new(builder)
}
}
impl GarrisonManager {
pub fn builder() -> GarrisonManagerBuilder {
GarrisonManagerBuilder::new()
}
}
fn default_factory_selector() -> Option<&'static GarrisonLogicFactoryEntry> {
use std::iter::Iterator;
inventory::iter::<GarrisonLogicFactoryEntry>().next()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GarrisonConfig;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::manager::mock::MockInterface;
use crate::session::GarrisonSession;
use crate::stp::GarrisonInterface;
use async_trait::async_trait;
use serial_test::serial;
use std::sync::Arc;
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_dao() -> Arc<dyn GarrisonDao> {
Arc::new(MockDao::new())
}
#[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
#[tokio::test]
async fn prepare_limiter_runtime_memory_returns_none() {
let mut builder = GarrisonManagerBuilder::new()
.dao(make_dao())
.config(Arc::new(make_config()));
builder.prepare_limiter_runtime().await.unwrap();
assert!(
builder.limiter_runtime.is_none(),
"Memory 配置不应建立 Redis 限流连接"
);
}
fn make_interface() -> Arc<dyn GarrisonInterface> {
Arc::new(MockInterface::new())
}
fn make_default_builder() -> GarrisonManagerBuilder {
GarrisonManagerBuilder::new()
}
fn make_ready_builder() -> GarrisonManagerBuilder {
GarrisonManagerBuilder::new()
.dao(make_dao())
.config(Arc::new(make_config()))
.interface(make_interface())
}
#[cfg(feature = "manager-explicit")]
async fn wait_finished(handle: &JoinHandle<()>) {
for _ in 0..100 {
if handle.is_finished() {
return;
}
tokio::task::yield_now().await;
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
}
#[derive(Clone)]
struct MockAuthLogic;
#[async_trait]
impl AuthLogic for MockAuthLogic {
async fn login(&self, id: &str, _params: Option<&str>) -> GarrisonResult<String> {
Ok(format!("mock-token-{}", id))
}
async fn logout(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn is_login(&self, _token: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn get_login_id(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(Some("mock-user".to_string()))
}
async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
Ok("mock-user".to_string())
}
}
#[derive(Clone)]
struct MockPermissionChecker;
#[async_trait]
impl PermissionChecker for MockPermissionChecker {
async fn has_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn has_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn has_any_permission(&self, _login_id: &str, _perms: &[&str]) -> bool {
true
}
async fn has_all_permissions(&self, _login_id: &str, _perms: &[&str]) -> bool {
true
}
}
#[derive(Clone)]
struct MockDisableRepository;
#[async_trait]
impl DisableRepository for MockDisableRepository {
async fn disable(
&self,
_login_id: &str,
_service: &str,
_until: Option<chrono::DateTime<chrono::Utc>>,
_level: u32,
_duration_secs: u64,
) -> GarrisonResult<()> {
Ok(())
}
async fn untie_disable(&self, _login_id: &str, _service: &str) -> GarrisonResult<()> {
Ok(())
}
async fn is_disable(&self, _login_id: &str, _service: &str) -> GarrisonResult<bool> {
Ok(false)
}
async fn get_disable_time(
&self,
_login_id: &str,
_service: &str,
) -> GarrisonResult<Option<chrono::DateTime<chrono::Utc>>> {
Ok(None)
}
async fn get_disable_level(
&self,
_login_id: &str,
_service: &str,
) -> GarrisonResult<Option<u32>> {
Ok(None)
}
}
#[cfg(feature = "manager-explicit")]
struct CountingDao {
counter: Arc<std::sync::atomic::AtomicUsize>,
}
#[cfg(feature = "manager-explicit")]
#[async_trait]
impl GarrisonDao for CountingDao {
crate::atomic_test_fallback!();
async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
self.counter
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Err(GarrisonError::Dao("test counting".to_string()))
}
async fn set(&self, _key: &str, _value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> GarrisonResult<()> {
Ok(())
}
}
#[test]
fn builder_new_all_fields_none() {
let b = make_default_builder();
assert!(b.dao.is_none());
assert!(b.config.is_none());
assert!(b.interface.is_none());
assert!(b.plugin_manager.is_none());
#[cfg(feature = "listener")]
assert!(b.listener_manager.is_none());
assert!(b.auth_logic.is_none());
assert!(b.permission_checker.is_none());
assert!(b.disable_repository.is_none());
#[cfg(feature = "three-tier-cache")]
assert!(b.user_cache_service.is_none());
assert!(b.factory.is_none());
}
#[test]
fn builder_setters_set_fields() {
let dao = make_dao();
let config = Arc::new(make_config());
let interface = make_interface();
let pm = Arc::new(crate::plugin::GarrisonPluginManager::new());
#[cfg(feature = "listener")]
let lm = Arc::new(crate::listener::GarrisonListenerManager::new());
let auth: Arc<dyn AuthLogic> = Arc::new(MockAuthLogic);
let pc: Arc<dyn PermissionChecker> = Arc::new(MockPermissionChecker);
let dr: Arc<dyn DisableRepository> = Arc::new(MockDisableRepository);
let mut b = make_default_builder();
b = b
.dao(dao)
.config(config)
.interface(interface)
.with_plugin_manager(pm)
.with_auth_logic(auth)
.with_permission_checker(pc)
.with_disable_repository(dr);
#[cfg(feature = "listener")]
{
b = b.with_listener_manager(lm);
}
#[cfg(feature = "three-tier-cache")]
{
let dao2 = make_dao();
let fw: Arc<dyn GarrisonPermissionStrategy> =
Arc::new(GarrisonPermissionStrategyDefault::new(make_interface()));
let ucs = Arc::new(crate::cache::UserCacheService::new(dao2, fw, 60, 3600).unwrap());
b = b.with_user_cache_service(ucs);
}
assert!(b.dao.is_some());
assert!(b.config.is_some());
assert!(b.interface.is_some());
assert!(b.plugin_manager.is_some());
#[cfg(feature = "listener")]
assert!(b.listener_manager.is_some());
assert!(b.auth_logic.is_some());
assert!(b.permission_checker.is_some());
assert!(b.disable_repository.is_some());
#[cfg(feature = "three-tier-cache")]
assert!(b.user_cache_service.is_some());
assert!(b.factory.is_none());
}
#[test]
fn builder_with_factory_sets_field() {
static TEST_ENTRY: GarrisonLogicFactoryEntry = GarrisonLogicFactoryEntry {
name: "test-factory-setter",
factory: crate::manager::factory::garrison_logic_factory_default,
};
let b = make_default_builder().with_factory(&TEST_ENTRY);
assert!(b.factory.is_some());
assert_eq!(b.factory.unwrap().name, "test-factory-setter");
}
#[tokio::test]
#[serial]
async fn build_injects_global_singleton() {
GarrisonManager::reset_for_test();
let result = make_ready_builder().build().await;
assert!(result.is_ok(), "build 应成功: {:?}", result.map(|_| ()));
assert!(GarrisonManager::is_initialized());
GarrisonManager::reset_for_test();
}
#[cfg(feature = "manager-explicit")]
#[tokio::test]
#[serial]
async fn build_explicit_returns_independent_manager() {
GarrisonManager::reset_for_test();
let manager = make_ready_builder().build_explicit().await;
assert!(
manager.is_ok(),
"build_explicit 应成功: {:?}",
manager.err()
);
assert!(
!GarrisonManager::is_initialized(),
"build_explicit 不应触碰全局单例"
);
drop(manager);
assert!(!GarrisonManager::is_initialized());
}
#[cfg(feature = "manager-explicit")]
#[tokio::test]
async fn build_explicit_drop_aborts_tasks() {
let mut config = make_config();
config.token_map_cleanup_interval_secs = 1;
let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let dao: Arc<dyn GarrisonDao> = Arc::new(CountingDao {
counter: counter.clone(),
});
let builder = GarrisonManagerBuilder::new()
.dao(dao)
.config(Arc::new(config))
.interface(make_interface());
let (logic, task_handles) = builder.build_logic().unwrap();
let cleanup_handle = task_handles.cleanup.clone().unwrap();
#[cfg(feature = "anomalous-detector-dual")]
let anomalous_handle = task_handles.anomalous.clone().unwrap();
#[cfg(feature = "anomalous-detector-dual")]
let anomalous_shutdown = task_handles.anomalous_shutdown.clone();
let manager = Manager::with_task_handles(logic, task_handles);
assert!(
!cleanup_handle.is_finished(),
"build 后 cleanup task 应运行中"
);
manager.logic.session.add_login_token("1001", "token1");
tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
let count_before = counter.load(std::sync::atomic::Ordering::SeqCst);
assert!(
count_before >= 1,
"drop 前 cleanup task 应已运行(计数>=1)"
);
drop(manager);
wait_finished(&cleanup_handle).await;
assert!(
cleanup_handle.is_finished(),
"Manager Drop 后 cleanup task 应被 abort"
);
#[cfg(feature = "anomalous-detector-dual")]
{
wait_finished(&anomalous_handle).await;
assert!(
anomalous_handle.is_finished(),
"Manager Drop 后 anomalous task 应被 abort"
);
drop(anomalous_shutdown);
}
let count_mid = counter.load(std::sync::atomic::Ordering::SeqCst);
tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
let count_after = counter.load(std::sync::atomic::Ordering::SeqCst);
assert!(
count_after <= count_mid + 1,
"abort 后 cleanup task 不应继续运行。mid={}, after={}",
count_mid,
count_after
);
}
#[tokio::test]
#[serial]
async fn build_injects_plugin_manager() {
GarrisonManager::reset_for_test();
let pm = Arc::new(crate::plugin::GarrisonPluginManager::new());
make_ready_builder()
.with_plugin_manager(pm.clone())
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
Arc::ptr_eq(logic.plugin_manager.as_ref().unwrap(), &pm),
"build 后 plugin_manager 应为注入实例"
);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "listener")]
#[tokio::test]
#[serial]
async fn build_injects_listener_manager() {
GarrisonManager::reset_for_test();
let lm = Arc::new(crate::listener::GarrisonListenerManager::new());
make_ready_builder()
.with_listener_manager(lm.clone())
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
Arc::ptr_eq(logic.listener_manager.as_ref().unwrap(), &lm),
"build 后 listener_manager 应为注入实例"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_injects_auth_logic() {
GarrisonManager::reset_for_test();
let al: Arc<dyn AuthLogic> = Arc::new(MockAuthLogic);
make_ready_builder()
.with_auth_logic(al.clone())
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
Arc::ptr_eq(&logic.auth_logic.as_ref().unwrap().clone(), &al),
"build 后 auth_logic 应为注入实例"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_injects_permission_checker() {
GarrisonManager::reset_for_test();
let pc: Arc<dyn PermissionChecker> = Arc::new(MockPermissionChecker);
make_ready_builder()
.with_permission_checker(pc.clone())
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
Arc::ptr_eq(&logic.permission_checker.as_ref().unwrap().clone(), &pc),
"build 后 permission_checker 应为注入实例"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_injects_disable_repository() {
GarrisonManager::reset_for_test();
let dr: Arc<dyn DisableRepository> = Arc::new(MockDisableRepository);
make_ready_builder()
.with_disable_repository(dr.clone())
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
Arc::ptr_eq(&logic.disable_repository, &dr),
"build 后 disable_repository 应为注入实例"
);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "manager-explicit")]
#[tokio::test]
#[serial]
async fn build_explicit_garrison_util_returns_manager_not_init() {
GarrisonManager::reset_for_test();
let _manager = make_ready_builder().build_explicit().await.unwrap();
let result = crate::stp::GarrisonUtil::login_simple("1001").await;
assert!(
matches!(
result,
Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")
),
"build_explicit 路径下 GarrisonUtil 应返回 manager-not-init,实际: {:?}",
result.map(|_| ())
);
drop(_manager);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_garrison_util_works_normally() {
GarrisonManager::reset_for_test();
make_ready_builder().build().await.unwrap();
let token = crate::stp::GarrisonUtil::login_simple("1001").await;
assert!(token.is_ok(), "build 路径下 GarrisonUtil 应正常工作");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_sets_cleanup_task_handle() {
GarrisonManager::reset_for_test();
let mut config = make_config();
config.token_map_cleanup_interval_secs = 1;
let builder = GarrisonManagerBuilder::new()
.dao(make_dao())
.config(Arc::new(config))
.interface(make_interface());
builder.build().await.unwrap();
assert!(
GARRISON_MANAGER.cleanup_task_handle.read().is_some(),
"interval > 0 时 build 后应持有 cleanup task handle"
);
GarrisonManager::reset_for_test();
assert!(
GARRISON_MANAGER.cleanup_task_handle.read().is_none(),
"reset_for_test 后 cleanup task handle 应为 None"
);
}
#[tokio::test]
#[serial]
async fn build_missing_dao_fails_closed() {
GarrisonManager::reset_for_test();
let builder = GarrisonManagerBuilder::new()
.config(Arc::new(make_config()))
.interface(make_interface());
let result = builder.build().await;
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m == "builder-dao-missing"),
"dao=None 应返回 builder-dao-missing,实际: {:?}",
result.map(|_| ())
);
assert!(!GarrisonManager::is_initialized(), "失败后单例不应被初始化");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_missing_config_fails_closed() {
GarrisonManager::reset_for_test();
let builder = GarrisonManagerBuilder::new()
.dao(make_dao())
.interface(make_interface());
let result = builder.build().await;
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m == "builder-config-missing"),
"config=None 应返回 builder-config-missing,实际: {:?}",
result.map(|_| ())
);
assert!(!GarrisonManager::is_initialized());
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn build_missing_interface_fails_closed() {
GarrisonManager::reset_for_test();
let builder = GarrisonManagerBuilder::new()
.dao(make_dao())
.config(Arc::new(make_config()));
let result = builder.build().await;
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m == "builder-interface-missing"),
"interface=None 应返回 builder-interface-missing,实际: {:?}",
result.map(|_| ())
);
assert!(!GarrisonManager::is_initialized());
GarrisonManager::reset_for_test();
}
static TEST_MARKER_ENTRY: GarrisonLogicFactoryEntry = GarrisonLogicFactoryEntry {
name: "test-marker",
factory: test_marker_factory,
};
fn test_marker_factory(
session: Arc<GarrisonSession>,
config: Arc<GarrisonConfig>,
firewall: Arc<dyn GarrisonPermissionStrategy>,
ctx: &GarrisonLogicFactoryContext,
) -> GarrisonResult<Arc<GarrisonLogicDefault>> {
let disable_repository = ctx.disable_repository.clone().unwrap_or_else(|| {
Arc::new(crate::account::disable::DefaultDisableRepository::new(
session.dao().clone(),
)) as Arc<dyn crate::account::disable::DisableRepository>
});
let mut builder = GarrisonLogicDefault::new(session, config, firewall, disable_repository);
if let Some(pm) = ctx.plugin_manager.clone() {
builder = builder.with_plugin_manager(pm);
}
#[cfg(feature = "listener")]
if let Some(lm) = ctx.listener_manager.clone() {
builder = builder.with_listener_manager(lm);
}
if let Some(auth) = ctx.auth_logic.clone() {
builder = builder.with_auth_logic(auth);
}
if let Some(pc) = ctx.permission_checker.clone() {
builder = builder.with_permission_checker(pc);
}
Ok(Arc::new(builder.with_marker("custom-factory")))
}
#[tokio::test]
#[serial]
async fn build_with_factory_uses_custom_marker() {
GarrisonManager::reset_for_test();
make_ready_builder()
.with_factory(&TEST_MARKER_ENTRY)
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert_eq!(
logic.marker,
Some("custom-factory"),
"with_factory 应使用自定义 factory 构造 logic"
);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "three-tier-cache")]
#[tokio::test]
#[serial]
async fn build_injects_user_cache_service() {
GarrisonManager::reset_for_test();
let fw: Arc<dyn GarrisonPermissionStrategy> =
Arc::new(GarrisonPermissionStrategyDefault::new(make_interface()));
let custom_ucs =
Arc::new(crate::cache::UserCacheService::new(make_dao(), fw, 60, 3600).unwrap());
make_ready_builder()
.with_user_cache_service(custom_ucs.clone())
.build()
.await
.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
Arc::ptr_eq(logic.user_cache_service.as_ref().unwrap(), &custom_ucs),
"build 后 user_cache_service 应为注入实例"
);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "three-tier-cache")]
#[tokio::test]
#[serial]
async fn build_auto_constructs_user_cache_service() {
GarrisonManager::reset_for_test();
make_ready_builder().build().await.unwrap();
let logic = GarrisonManager::logic().unwrap();
assert!(
logic.user_cache_service.is_some(),
"three-tier-cache feature 下未注入时 build 应自动构造 user_cache_service"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
async fn build_logic_via_builder_chain_constructs_default_managers() {
let dao = make_dao();
let config = Arc::new(make_config());
let interface = make_interface();
let timeout = u64::try_from(config.timeout).unwrap();
let session = Arc::new(GarrisonSession::new(dao, timeout, timeout, 0));
let firewall: Arc<dyn GarrisonPermissionStrategy> =
Arc::new(GarrisonPermissionStrategyDefault::new(interface));
let plugin_manager = Arc::new(crate::plugin::GarrisonPluginManager::new());
#[cfg(feature = "listener")]
let listener_manager = Arc::new(crate::listener::GarrisonListenerManager::new());
let auth_logic: Arc<dyn AuthLogic> = Arc::new(MockAuthLogic);
let permission_checker: Arc<dyn PermissionChecker> = Arc::new(MockPermissionChecker);
let disable_repo: Arc<dyn DisableRepository> = Arc::new(MockDisableRepository);
#[cfg(feature = "three-tier-cache")]
let firewall_for_cache = firewall.clone();
let logic = GarrisonManagerBuilder::build_logic_via_builder_chain(
session,
config,
firewall,
plugin_manager,
auth_logic,
permission_checker,
disable_repo,
#[cfg(feature = "listener")]
listener_manager,
#[cfg(feature = "three-tier-cache")]
Arc::new(
crate::cache::UserCacheService::new(make_dao(), firewall_for_cache, 60, 3600)
.unwrap(),
),
);
assert!(
logic.plugin_manager.is_some(),
"兜底 logic 应注入 plugin_manager"
);
#[cfg(feature = "listener")]
assert!(
logic.listener_manager.is_some(),
"兜底 logic 应注入 listener_manager"
);
assert!(logic.auth_logic.is_some(), "兜底 logic 应注入 auth_logic");
assert!(
logic.permission_checker.is_some(),
"兜底 logic 应注入 permission_checker"
);
}
#[cfg(feature = "manager-explicit")]
#[test]
fn task_handles_empty_all_fields_none() {
let handles = TaskHandles::empty();
assert!(handles.cleanup.is_none(), "empty() cleanup 应为 None");
#[cfg(feature = "anomalous-detector-dual")]
assert!(handles.anomalous.is_none(), "empty() anomalous 应为 None");
#[cfg(feature = "anomalous-detector-dual")]
assert!(
handles.anomalous_shutdown.is_none(),
"empty() anomalous_shutdown 应为 None"
);
}
#[tokio::test]
async fn build_logic_missing_dao_returns_error() {
let config = Arc::new(make_config());
let interface = make_interface();
let timeout = u64::try_from(config.timeout).unwrap();
let session = Arc::new(crate::session::GarrisonSession::new(
make_dao(),
timeout,
timeout,
0,
));
let firewall: Arc<dyn crate::strategy::GarrisonPermissionStrategy> = Arc::new(
crate::strategy::GarrisonPermissionStrategyDefault::new(interface),
);
let plugin_manager = Arc::new(crate::plugin::GarrisonPluginManager::new());
let auth_logic: Arc<dyn crate::core::auth::AuthLogic> = Arc::new(MockAuthLogic);
let permission_checker: Arc<dyn crate::core::permission::PermissionChecker> =
Arc::new(MockPermissionChecker);
let disable_repo: Arc<dyn crate::account::disable::DisableRepository> =
Arc::new(MockDisableRepository);
let result = GarrisonManagerBuilder::build_logic_via_builder_chain(
session,
config,
firewall,
plugin_manager,
auth_logic,
permission_checker,
disable_repo,
#[cfg(feature = "listener")]
Arc::new(crate::listener::GarrisonListenerManager::new()),
#[cfg(feature = "three-tier-cache")]
{
let dao2 = make_dao();
let fw2: Arc<dyn crate::strategy::GarrisonPermissionStrategy> = Arc::new(
crate::strategy::GarrisonPermissionStrategyDefault::new(make_interface()),
);
Arc::new(crate::cache::UserCacheService::new(dao2, fw2, 60, 3600).unwrap())
},
);
assert!(result.plugin_manager.is_some());
}
#[tokio::test]
async fn mock_methods_coverage_auth_logic_permission_checker_disable_repo() {
let logic = MockAuthLogic;
assert!(logic.login("u1", None).await.is_ok());
assert!(logic.logout("t1").await.is_ok());
assert!(logic.is_login("t1").await.is_ok());
assert!(logic.get_login_id("t1").await.is_ok());
assert!(logic.verify_token("t1").await.is_ok());
let pc = MockPermissionChecker;
assert!(pc.has_permission("u1", "p1").await.is_ok());
assert!(pc.has_role("u1", "r1").await.is_ok());
assert!(pc.has_any_permission("u1", &["p1", "p2"]).await);
assert!(pc.has_all_permissions("u1", &["p1", "p2"]).await);
let dr = MockDisableRepository;
assert!(dr.disable("u1", "svc", None, 0, 0).await.is_ok());
assert!(dr.untie_disable("u1", "svc").await.is_ok());
assert!(dr.is_disable("u1", "svc").await.is_ok());
assert!(dr.get_disable_time("u1", "svc").await.is_ok());
assert!(dr.get_disable_level("u1", "svc").await.is_ok());
}
#[test]
fn builder_default_returns_empty_builder() {
let b = GarrisonManagerBuilder::default();
assert!(b.dao.is_none());
assert!(b.config.is_none());
assert!(b.interface.is_none());
}
}