#![allow(clippy::useless_conversion)]
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use super::mock::MockUserRepository;
use super::mock::{
MockDao, MockFirewall, MockInterface, MockInterfaceWithLoginType, MockInterfaceWithPerms,
};
use super::*;
use crate::config::{OverflowLogoutMode, ReplacedLoginExitMode};
use crate::context::tenant::with_default_tenant;
use crate::core::token::Token;
use crate::dao::GarrisonDao;
use crate::manager::GarrisonManager;
use crate::session::token_key;
use async_trait::async_trait;
#[cfg(feature = "listener")]
use parking_lot::Mutex;
use serial_test::serial;
use std::collections::HashMap;
use std::time::Duration;
fn make_logic(
timeout: u64,
active_timeout: u64,
throw_on_not_login: bool,
token_style: &str,
has_permission: bool,
has_role: bool,
) -> GarrisonLogicDefault {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone(),
timeout,
active_timeout,
0,
));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = throw_on_not_login;
config.token_style = token_style.to_string();
if token_style == "simple" {
config.jwt_secret = test_jwt_secret(STP_SIMPLE_TEST_SECRET);
}
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission,
has_role,
});
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
}
const STP_SIMPLE_TEST_SECRET: &str = "stp-simple-test-secret-0123456789abcd";
fn test_jwt_secret(secret: &str) -> crate::config::JwtSecret {
#[cfg(feature = "protocol-zeroize")]
{
secret.to_string().into()
}
#[cfg(not(feature = "protocol-zeroize"))]
{
secret.to_string()
}
}
fn make_logic_with_dao(
timeout: u64,
active_timeout: u64,
throw_on_not_login: bool,
token_style: &str,
has_permission: bool,
has_role: bool,
) -> (Arc<MockDao>, GarrisonLogicDefault) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
timeout,
active_timeout,
0,
));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = throw_on_not_login;
config.token_style = token_style.to_string();
if token_style == "simple" {
config.jwt_secret = test_jwt_secret(STP_SIMPLE_TEST_SECRET);
}
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission,
has_role,
});
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
);
(dao, logic)
}
async fn set_account_token_stamps(dao: &Arc<MockDao>, login_id: &str, stamps: &[i64]) {
let key = crate::session::account_key(login_id);
let json = dao
.get(&key)
.await
.unwrap()
.expect("account session 应已由登录创建");
let mut account: crate::session::AccountSession = serde_json::from_str(&json).unwrap();
assert_eq!(
account.tokens.len(),
stamps.len(),
"token 条数与注入时间戳条数应一致(前置登录次数与测试设计不符)"
);
for (ti, stamp) in account.tokens.iter_mut().zip(stamps) {
ti.last_active_at = *stamp;
}
let json = serde_json::to_string(&account).unwrap();
dao.set(&key, &json, 86400).await.unwrap();
}
async fn with_token<R>(token: &str, f: impl std::future::Future<Output = R>) -> R {
with_current_token(token.to_string(), f).await
}
async fn init_global_manager(throw_on_not_login: bool) {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
config.throw_on_not_login = throw_on_not_login;
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao)
.config(Arc::new(config))
.interface(interface)
.build()
.await
.unwrap();
}
#[cfg(feature = "protocol-apikey")]
async fn init_global_manager_with_dao(throw_on_not_login: bool) -> Arc<MockDao> {
GarrisonManager::reset_for_test();
let dao = Arc::new(MockDao::new());
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
config.throw_on_not_login = throw_on_not_login;
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao.clone() as Arc<dyn GarrisonDao>)
.config(Arc::new(config))
.interface(interface)
.build()
.await
.unwrap();
dao
}
async fn init_global_manager_with_perms(
throw_on_not_login: bool,
permissions: Vec<String>,
roles: Vec<String>,
) {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
config.throw_on_not_login = throw_on_not_login;
let interface: Arc<dyn GarrisonInterface> =
Arc::new(MockInterfaceWithPerms { permissions, roles });
GarrisonManager::builder()
.dao(dao)
.config(Arc::new(config))
.interface(interface)
.build()
.await
.unwrap();
}
#[serial]
#[tokio::test]
async fn login_creates_session_and_returns_token() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
assert!(!token.is_empty(), "login 应返回非空 token");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.unwrap();
assert_eq!(ts.login_id, "1001".to_string());
}
#[serial]
#[tokio::test]
async fn login_repeated_creates_multiple_tokens() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let t1 = logic.login("1001", &LoginParams::default()).await.unwrap();
let t2 = logic.login("1001", &LoginParams::default()).await.unwrap();
assert_ne!(t1, t2, "重复登录应生成不同 token");
let as_ = logic
.session
.get_account_session("1001")
.await
.unwrap()
.unwrap();
assert_eq!(as_.tokens.len(), 2);
}
#[serial]
#[tokio::test]
async fn login_with_random_64_style() {
let logic = make_logic(3600, 86400, false, "random_64", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
assert_eq!(token.len(), 64, "random_64 应生成 64 字符 token");
}
#[cfg(feature = "secure-simple-token")]
#[serial]
#[tokio::test]
async fn login_with_simple_style() {
let logic = make_logic(3600, 86400, false, "simple", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
assert!(token.contains('.'), "simple token 应含 HMAC '.' 分隔符");
}
#[cfg(not(feature = "secure-simple-token"))]
#[serial]
#[tokio::test]
async fn login_simple_without_feature_fails_closed() {
let logic = make_logic(3600, 86400, false, "simple", true, true);
let result = logic.login("1001", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::Config(_))),
"无 secure-simple-token 时 simple style 应 fail-closed 返回 Config 错误"
);
}
#[serial]
#[tokio::test]
async fn create_token_unknown_style_errors() {
let logic = make_logic(3600, 86400, false, "unknown_style", true, true);
let result = logic.login("1001", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("stp-unknown-token-style")),
"未知 token_style 应返回含 'stp-unknown-token-style' 的 Config 错误,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn login_with_custom_token() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
logic
.login_with_token("1001", "custom-token-123")
.await
.unwrap();
let ts = logic
.session
.get_token_session("custom-token-123")
.await
.unwrap()
.unwrap();
assert_eq!(ts.login_id, "1001".to_string());
assert_eq!(ts.token, "custom-token-123");
}
#[serial]
#[tokio::test]
async fn logout_destroys_current_token() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token.clone(), async {
logic.logout().await.unwrap();
})
.await;
let ts = logic.session.get_token_session(&token).await.unwrap();
assert!(ts.is_none(), "logout 后 Token-Session 应删除");
}
#[serial]
#[tokio::test]
async fn logout_when_not_logged_in_is_noop() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.logout().await;
assert!(result.is_ok(), "未登录时 logout 应幂等返回 Ok");
}
#[serial]
#[tokio::test]
async fn logout_by_login_id_destroys_all_tokens() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let t1 = logic.login("1001", &LoginParams::default()).await.unwrap();
let t2 = logic.login("1001", &LoginParams::default()).await.unwrap();
logic.logout_by_login_id("1001").await.unwrap();
assert!(logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none());
assert!(logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_none());
assert!(logic
.session
.get_account_session("1001")
.await
.unwrap()
.is_none());
}
#[serial]
#[tokio::test]
async fn kickout_by_account_destroys_session() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
logic.kickout("1001").await.unwrap();
assert!(logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_none());
assert!(logic
.session
.get_account_session("1001")
.await
.unwrap()
.is_none());
}
#[serial]
#[tokio::test]
async fn kickout_by_token_destroys_token_session() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
logic.kickout_by_token(&token).await.unwrap();
assert!(logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_none());
}
#[tokio::test]
#[serial]
async fn invalidate_sessions_after_password_change_destroys_all_sessions() {
init_global_manager(false).await;
let logic = GarrisonManager::logic().unwrap();
let t1 = logic
.login("pwd-change-user", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("pwd-change-user", &LoginParams::default())
.await
.unwrap();
assert!(logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_some());
assert!(logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_some());
GarrisonUtil::invalidate_sessions_after_password_change("pwd-change-user")
.await
.unwrap();
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none(),
"密码修改后 t1 应失效"
);
assert!(
logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_none(),
"密码修改后 t2 应失效"
);
assert!(
logic
.session
.get_account_session("pwd-change-user")
.await
.unwrap()
.is_none(),
"密码修改后 Account-Session 应被清除"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
async fn check_login_returns_true_for_valid_token() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "有效 token 应返回 true");
})
.await;
}
#[tokio::test]
async fn check_login_returns_false_for_invalid_token() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
with_current_token("invalid-token".to_string(), async {
let valid = logic.check_login().await.unwrap();
assert!(!valid, "无效 token 应返回 false");
})
.await;
}
#[tokio::test]
async fn check_login_returns_false_when_no_token() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let valid = logic.check_login().await.unwrap();
assert!(!valid, "未设置 token 应返回 false");
}
#[tokio::test]
async fn check_login_throws_when_throw_on_not_login() {
let logic = make_logic(3600, 86400, true, "uuid", true, true);
let result = logic.check_login().await;
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"throw_on_not_login=true 且未登录应抛 Session 错误"
);
}
#[tokio::test]
async fn check_login_returns_false_for_expired_token() {
let logic = Arc::new(make_logic(1, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(!valid, "过期 token 应返回 false");
})
.await;
}
#[tokio::test]
async fn check_access_token_delegates_to_check_login() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let result = logic.check_access_token().await;
assert!(
result.is_ok(),
"已登录时 check_access_token 应返回 Ok,实际: {:?}",
result
);
})
.await;
}
#[tokio::test]
async fn check_client_token_delegates_to_check_login() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let result = logic.check_client_token().await;
assert!(
result.is_ok(),
"已登录时 check_client_token 应返回 Ok,实际: {:?}",
result
);
})
.await;
}
#[tokio::test]
async fn check_temp_token_delegates_to_check_login() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let result = logic.check_temp_token().await;
assert!(
result.is_ok(),
"已登录时 check_temp_token 应返回 Ok,实际: {:?}",
result
);
})
.await;
}
#[tokio::test]
async fn get_login_id_returns_current_login_id() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let login_id = logic.get_login_id().await.unwrap();
assert_eq!(login_id, Some("1001".to_string()));
})
.await;
}
#[tokio::test]
async fn get_login_id_returns_none_when_not_logged_in() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let login_id = logic.get_login_id().await.unwrap();
assert_eq!(login_id, None, "未登录应返回 None");
}
#[tokio::test]
async fn get_login_id_returns_none_for_invalid_token() {
let logic = Arc::new(make_logic(3600, 86400, false, "uuid", true, true));
with_current_token("invalid-token".to_string(), async {
let login_id = logic.get_login_id().await.unwrap();
assert_eq!(login_id, None, "无效 token 应返回 None");
})
.await;
}
#[serial]
#[test]
fn current_token_errors_when_not_set() {
let result = current_token();
assert!(
matches!(result, Err(GarrisonError::Session(_))),
"未设置 task_local 时 current_token 应抛错"
);
}
#[serial]
#[tokio::test]
async fn current_token_returns_value_in_scope() {
with_current_token("scoped-token".to_string(), async {
let token = current_token().unwrap();
assert_eq!(token, "scoped-token");
})
.await;
}
#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn task_local_propagates_across_spawn() {
let ctx = with_current_token("parent-task-token".to_string(), async {
GarrisonContext::capture()
})
.await;
let handle = tokio::spawn(async move {
ctx.within(async {
match current_token() {
Ok(t) => t == "parent-task-token",
Err(_) => false,
}
})
.await
});
let result = handle.await.expect("子任务 panic");
assert!(
result,
"子任务内 current_token() 应返回父 task 设置的 token(通过 GarrisonContext 传播)"
);
}
#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn garrison_context_capture_without_token_propagates_none() {
let ctx = GarrisonContext::capture();
let handle = tokio::spawn(async move { ctx.within(async { current_token().is_ok() }).await });
let result = handle.await.expect("子任务 panic");
assert!(
!result,
"未设置 token 时 capture 的上下文在子任务内 current_token() 应失败"
);
}
#[serial]
#[tokio::test]
async fn check_permission_held_returns_ok() {
let logic = make_logic(3600, 86400, true, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = with_token(
&token,
with_default_tenant(async { logic.check_permission("user:read").await }),
)
.await;
assert!(result.is_ok(), "持有权限应返回 Ok");
}
#[serial]
#[tokio::test]
async fn check_permission_not_held_throws_not_permission() {
let logic = make_logic(3600, 86400, true, "uuid", false, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = with_token(
&token,
with_default_tenant(async { logic.check_permission("user:delete").await }),
)
.await;
assert!(
matches!(result, Err(GarrisonError::NotPermission(_))),
"未持有权限应抛 NotPermission"
);
}
#[serial]
#[tokio::test]
async fn check_permission_not_login_throws_when_throw_on_not_login() {
let logic = make_logic(3600, 86400, true, "uuid", true, true);
let result = logic.check_permission("user:read").await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"未登录且 throw_on_not_login=true 应抛 NotLogin"
);
}
#[serial]
#[tokio::test]
async fn check_permission_not_login_throws_not_permission_when_silent() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.check_permission("user:read").await;
assert!(
matches!(result, Err(GarrisonError::NotPermission(_))),
"未登录且 throw_on_not_login=false 应抛 NotPermission(降级)"
);
}
#[serial]
#[tokio::test]
async fn check_role_held_returns_ok() {
let logic = make_logic(3600, 86400, true, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = with_token(&token, with_default_tenant(logic.check_role("admin"))).await;
assert!(result.is_ok(), "持有角色应返回 Ok");
}
#[serial]
#[tokio::test]
async fn check_role_not_held_throws_not_role() {
let logic = make_logic(3600, 86400, true, "uuid", true, false);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = with_token(&token, with_default_tenant(logic.check_role("admin"))).await;
assert!(
matches!(result, Err(GarrisonError::NotRole(_))),
"未持有角色应抛 NotRole"
);
}
#[serial]
#[tokio::test]
async fn check_role_not_login_throws_when_throw_on_not_login() {
let logic = make_logic(3600, 86400, true, "uuid", true, true);
let result = logic.check_role("admin").await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"未登录且 throw_on_not_login=true 应抛 NotLogin"
);
}
#[serial]
#[tokio::test]
async fn check_role_not_login_throws_not_role_when_silent() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.check_role("admin").await;
assert!(
matches!(result, Err(GarrisonError::NotRole(_))),
"未登录且 throw_on_not_login=false 应抛 NotRole(降级)"
);
}
#[tokio::test]
#[serial]
async fn util_logout_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::logout().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 logout 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_logout_by_login_id_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::logout_by_login_id("1001").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 logout_by_login_id 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_kickout_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::kickout("1001").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 kickout 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_kickout_by_token_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::kickout_by_token("some-token").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 kickout_by_token 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_check_login_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::check_login().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 check_login 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_get_login_id_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::get_login_id().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 get_login_id 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_check_permission_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::check_permission("user:read").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 check_permission 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_check_role_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::check_role("admin").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 check_role 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_check_safe_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::check_safe().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 check_safe 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_check_disable_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::check_disable().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 check_disable 应返回 Session 错误"
);
}
#[serial]
#[tokio::test]
async fn util_has_permission_empty_string_returns_invalid_param() {
let result = GarrisonUtil::has_permission("").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref s)) if s.contains("permission")),
"空 permission 应返回 InvalidParam,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn util_has_role_empty_string_returns_invalid_param() {
let result = GarrisonUtil::has_role("").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref s)) if s.contains("role")),
"空 role 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
#[serial]
async fn util_has_permission_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::has_permission("user:read").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 has_permission 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_has_role_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::has_role("admin").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 has_role 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_has_permission_returns_true_when_granted() {
init_global_manager_with_perms(
false,
vec!["user:read".to_string()],
vec!["admin".to_string()],
)
.await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(
&token,
with_default_tenant(GarrisonUtil::has_permission("user:read")),
)
.await;
assert!(result.unwrap(), "持有权限应返回 true");
}
#[tokio::test]
#[serial]
async fn util_has_permission_returns_false_when_not_granted() {
init_global_manager_with_perms(false, vec![], vec![]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(
&token,
with_default_tenant(GarrisonUtil::has_permission("user:read")),
)
.await;
assert!(!result.unwrap(), "未持有权限应返回 false");
}
#[tokio::test]
#[serial]
async fn util_has_permission_returns_false_when_not_logged_in() {
init_global_manager(false).await;
let result = GarrisonUtil::has_permission("user:read").await;
assert!(!result.unwrap(), "未登录应返回 false");
}
#[tokio::test]
#[serial]
async fn util_has_role_returns_true_when_granted() {
init_global_manager_with_perms(
false,
vec!["user:read".to_string()],
vec!["admin".to_string()],
)
.await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(&token, with_default_tenant(GarrisonUtil::has_role("admin"))).await;
assert!(result.unwrap(), "持有角色应返回 true");
}
#[tokio::test]
#[serial]
async fn util_has_role_returns_false_when_not_granted() {
init_global_manager_with_perms(false, vec![], vec![]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(&token, with_default_tenant(GarrisonUtil::has_role("admin"))).await;
assert!(!result.unwrap(), "未持有角色应返回 false");
}
#[tokio::test]
#[serial]
async fn util_has_role_returns_false_when_not_logged_in() {
init_global_manager(false).await;
let result = GarrisonUtil::has_role("admin").await;
assert!(!result.unwrap(), "未登录应返回 false");
}
#[tokio::test]
#[serial]
async fn util_get_permission_list_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::get_permission_list().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 get_permission_list 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_get_role_list_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::get_role_list().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 get_role_list 应返回 Session 错误"
);
}
#[tokio::test]
#[serial]
async fn util_get_permission_list_returns_permissions_when_granted() {
init_global_manager_with_perms(
false,
vec!["user:read".to_string(), "user:write".to_string()],
vec!["admin".to_string()],
)
.await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(&token, GarrisonUtil::get_permission_list()).await;
let perms = result.unwrap();
assert_eq!(perms.len(), 2, "应返回 2 个权限");
assert!(perms.contains(&"user:read".to_string()), "应包含 user:read");
assert!(
perms.contains(&"user:write".to_string()),
"应包含 user:write"
);
}
#[tokio::test]
#[serial]
async fn util_get_permission_list_returns_empty_when_no_permissions() {
init_global_manager_with_perms(false, vec![], vec![]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(&token, GarrisonUtil::get_permission_list()).await;
assert!(result.unwrap().is_empty(), "无权限时应返回空 vec");
}
#[tokio::test]
#[serial]
async fn util_get_permission_list_returns_empty_when_not_logged_in() {
init_global_manager(false).await;
let result = GarrisonUtil::get_permission_list().await;
assert!(result.unwrap().is_empty(), "未登录应返回空 vec");
}
#[tokio::test]
#[serial]
async fn util_get_role_list_returns_roles_when_granted() {
init_global_manager_with_perms(
false,
vec!["user:read".to_string()],
vec!["admin".to_string(), "user".to_string()],
)
.await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(&token, GarrisonUtil::get_role_list()).await;
let roles = result.unwrap();
assert_eq!(roles.len(), 2, "应返回 2 个角色");
assert!(roles.contains(&"admin".to_string()), "应包含 admin");
assert!(roles.contains(&"user".to_string()), "应包含 user");
}
#[tokio::test]
#[serial]
async fn util_get_role_list_returns_empty_when_no_roles() {
init_global_manager_with_perms(false, vec![], vec![]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let result = with_token(&token, GarrisonUtil::get_role_list()).await;
assert!(result.unwrap().is_empty(), "无角色时应返回空 vec");
}
#[tokio::test]
#[serial]
async fn util_get_role_list_returns_empty_when_not_logged_in() {
init_global_manager(false).await;
let result = GarrisonUtil::get_role_list().await;
assert!(result.unwrap().is_empty(), "未登录应返回空 vec");
}
#[tokio::test]
#[serial]
async fn util_logout_by_login_id_succeeds() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
assert!(!token.is_empty());
GarrisonUtil::logout_by_login_id("1001").await.unwrap();
let valid = with_token(&token, async { GarrisonUtil::check_login().await })
.await
.unwrap();
assert!(!valid, "logout_by_login_id 后 check_login 应返回 false");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn util_kickout_succeeds() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
GarrisonUtil::kickout("1001").await.unwrap();
let valid = with_token(&token, async { GarrisonUtil::check_login().await })
.await
.unwrap();
assert!(!valid, "kickout 后 check_login 应返回 false");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn util_kickout_by_token_succeeds() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
GarrisonUtil::kickout_by_token(&token).await.unwrap();
let valid = with_token(&token, async { GarrisonUtil::check_login().await })
.await
.unwrap();
assert!(!valid, "kickout_by_token 后 check_login 应返回 false");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn util_get_login_id_returns_current_id() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let login_id = with_token(&token, async { GarrisonUtil::get_login_id().await })
.await
.unwrap();
assert_eq!(
login_id,
Some("1001".to_string()),
"get_login_id 应返回当前 login_id"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn util_check_safe_returns_ok_by_default() {
init_global_manager(false).await;
let _ = GarrisonUtil::login_simple("1001").await.unwrap();
let result = GarrisonUtil::check_safe().await;
#[cfg(feature = "security-extra")]
{
assert!(
matches!(result, Err(GarrisonError::NotSafe { .. })),
"启用 safe-auth 时未 open_safe,check_safe 应返回 Err(NotSafe),实际: {:?}",
result
);
}
#[cfg(not(feature = "security-extra"))]
{
assert!(
result.is_ok(),
"未启用 safe-auth 时 check_safe 应返回 Ok,实际: {:?}",
result
);
}
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn util_check_disable_returns_ok_by_default() {
init_global_manager(false).await;
let _ = GarrisonUtil::login_simple("1001").await.unwrap();
let result = GarrisonUtil::check_disable().await;
assert!(
result.is_ok(),
"默认 check_disable 应返回 Ok,实际: {:?}",
result
);
GarrisonManager::reset_for_test();
}
#[serial]
#[tokio::test]
async fn login_by_token_uuid_style_returns_invalid_token() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.login_by_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"uuid style login_by_token 应返回 InvalidToken,实际: {:?}",
result
);
}
#[tokio::test]
#[serial]
async fn util_login_by_token_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::login_by_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 login_by_token 应返回 Session 错误"
);
}
#[cfg(feature = "secure-simple-token")]
#[serial]
#[tokio::test]
async fn verify_token_simple_style_returns_login_id() {
let logic = make_logic(3600, 86400, false, "simple", true, true);
let style = crate::core::token::SimpleTokenStyle::new(STP_SIMPLE_TEST_SECRET.to_string());
let token = style.generate("1001", 3600).unwrap();
let login_id = logic.verify_token(&token).await.unwrap();
assert_eq!(login_id, "1001".to_string(), "verify_token 应返回 login_id");
}
#[serial]
#[tokio::test]
async fn verify_token_uuid_style_returns_invalid_token() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = logic.verify_token(&token).await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"uuid style verify_token 应返回 InvalidToken,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn verify_token_invalid_returns_error() {
let logic = make_logic(3600, 86400, false, "simple", true, true);
let result = logic.verify_token("nodash").await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"无效 token 应返回 InvalidToken,实际: {:?}",
result
);
}
#[cfg(feature = "secure-simple-token")]
#[serial]
#[tokio::test]
async fn verify_token_malformed_returns_invalid_token() {
let logic = make_logic(3600, 86400, false, "simple", true, true);
let style = crate::core::token::SimpleTokenStyle::new(STP_SIMPLE_TEST_SECRET.to_string());
let token = style.generate("abc", 3600).unwrap();
let result = logic.verify_token(&token).await;
assert!(
result.is_ok(),
"simple-format token with valid HMAC 应返回 Ok,实际: {:?}",
result
);
assert_eq!(result.unwrap(), "abc");
}
#[tokio::test]
#[serial]
async fn util_verify_token_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::verify_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 verify_token 应返回 Session 错误"
);
}
#[serial]
#[tokio::test]
async fn refresh_token_default_returns_not_implemented() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.refresh_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"default refresh_token 应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
#[serial]
async fn util_refresh_token_fails_when_not_initialized() {
GarrisonManager::reset_for_test();
let result = GarrisonUtil::refresh_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"未初始化时 refresh_token 应返回 Session 错误"
);
}
#[cfg(feature = "secure-simple-token")]
#[tokio::test]
#[serial]
async fn util_verify_token_returns_login_id() {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
config.token_style = "simple".to_string();
config.jwt_secret = test_jwt_secret(STP_SIMPLE_TEST_SECRET);
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao)
.config(Arc::new(config))
.interface(interface)
.build()
.await
.unwrap();
let style = crate::core::token::SimpleTokenStyle::new(STP_SIMPLE_TEST_SECRET.to_string());
let token = style.generate("1001", 3600).unwrap();
let login_id = GarrisonUtil::verify_token(&token).await.unwrap();
assert_eq!(login_id, "1001".to_string());
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn util_refresh_token_returns_not_implemented_without_jwt() {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao)
.config(Arc::new(config))
.interface(interface)
.build()
.await
.unwrap();
let result = GarrisonUtil::refresh_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"未启用 protocol-jwt 时 refresh_token 应返回 NotImplemented"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
async fn builder_methods_return_self_for_chaining() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let pm = Arc::new(GarrisonPluginManager::new());
#[cfg(feature = "listener")]
let lm = Arc::new(GarrisonListenerManager::new());
#[cfg(feature = "listener")]
let _logic = logic.with_plugin_manager(pm).with_listener_manager(lm);
#[cfg(not(feature = "listener"))]
let _logic = logic.with_plugin_manager(pm);
let logic2 = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic2.login("1001", &LoginParams::default()).await.unwrap();
assert!(!token.is_empty());
}
#[tokio::test]
async fn login_with_plugin_manager_triggers_on_login() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let pm = Arc::new(GarrisonPluginManager::new());
let logic = logic.with_plugin_manager(pm);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
assert!(!token.is_empty());
}
#[tokio::test]
async fn login_with_listener_manager_broadcasts_login_event() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
#[cfg(feature = "listener")]
{
let lm = Arc::new(GarrisonListenerManager::new());
let logic = logic.with_listener_manager(lm);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
assert!(!token.is_empty());
}
#[cfg(not(feature = "listener"))]
{
let _ = logic;
}
}
#[tokio::test]
async fn logout_with_managers_triggers_hooks() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let pm = Arc::new(GarrisonPluginManager::new());
let logic = logic.with_plugin_manager(pm);
#[cfg(feature = "listener")]
let logic = logic.with_listener_manager(Arc::new(GarrisonListenerManager::new()));
let token = logic.login("2002", &LoginParams::default()).await.unwrap();
with_current_token(token.clone(), async { logic.logout().await })
.await
.unwrap();
}
#[tokio::test]
async fn kickout_with_listener_manager_broadcasts_event() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
#[cfg(feature = "listener")]
{
let lm = Arc::new(GarrisonListenerManager::new());
let logic = logic.with_listener_manager(lm);
logic.kickout("3003").await.unwrap();
}
#[cfg(not(feature = "listener"))]
{
logic.kickout("3003").await.unwrap();
}
}
#[tokio::test]
async fn revoke_token_destroys_session() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic.login("4004", &LoginParams::default()).await.unwrap();
assert!(logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_some());
logic.revoke_token(&token).await.unwrap();
assert!(logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_none());
}
#[tokio::test]
async fn revoke_token_with_listener_manager_broadcasts_event() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
#[cfg(feature = "listener")]
{
let lm = Arc::new(GarrisonListenerManager::new());
let logic = logic.with_listener_manager(lm);
let token = logic.login("4005", &LoginParams::default()).await.unwrap();
logic.revoke_token(&token).await.unwrap();
assert!(logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_none());
}
#[cfg(not(feature = "listener"))]
{
let token = logic.login("4005", &LoginParams::default()).await.unwrap();
logic.revoke_token(&token).await.unwrap();
}
}
#[tokio::test]
async fn revoke_token_nonexistent_is_noop() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.revoke_token("nonexistent-token").await;
assert!(
result.is_ok(),
"revoke_token 对不存在的 token 应幂等返回 Ok"
);
}
#[tokio::test]
async fn without_managers_login_logout_kickout_still_work() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic.login("5005", &LoginParams::default()).await.unwrap();
assert!(!token.is_empty());
let is_valid = with_current_token(token.clone(), async { logic.check_login().await })
.await
.unwrap();
assert!(is_valid);
with_current_token(token.clone(), async { logic.logout().await })
.await
.unwrap();
logic.kickout("5005").await.unwrap();
}
#[tokio::test]
async fn login_by_token_with_auth_logic_delegates_to_auth() {
use crate::core::auth::{AuthLogic, AuthLogicDefault};
use crate::core::token::{Token, UuidTokenStyle};
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao, 3600, 86400, 0));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
let auth_logic: Arc<dyn AuthLogic> =
Arc::new(AuthLogicDefault::new(session.clone(), token_handler, 3600));
let valid_token = auth_logic.login("6006", None).await.unwrap();
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let logic = logic.with_auth_logic(auth_logic);
logic.login_by_token(&valid_token).await.unwrap();
let ts = logic.session.get_token_session(&valid_token).await.unwrap();
assert!(ts.is_some(), "login_by_token 后应建立会话");
assert_eq!(ts.unwrap().login_id, "6006".to_string());
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn refresh_token_non_jwt_style_returns_not_implemented() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.refresh_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("token_style=jwt")),
"非 jwt style 的 refresh_token 应返回 NotImplemented,实际: {:?}",
result
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn refresh_token_invalid_jwt_returns_error() {
let logic = make_logic(3600, 86400, false, "jwt", true, true);
let result = logic.refresh_token("invalid.jwt.token").await;
assert!(
result.is_err(),
"无效 JWT refresh_token 应返回 Err,实际: {:?}",
result
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn refresh_token_valid_jwt_returns_new_token() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.token_style = "jwt".to_string();
config.jwt_secret = "refresh-test-secret-aaaabbbbccccdddd".to_string().into();
config.timeout = 3600;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
);
let pm = Arc::new(GarrisonPluginManager::new());
let logic = logic.with_plugin_manager(pm);
#[cfg(feature = "listener")]
let logic = logic.with_listener_manager(Arc::new(GarrisonListenerManager::new()));
let handler = crate::protocol::jwt::JwtHandler::new("refresh-test-secret-aaaabbbbccccdddd");
let original_token = handler.sign("7007", 3600).unwrap();
let new_token = logic.refresh_token(&original_token).await.unwrap();
assert!(!new_token.is_empty(), "refresh_token 应返回非空 token");
let new_claims = handler.verify(&new_token).unwrap();
assert_eq!(new_claims.login_id, "7007".to_string());
}
struct MinimalLogic {
config: Arc<GarrisonConfig>,
}
impl GarrisonCore for MinimalLogic {
fn config(&self) -> Arc<GarrisonConfig> {
Arc::clone(&self.config)
}
}
#[async_trait]
impl SessionLogic for MinimalLogic {
async fn login(&self, _: &str, _params: &LoginParams) -> GarrisonResult<String> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn login_with_token(&self, _: &str, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn logout(&self) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn logout_by_login_id(&self, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn kickout(&self, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn kickout_by_token(&self, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn revoke_token(&self, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn check_login(&self) -> GarrisonResult<bool> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
}
#[async_trait]
impl PermissionLogic for MinimalLogic {
async fn check_permission(&self, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
async fn check_role(&self, _: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"mock implementation, not for production".to_string(),
))
}
}
#[async_trait]
impl TokenLogic for MinimalLogic {}
#[async_trait]
impl MfaLogic for MinimalLogic {}
#[async_trait]
impl PasswordLogic for MinimalLogic {}
#[tokio::test]
async fn trait_default_login_by_token_returns_not_implemented() {
let logic = MinimalLogic {
config: Arc::new(GarrisonConfig::default_config()),
};
let result = logic.login_by_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("stp-login-by-token-feature-required")),
"trait default login_by_token 应返回 NotImplemented,实际: {:?}",
result
);
let _ = logic.config();
}
#[tokio::test]
async fn trait_default_verify_token_returns_not_implemented() {
let logic = MinimalLogic {
config: Arc::new(GarrisonConfig::default_config()),
};
let result = logic.verify_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("override")),
"trait default verify_token 应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn trait_default_refresh_token_returns_not_implemented() {
let logic = MinimalLogic {
config: Arc::new(GarrisonConfig::default_config()),
};
let result = logic.refresh_token("any-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("protocol-jwt")),
"trait default refresh_token 应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn minimal_logic_returns_not_implemented() {
let logic = MinimalLogic {
config: Arc::new(GarrisonConfig::default_config()),
};
assert!(
matches!(
logic.login("1", &LoginParams::default()).await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::login 应返回 NotImplemented(mock 不应 panic)"
);
assert!(
matches!(
logic.login_with_token("1", "t").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::login_with_token 应返回 NotImplemented"
);
assert!(
matches!(logic.logout().await, Err(GarrisonError::NotImplemented(_))),
"MinimalLogic::logout 应返回 NotImplemented"
);
assert!(
matches!(
logic.logout_by_login_id("1").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::logout_by_login_id 应返回 NotImplemented"
);
assert!(
matches!(
logic.kickout("1").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::kickout 应返回 NotImplemented"
);
assert!(
matches!(
logic.kickout_by_token("t").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::kickout_by_token 应返回 NotImplemented"
);
assert!(
matches!(
logic.revoke_token("t").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::revoke_token 应返回 NotImplemented"
);
assert!(
matches!(
logic.check_login().await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::check_login 应返回 NotImplemented"
);
assert!(
matches!(
logic.get_login_id().await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::get_login_id 应返回 NotImplemented"
);
assert!(
matches!(
logic.check_permission("p").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::check_permission 应返回 NotImplemented"
);
assert!(
matches!(
logic.check_role("r").await,
Err(GarrisonError::NotImplemented(_))
),
"MinimalLogic::check_role 应返回 NotImplemented"
);
}
#[cfg(feature = "secure-simple-token")]
#[tokio::test]
async fn login_by_token_with_managers_triggers_hooks() {
let logic = make_logic(3600, 86400, false, "simple", true, true);
let pm = Arc::new(GarrisonPluginManager::new());
let logic = logic.with_plugin_manager(pm);
#[cfg(feature = "listener")]
let logic = logic.with_listener_manager(Arc::new(GarrisonListenerManager::new()));
let style = crate::core::token::SimpleTokenStyle::new(STP_SIMPLE_TEST_SECRET.to_string());
let token = style.generate("8008", 3600).unwrap();
logic.login_by_token(&token).await.unwrap();
let ts = logic.session.get_token_session(&token).await.unwrap();
assert!(ts.is_some(), "login_by_token 后应建立会话");
assert_eq!(ts.unwrap().login_id, "8008".to_string());
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::account::credential::{Argon2Hasher, PasswordHasher};
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::dao::repository::{UserRepository, UserRow};
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
fn make_user_row(login_id: &str, password_hash: &str) -> UserRow {
UserRow {
id: format!("u-{}", login_id),
username: login_id.to_string(),
password_hash: password_hash.to_string(),
status: "active".to_string(),
tenant_id: 0,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
last_login_at: None,
}
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[tokio::test]
#[serial]
async fn login_with_password_correct_returns_token() {
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let hash = hasher.hash("correct-password").unwrap();
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1001", &hash));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let logic = make_logic(3600, 86400, false, "uuid", true, true)
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("1001", "correct-password").await;
assert!(result.is_ok(), "正确密码应返回 Ok,实际: {:?}", result);
let token = result.unwrap();
assert!(!token.is_empty(), "token 应非空");
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[tokio::test]
#[serial]
async fn login_with_password_wrong_password_returns_invalid_param() {
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let hash = hasher.hash("correct-password").unwrap();
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1001", &hash));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let logic = make_logic(3600, 86400, false, "uuid", true, true)
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("1001", "wrong-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"错误密码应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
result
);
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[tokio::test]
#[serial]
async fn login_with_password_user_not_found_returns_invalid_param() {
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new());
let logic = make_logic(3600, 86400, false, "uuid", true, true)
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("9999", "any-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"用户不存在应返回 InvalidParam(\"stp-invalid-password\")(不泄露 NotLogin),实际: {:?}",
result
);
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[tokio::test]
#[serial]
async fn login_with_password_unsupported_hash_format_returns_invalid_param() {
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1001", "unsupported_hash_format"));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let logic = make_logic(3600, 86400, false, "uuid", true, true)
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("1001", "any-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"不支持的哈希格式应与密码错误统一返回 stp-invalid-password(T019),实际: {:?}",
result
);
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
async fn login_with_metrics_records_success() {
let logic = make_logic(3600, 86400, false, "uuid", false, false);
let registry = prometheus::Registry::new();
let metrics = Arc::new(crate::observability::GarrisonMetrics::register_to(®istry).unwrap());
let logic = logic.with_metrics(metrics.clone());
let _token = logic.login("1001", &LoginParams::default()).await.unwrap();
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.unwrap();
assert!(
output.contains("garrison_login_total{result=\"success\"} 1"),
"expected success counter=1, got: {}",
output
);
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
async fn check_permission_with_metrics_records_query() {
let logic = make_logic(3600, 86400, true, "uuid", false, false);
let registry = prometheus::Registry::new();
let metrics = Arc::new(crate::observability::GarrisonMetrics::register_to(®istry).unwrap());
let logic = logic.with_metrics(metrics.clone());
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let result = with_token(
&token,
with_default_tenant(async { logic.check_permission("user:read").await }),
)
.await;
assert!(result.is_err(), "未授权权限应返回 Err");
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.unwrap();
assert!(
output.contains("garrison_permission_query_total{result=\"deny\"} 1"),
"expected deny counter=1, got: {}",
output
);
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
async fn login_without_metrics_does_not_panic() {
let logic = make_logic(3600, 86400, false, "uuid", false, false);
let _token = logic.login("1001", &LoginParams::default()).await.unwrap();
}
#[tokio::test]
#[serial]
async fn get_permission_list_with_type_delegates_to_default() {
let interface = MockInterface;
let result = interface
.get_permission_list_with_type("1001", "default")
.await;
assert!(result.is_ok(), "新方法应成功,实际: {:?}", result);
assert!(result.unwrap().is_empty(), "默认委托旧方法应返回空 Vec");
}
#[tokio::test]
#[serial]
async fn get_role_list_with_type_delegates_to_default() {
let interface = MockInterface;
let result = interface.get_role_list_with_type("1001", "default").await;
assert!(result.is_ok(), "新方法应成功,实际: {:?}", result);
assert!(result.unwrap().is_empty(), "默认委托旧方法应返回空 Vec");
}
#[tokio::test]
#[serial]
async fn get_permission_list_with_type_admin_isolated_from_user() {
let mut perms = HashMap::new();
perms.insert("admin".to_string(), vec!["admin:*".to_string()]);
perms.insert("user".to_string(), vec!["user:*".to_string()]);
let interface = MockInterfaceWithLoginType {
perms,
roles: HashMap::new(),
};
let admin_perms = interface
.get_permission_list_with_type("1001", "admin")
.await
.unwrap();
assert_eq!(admin_perms, vec!["admin:*"]);
assert!(
!admin_perms.iter().any(|p| p == "user:*"),
"admin login_type 不应返回 user 的权限"
);
}
#[tokio::test]
#[serial]
async fn same_login_id_different_login_type_different_permissions() {
let mut perms = HashMap::new();
perms.insert("admin".to_string(), vec!["admin:*".to_string()]);
perms.insert("user".to_string(), vec!["user:*".to_string()]);
let interface = MockInterfaceWithLoginType {
perms,
roles: HashMap::new(),
};
let admin_perms = interface
.get_permission_list_with_type("1001", "admin")
.await
.unwrap();
let user_perms = interface
.get_permission_list_with_type("1001", "user")
.await
.unwrap();
assert_ne!(admin_perms, user_perms, "不同 login_type 应返回不同权限");
assert_eq!(admin_perms, vec!["admin:*"]);
assert_eq!(user_perms, vec!["user:*"]);
}
#[tokio::test]
#[serial]
async fn with_login_type_builder_sets_login_type() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
assert_eq!(
logic.login_type, "default",
"默认 login_type 应为 'default'"
);
let logic2 = make_logic(3600, 86400, false, "uuid", true, true).with_login_type("admin");
assert_eq!(
logic2.login_type, "admin",
"with_login_type 应设置 login_type 为 'admin'"
);
}
#[tokio::test]
#[serial]
async fn with_login_type_chains_with_other_builders() {
let pm = Arc::new(GarrisonPluginManager::new());
let logic = make_logic(3600, 86400, false, "uuid", true, true)
.with_plugin_manager(pm)
.with_login_type("merchant");
assert_eq!(logic.login_type, "merchant");
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
assert!(!token.is_empty());
}
#[test]
fn jwt_mode_default_is_mixin() {
assert_eq!(JwtMode::default(), JwtMode::Mixin);
}
#[serial]
#[test]
fn jwt_mode_is_copy() {
let mode = JwtMode::Stateless;
let copied = mode; assert_eq!(mode, copied);
assert_eq!(mode, JwtMode::Stateless);
}
#[tokio::test]
#[serial]
async fn with_jwt_mode_builder_sets_mode() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
assert_eq!(
logic.jwt_mode,
JwtMode::Mixin,
"未设置时默认 JwtMode::Mixin"
);
let logic2 =
make_logic(3600, 86400, false, "uuid", true, true).with_jwt_mode(JwtMode::Stateless);
assert_eq!(
logic2.jwt_mode,
JwtMode::Stateless,
"with_jwt_mode 应设置 jwt_mode 为 Stateless"
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
#[serial]
async fn check_login_stateless_only_jwt_verify() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.token_style = "jwt".to_string();
config.jwt_secret = "stateless-test-secret-aaaabbbbccccdddd".to_string().into();
config.throw_on_not_login = true;
config.enable_jwt_revocation = true;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = Arc::new(
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_jwt_mode(JwtMode::Stateless),
);
let handler = crate::protocol::jwt::JwtHandler::new("stateless-test-secret-aaaabbbbccccdddd");
let token = handler.sign("1001", 3600).unwrap();
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(
valid,
"Stateless 模式下有效 JWT 应返回 true(不查 session)"
);
})
.await;
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
#[serial]
async fn check_login_mixin_jwt_and_session() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.token_style = "jwt".to_string();
config.jwt_secret = "mixin-test-secret-aaaabbbbccccdddd".to_string().into();
config.throw_on_not_login = true;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = Arc::new(
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_jwt_mode(JwtMode::Mixin),
);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "Mixin 模式下有效 JWT + session 存在应返回 true");
})
.await;
}
#[tokio::test]
#[serial]
async fn check_login_simple_only_session() {
let logic =
Arc::new(make_logic(3600, 86400, true, "uuid", true, true).with_jwt_mode(JwtMode::Simple));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "Simple 模式下 session 存在应返回 true(不验证 JWT)");
})
.await;
}
#[serial]
#[tokio::test]
async fn trait_default_login_with_password_returns_not_implemented() {
let logic = MinimalLogic {
config: Arc::new(GarrisonConfig::default_config()),
};
let result = logic.login_with_password("1001", "any-password").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("stp-not-implemented")),
"trait default login_with_password 应返回 NotImplemented(需 account-credential + db-sqlite),实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn check_login_mixin_broadcasts_session_timeout_when_account_missing() {
let (dao, logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
dao.delete("account:session:1001").await.unwrap();
#[cfg(feature = "listener")]
let logic = logic.with_listener_manager(Arc::new(GarrisonListenerManager::new()));
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(!valid, "account session 不存在时 check_login 应返回 false");
})
.await;
}
#[serial]
#[tokio::test]
async fn check_login_simple_broadcasts_session_timeout_when_account_missing() {
let (dao, logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
let logic = logic.with_jwt_mode(JwtMode::Simple);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
dao.delete("account:session:1001").await.unwrap();
#[cfg(feature = "listener")]
let logic = logic.with_listener_manager(Arc::new(GarrisonListenerManager::new()));
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(!valid, "account session 不存在时 check_login 应返回 false");
})
.await;
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
#[serial]
async fn check_permission_not_logged_in_emits_deny_metric() {
use crate::observability::GarrisonMetrics;
let registry = prometheus::Registry::new();
let metrics = Arc::new(GarrisonMetrics::register_to(®istry).expect("注册失败"));
let logic = make_logic(3600, 86400, false, "uuid", true, true).with_metrics(metrics);
let result = logic.check_permission("user:read").await;
assert!(matches!(result, Err(GarrisonError::NotPermission(_))));
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.expect("encode 失败");
assert!(
output.contains("garrison_permission_query_total{result=\"deny\"}"),
"未登录 check_permission 应 emit deny metric,实际: {}",
output
);
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
#[serial]
async fn check_permission_with_checker_emits_metric() {
use crate::core::permission::PermissionCheckerDefault;
use crate::observability::GarrisonMetrics;
struct MockInterfaceWithPerms;
#[async_trait]
impl GarrisonInterface for MockInterfaceWithPerms {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec!["user:read".to_string()])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
}
let registry = prometheus::Registry::new();
let metrics = Arc::new(GarrisonMetrics::register_to(®istry).expect("注册失败"));
let interface: Arc<dyn GarrisonInterface> = Arc::new(MockInterfaceWithPerms);
let checker = Arc::new(PermissionCheckerDefault::new(interface));
let logic = make_logic(3600, 86400, false, "uuid", true, true)
.with_metrics(metrics)
.with_permission_checker(checker);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
with_default_tenant(async {
let result = logic.check_permission("user:read").await;
assert_eq!(
result.unwrap(),
(),
"持有权限时 check_permission 应返回 Ok(())"
);
})
.await
})
.await;
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.expect("encode 失败");
assert!(
output.contains("garrison_permission_query_total{result=\"allow\"}"),
"持有权限应 emit allow metric,实际: {}",
output
);
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
#[serial]
async fn check_role_not_logged_in_emits_deny_metric() {
use crate::observability::GarrisonMetrics;
let registry = prometheus::Registry::new();
let metrics = Arc::new(GarrisonMetrics::register_to(®istry).expect("注册失败"));
let logic = make_logic(3600, 86400, false, "uuid", true, true).with_metrics(metrics);
let result = logic.check_role("admin").await;
assert!(matches!(result, Err(GarrisonError::NotRole(_))));
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.expect("encode 失败");
assert!(
output.contains("garrison_role_query_total{result=\"deny\"}"),
"未登录 check_role 应 emit deny metric,实际: {}",
output
);
}
#[cfg(feature = "metrics-prometheus")]
#[tokio::test]
#[serial]
async fn check_role_logged_in_emits_metric() {
use crate::observability::GarrisonMetrics;
let registry = prometheus::Registry::new();
let metrics = Arc::new(GarrisonMetrics::register_to(®istry).expect("注册失败"));
let logic = make_logic(3600, 86400, false, "uuid", true, true).with_metrics(metrics);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token, async {
let result = with_default_tenant(logic.check_role("admin")).await;
assert!(result.is_ok(), "check_role 应返回 Ok,实际: {:?}", result);
})
.await;
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.expect("encode 失败");
assert!(
output.contains("garrison_role_query_total{result=\"allow\"}"),
"持有角色应 emit allow metric,实际: {}",
output
);
}
#[tokio::test]
#[serial]
async fn util_revoke_token_destroys_session() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
GarrisonUtil::revoke_token(&token).await.unwrap();
let valid = with_token(&token, async { GarrisonUtil::check_login().await })
.await
.unwrap();
assert!(!valid, "revoke_token 后 check_login 应返回 false");
}
#[tokio::test]
#[serial]
async fn util_login_by_token_delegates_to_logic_after_init() {
init_global_manager(false).await;
let result = GarrisonUtil::login_by_token("any-token").await;
assert!(
!matches!(result, Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")),
"初始化后 login_by_token 不应返回 '未初始化' Session 错误,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn check_access_token_not_logged_in_returns_not_login() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.check_access_token().await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"未登录时 check_access_token 应返回 NotLogin,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn check_client_token_not_logged_in_returns_not_login() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.check_client_token().await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"未登录时 check_client_token 应返回 NotLogin,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn check_temp_token_not_logged_in_returns_not_login() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.check_temp_token().await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"未登录时 check_temp_token 应返回 NotLogin,实际: {:?}",
result
);
}
#[tokio::test]
#[serial]
async fn util_check_access_token_delegates_to_logic() {
init_global_manager(false).await;
let result = GarrisonUtil::check_access_token().await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"无 token 时 check_access_token 应返回 NotLogin,实际: {:?}",
result
);
}
#[tokio::test]
#[serial]
async fn util_check_client_token_delegates_to_logic() {
init_global_manager(false).await;
let result = GarrisonUtil::check_client_token().await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"无 token 时 check_client_token 应返回 NotLogin,实际: {:?}",
result
);
}
#[tokio::test]
#[serial]
async fn util_check_temp_token_delegates_to_logic() {
init_global_manager(false).await;
let result = GarrisonUtil::check_temp_token().await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"无 token 时 check_temp_token 应返回 NotLogin,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_login_works_in_runtime() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(token, async {
let result = GarrisonUtil::check_login_sync();
assert!(
result.is_ok(),
"check_login_sync 应返回 Ok,实际: {:?}",
result
);
assert!(result.unwrap(), "已登录时 check_login_sync 应返回 Ok(true)");
})
.await;
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_login_returns_false_when_not_logged_in() {
init_global_manager(false).await;
let result = GarrisonUtil::check_login_sync();
assert!(
result.is_ok(),
"check_login_sync 应返回 Ok,实际: {:?}",
result
);
assert!(
!result.unwrap(),
"未登录时 check_login_sync 应返回 Ok(false)"
);
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_permission_held_returns_ok() {
init_global_manager_with_perms(
false,
vec!["user:read".to_string()],
vec!["admin".to_string()],
)
.await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(token, async {
with_default_tenant(async {
let result = GarrisonUtil::check_permission_sync("user:read");
assert!(
result.is_ok(),
"持有权限时 check_permission_sync 应返回 Ok,实际: {:?}",
result
);
})
.await
})
.await;
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_role_held_returns_ok() {
init_global_manager_with_perms(
false,
vec!["user:read".to_string()],
vec!["admin".to_string()],
)
.await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(
token,
with_default_tenant(async {
let result = GarrisonUtil::check_role_sync("admin");
assert!(
result.is_ok(),
"持有角色时 check_role_sync 应返回 Ok,实际: {:?}",
result
);
}),
)
.await;
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_access_token_returns_ok_when_logged_in() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(token, async {
let result = GarrisonUtil::check_access_token_sync();
assert!(
result.is_ok(),
"已登录时 check_access_token_sync 应返回 Ok,实际: {:?}",
result
);
})
.await;
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_client_token_returns_ok_when_logged_in() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(token, async {
let result = GarrisonUtil::check_client_token_sync();
assert!(
result.is_ok(),
"已登录时 check_client_token_sync 应返回 Ok,实际: {:?}",
result
);
})
.await;
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_temp_token_returns_ok_when_logged_in() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(token, async {
let result = GarrisonUtil::check_temp_token_sync();
assert!(
result.is_ok(),
"已登录时 check_temp_token_sync 应返回 Ok,实际: {:?}",
result
);
})
.await;
GarrisonManager::reset_for_test();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn sync_check_api_key_executes_without_panic() {
init_global_manager(false).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
with_current_token(token, async {
let _ = GarrisonUtil::check_api_key_sync("default");
})
.await;
GarrisonManager::reset_for_test();
}
#[serial]
#[tokio::test]
async fn hover_timeout_evicts_inactive_session() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.token_style = "uuid".to_string();
config.session_hover_timeout = 1;
config.throw_on_not_login = false;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let mock_clock = Arc::new(MockClock::new(chrono::Utc::now()));
let logic = Arc::new(
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_clock(mock_clock.clone()),
);
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let first_check = with_current_token(token.clone(), async { logic.check_login().await })
.await
.unwrap();
assert!(first_check, "首次 check_login 应返回 true");
mock_clock.advance(chrono::Duration::seconds(2));
let second_check = with_current_token(token.clone(), async { logic.check_login().await })
.await
.unwrap();
assert!(!second_check, "悬停超时后 check_login 应返回 false");
}
#[serial]
#[tokio::test]
async fn hover_timeout_active_session_not_evicted() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.token_style = "uuid".to_string();
config.session_hover_timeout = 10;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = Arc::new(GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(dao)),
));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token.clone(), async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "活跃会话不应被踢出");
})
.await;
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "连续 check_login 应始终返回 true");
})
.await;
}
#[serial]
#[tokio::test]
async fn hover_timeout_disabled_by_default() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.token_style = "uuid".to_string();
assert_eq!(config.session_hover_timeout, -1);
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = Arc::new(GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(dao)),
));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
with_current_token(token.clone(), async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "默认配置(hover=-1)应始终返回 true");
})
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
with_current_token(token, async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "hover=-1 时不应因时间推移踢出");
})
.await;
}
#[cfg(feature = "protocol-apikey")]
mod check_api_key_tests {
use super::*;
use crate::protocol::apikey::ApiKeyHandler;
#[tokio::test]
#[serial]
async fn check_api_key_valid_key_correct_namespace_succeeds() {
let dao = init_global_manager_with_dao(false).await;
let handler = ApiKeyHandler::new(dao.clone() as Arc<dyn GarrisonDao>);
let key = handler
.generate_with_namespace("user1", "ns1", vec![], 3600)
.await
.unwrap();
let result = with_token(&key, GarrisonUtil::check_api_key("ns1")).await;
assert!(result.is_ok(), "有效 key + 正确 namespace 应通过校验");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn check_api_key_nonexistent_key_fails() {
init_global_manager_with_dao(false).await;
let result = with_token(
"nonexistent-key-12345",
GarrisonUtil::check_api_key("default"),
)
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"不存在的 key 应返回 InvalidToken,实际: {:?}",
result
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn check_api_key_without_token_context_fails() {
init_global_manager_with_dao(false).await;
let result = GarrisonUtil::check_api_key("default").await;
assert!(
result.is_err(),
"未设置 token 上下文应返回错误,实际: {:?}",
result
);
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"未设置 token 上下文应返回 NotLogin(映射 401),实际: {:?}",
result
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn check_api_key_namespace_isolation() {
let dao = init_global_manager_with_dao(false).await;
let handler = ApiKeyHandler::new(dao.clone() as Arc<dyn GarrisonDao>);
let key_ns1 = handler
.generate_with_namespace("user1", "ns1", vec![], 3600)
.await
.unwrap();
let result_ns1 = with_token(&key_ns1, GarrisonUtil::check_api_key("ns1")).await;
assert!(result_ns1.is_ok(), "ns1 key + ns1 namespace 应通过");
let result_ns2 = with_token(&key_ns1, GarrisonUtil::check_api_key("ns2")).await;
assert!(
result_ns2.is_err(),
"ns1 key + ns2 namespace 应失败(namespace 隔离)"
);
assert!(
matches!(result_ns2, Err(GarrisonError::InvalidToken(_))),
"namespace 不匹配应返回 InvalidToken,实际: {:?}",
result_ns2
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn check_api_key_default_namespace() {
let dao = init_global_manager_with_dao(false).await;
let handler = ApiKeyHandler::new(dao.clone() as Arc<dyn GarrisonDao>);
let key = handler.generate("user1", vec![], 3600).await.unwrap();
let result = with_token(&key, GarrisonUtil::check_api_key("default")).await;
assert!(result.is_ok(), "默认命名空间生成的 key 应在 default 通过");
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn check_api_key_manager_not_initialized_fails() {
GarrisonManager::reset_for_test();
let result = with_token("some-key", GarrisonUtil::check_api_key("default")).await;
assert!(
result.is_err(),
"Manager 未初始化应返回错误,实际: {:?}",
result
);
GarrisonManager::reset_for_test();
}
}
use super::context::{current_renewed_token, with_renewed_token_scope};
use crate::core::auth::AuthLogicDefault;
use crate::core::token::UuidTokenStyle;
fn make_logic_with_auth(
timeout: u64,
active_timeout: u64,
token_style: &str,
auto_renewal_threshold: i64,
) -> (Arc<MockDao>, GarrisonLogicDefault) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
timeout,
active_timeout,
0,
));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
let auth_logic: Arc<dyn AuthLogic> = Arc::new(AuthLogicDefault::new(
session.clone(),
token_handler,
timeout as i64,
));
let mut config = GarrisonConfig::default_config();
config.timeout = timeout as i64;
config.token_style = token_style.to_string();
config.auto_renewal_threshold = auto_renewal_threshold;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_auth_logic(auth_logic);
(dao, logic)
}
#[tokio::test]
async fn check_and_renew_returns_none_when_threshold_disabled() {
let (_dao, logic) = make_logic_with_auth(3600, 86400, "uuid", -1);
let token = logic
.login("user-001", &LoginParams::default())
.await
.unwrap();
let result = logic.check_and_renew(&token).await.unwrap();
assert!(result.is_none(), "threshold=-1 时应返回 None");
}
#[tokio::test]
async fn check_and_renew_returns_none_when_ttl_sufficient() {
let (_dao, logic) = make_logic_with_auth(3600, 86400, "uuid", 20);
let token = logic
.login("user-002", &LoginParams::default())
.await
.unwrap();
let result = logic.check_and_renew(&token).await.unwrap();
assert!(result.is_none(), "TTL 充足时应返回 None");
}
#[tokio::test]
async fn check_and_renew_renews_non_jwt_when_threshold_reached() {
let (dao, logic) = make_logic_with_auth(10, 86400, "uuid", 90);
let token = logic
.login("user-003", &LoginParams::default())
.await
.unwrap();
let key = token_key(&token);
dao.expire(&key, 1).await.unwrap();
let result = logic.check_and_renew(&token).await.unwrap();
assert!(result.is_some(), "remaining_pct < threshold 时应触发续签");
let new_token = result.unwrap();
assert_ne!(new_token, token, "续签后应生成新 token");
let old_valid = logic.session.is_valid(&token).await.unwrap();
assert!(!old_valid, "旧 token 续签后应失效");
let new_valid = logic.session.is_valid(&new_token).await.unwrap();
assert!(new_valid, "新 token 应有效");
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn check_and_renew_renews_jwt_when_threshold_reached() {
let dao: Arc<MockDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(
dao.clone() as Arc<dyn GarrisonDao>,
10,
86400,
0,
));
let mut config = GarrisonConfig::default_config();
config.timeout = 10;
config.token_style = "jwt".to_string();
config.jwt_secret = "test-secret-aaaabbbbccccdddd-0123456789".to_string().into();
config.auto_renewal_threshold = 90;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
);
let token = logic
.login("user-004", &LoginParams::default())
.await
.unwrap();
let key = token_key(&token);
dao.expire(&key, 1).await.unwrap();
let result = logic.check_and_renew(&token).await.unwrap();
assert!(
result.is_some(),
"JWT 模式 remaining_pct < threshold 时应触发续签"
);
let new_token = result.unwrap();
assert_ne!(new_token, token, "续签后应生成新 token");
}
#[tokio::test]
async fn check_login_renews_token_when_threshold_reached() {
let (dao, logic) = make_logic_with_auth(10, 86400, "uuid", 90);
let token = logic
.login("user-005", &LoginParams::default())
.await
.unwrap();
let key = token_key(&token);
dao.expire(&key, 1).await.unwrap();
let renewed = with_current_token(token.clone(), async {
with_renewed_token_scope(async {
let valid = logic.check_login().await.unwrap();
assert!(valid, "check_login 应返回 true(token 续签前有效)");
current_renewed_token()
})
.await
})
.await;
assert!(renewed.is_some(), "续签后应设置 CURRENT_RENEWED_TOKEN");
assert_ne!(renewed.unwrap(), token, "续签后的 token 应不同于原 token");
}
#[test]
fn login_params_default_is_all_none() {
let params = LoginParams::default();
assert!(params.device.is_none(), "默认 device 应为 None");
assert!(params.ip.is_none(), "默认 ip 应为 None");
assert!(params.user_agent.is_none(), "默认 user_agent 应为 None");
assert!(!params.remember_me, "默认 remember_me 应为 false");
}
#[tokio::test]
async fn login_with_default_params_creates_session() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let token = logic
.login("user-params-001", &LoginParams::default())
.await
.unwrap();
assert!(!token.is_empty(), "login 应返回非空 token");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.unwrap();
assert_eq!(ts.login_id, "user-params-001");
}
#[tokio::test]
async fn login_with_is_share_reuses_existing_token() {
let mut logic = make_logic(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_share = true;
let t1 = logic
.login("share-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("share-user-001", &LoginParams::default())
.await
.unwrap();
assert_eq!(t1, t2, "is_share=true 应复用现有 token");
}
#[tokio::test]
async fn login_with_is_share_creates_new_when_no_existing() {
let mut logic = make_logic(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_share = true;
let token = logic
.login("share-user-002", &LoginParams::default())
.await
.unwrap();
assert!(!token.is_empty());
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.unwrap();
assert_eq!(ts.login_id, "share-user-002");
}
#[tokio::test]
async fn login_with_is_concurrent_false_kickouts_existing() {
let mut logic = make_logic(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_concurrent = false;
let t1 = logic
.login("concurrent-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("concurrent-user-001", &LoginParams::default())
.await
.unwrap();
assert_ne!(t1, t2, "is_concurrent=false 应创建新 token");
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
assert!(ts1.is_none(), "is_concurrent=false 登录后旧 token 应被踢出");
}
#[tokio::test]
async fn login_new_device_mode_rejects_new_login() {
let mut logic = make_logic(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_concurrent = false;
Arc::make_mut(&mut logic.config).replaced_login_exit_mode = ReplacedLoginExitMode::NewDevice;
let token1 = logic
.login("new-device-user-001", &LoginParams::default())
.await
.unwrap();
assert!(!token1.is_empty(), "首次登录应成功");
let result = logic
.login("new-device-user-001", &LoginParams::default())
.await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(ref msg)) if msg.contains("stp-new-device-login-rejected-not-allowed")),
"NewDevice 模式下已有旧会话时应返回 NotLogin 错误,实际: {:?}",
result
);
let ts1 = logic.session.get_token_session(&token1).await.unwrap();
assert!(ts1.is_some(), "NewDevice 模式拒绝新登录后,旧会话应保留");
}
#[tokio::test]
async fn login_new_device_mode_allows_when_old_session_expired() {
let (dao, mut logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_concurrent = false;
Arc::make_mut(&mut logic.config).replaced_login_exit_mode = ReplacedLoginExitMode::NewDevice;
let token1 = logic
.login("expired-user-001", &LoginParams::default())
.await
.unwrap();
dao.delete(&token_key(&token1)).await.unwrap();
assert_eq!(
logic.session.get_token_by_login_id("expired-user-001"),
Some(token1.clone()),
"login_token_map 条目应仍存在"
);
let ts1 = logic.session.get_token_session(&token1).await.unwrap();
assert!(ts1.is_none(), "Token-Session 应已从 DAO 删除");
let token2 = logic
.login("expired-user-001", &LoginParams::default())
.await
.unwrap();
assert!(
!token2.is_empty(),
"旧会话过期后 NewDevice 模式应允许新登录"
);
assert_ne!(token1, token2, "新登录应生成新 token");
}
#[tokio::test]
async fn login_old_device_mode_kickout_old_session() {
let mut logic = make_logic(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_concurrent = false;
Arc::make_mut(&mut logic.config).replaced_login_exit_mode = ReplacedLoginExitMode::OldDevice;
let token1 = logic
.login("old-device-user-001", &LoginParams::default())
.await
.unwrap();
assert!(!token1.is_empty(), "首次登录应成功");
let token2 = logic
.login("old-device-user-001", &LoginParams::default())
.await
.unwrap();
assert_ne!(token1, token2, "第二次登录应生成新 token");
let ts1 = logic.session.get_token_session(&token1).await.unwrap();
assert!(ts1.is_none(), "OldDevice 模式下旧会话应被踢出");
let ts2 = logic.session.get_token_session(&token2).await.unwrap();
assert!(ts2.is_some(), "OldDevice 模式下新会话应有效");
}
#[tokio::test]
async fn login_with_is_concurrent_true_preserves_existing() {
let mut logic = make_logic(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).is_concurrent = true;
let t1 = logic
.login("concurrent-user-002", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("concurrent-user-002", &LoginParams::default())
.await
.unwrap();
assert_ne!(
t1, t2,
"is_concurrent=true + is_share=false 应创建不同 token"
);
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
assert!(ts1.is_some(), "is_concurrent=true 应保留旧 token");
}
#[tokio::test]
async fn enforce_max_login_count_evicts_oldest() {
let (dao, logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
let t1 = logic
.login("max-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("max-user-001", &LoginParams::default())
.await
.unwrap();
let t3 = logic
.login("max-user-001", &LoginParams::default())
.await
.unwrap();
let base = chrono::Utc::now().timestamp();
set_account_token_stamps(&dao, "max-user-001", &[base - 10, base - 5, base]).await;
logic
.enforce_max_login_count("max-user-001", 2)
.await
.unwrap();
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
assert!(ts1.is_none(), "最旧的 token 应被踢出");
let ts2 = logic.session.get_token_session(&t2).await.unwrap();
let ts3 = logic.session.get_token_session(&t3).await.unwrap();
assert!(ts2.is_some(), "较新的 token 应保留");
assert!(ts3.is_some(), "最新的 token 应保留");
}
#[tokio::test]
async fn enforce_max_login_count_no_op_when_under_limit() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let t1 = logic
.login("max-user-002", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("max-user-002", &LoginParams::default())
.await
.unwrap();
logic
.enforce_max_login_count("max-user-002", 5)
.await
.unwrap();
assert!(logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_some());
assert!(logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_some());
}
#[tokio::test]
async fn login_with_max_login_count_evicts_oldest_session() {
let (dao, mut logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).max_login_count = 2;
let t1 = logic
.login("max-login-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("max-login-user-001", &LoginParams::default())
.await
.unwrap();
let base = chrono::Utc::now().timestamp();
set_account_token_stamps(&dao, "max-login-user-001", &[base - 10, base - 5]).await;
let t3 = logic
.login("max-login-user-001", &LoginParams::default())
.await
.unwrap();
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
let ts2 = logic.session.get_token_session(&t2).await.unwrap();
let ts3 = logic.session.get_token_session(&t3).await.unwrap();
assert!(ts1.is_none(), "max_login_count=2 时最旧 token 应被踢出");
assert!(ts2.is_some(), "第二个 token 应保留");
assert!(ts3.is_some(), "最新 token 应保留");
}
#[cfg(feature = "listener")]
struct RecordingListener {
events: Arc<Mutex<Vec<crate::listener::GarrisonEvent>>>,
}
#[cfg(feature = "listener")]
#[async_trait]
impl crate::listener::GarrisonListener for RecordingListener {
async fn on_event(
&self,
event: &crate::listener::GarrisonEvent,
) -> crate::error::GarrisonResult<()> {
self.events.lock().push(event.clone());
Ok(())
}
}
#[tokio::test]
async fn enforce_max_login_count_overflow_logout_mode_logout() {
let (dao, mut logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).max_login_count = 2;
Arc::make_mut(&mut logic.config).overflow_logout_mode = OverflowLogoutMode::Logout;
#[cfg(feature = "listener")]
let captured_events: Arc<Mutex<Vec<crate::listener::GarrisonEvent>>> =
Arc::new(Mutex::new(Vec::new()));
#[cfg(feature = "listener")]
{
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(Arc::new(RecordingListener {
events: captured_events.clone(),
}));
logic = logic.with_listener_manager(lm);
}
let t1 = logic
.login("overflow-logout-user-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("overflow-logout-user-001", &LoginParams::default())
.await
.unwrap();
let base = chrono::Utc::now().timestamp();
set_account_token_stamps(&dao, "overflow-logout-user-001", &[base - 10, base - 5]).await;
let _t3 = logic
.login("overflow-logout-user-001", &LoginParams::default())
.await
.unwrap();
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
assert!(ts1.is_none(), "Logout 模式:最旧 token 应被踢出");
#[cfg(feature = "listener")]
{
let events = captured_events.lock();
let has_logout = events.iter().any(|e| match e {
crate::listener::GarrisonEvent::Logout { token, .. } => {
*token == crate::listener::mask_token_for_event(&t1)
},
_ => false,
});
assert!(
has_logout,
"Logout 模式应广播 Logout 事件(含被踢出的 token),实际事件: {:?}",
events
.iter()
.map(|e| format!("{:?}", e))
.collect::<Vec<_>>()
);
}
}
#[tokio::test]
async fn enforce_max_login_count_overflow_logout_mode_kickout() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let (dao, mut logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).max_login_count = 2;
Arc::make_mut(&mut logic.config).overflow_logout_mode = OverflowLogoutMode::Kickout;
#[cfg(feature = "listener")]
let captured_events: Arc<Mutex<Vec<crate::listener::GarrisonEvent>>> =
Arc::new(Mutex::new(Vec::new()));
#[cfg(feature = "listener")]
{
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(Arc::new(RecordingListener {
events: captured_events.clone(),
}));
logic = logic.with_listener_manager(lm);
}
let t1 = logic
.login("overflow-kickout-user-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("overflow-kickout-user-001", &LoginParams::default())
.await
.unwrap();
let base = chrono::Utc::now().timestamp();
set_account_token_stamps(&dao, "overflow-kickout-user-001", &[base - 10, base - 5]).await;
let _t3 = logic
.login("overflow-kickout-user-001", &LoginParams::default())
.await
.unwrap();
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
assert!(ts1.is_none(), "Kickout 模式:最旧 token 应被踢出");
#[cfg(feature = "listener")]
{
let events = captured_events.lock();
let has_kickout = events.iter().any(|e| match e {
crate::listener::GarrisonEvent::Kickout { token, reason, .. } => {
*token == crate::listener::mask_token_for_event(&t1)
&& reason == "超过最大登录数限制"
},
_ => false,
});
assert!(
has_kickout,
"Kickout 模式应广播 Kickout 事件(reason='超过最大登录数限制'),实际事件: {:?}",
events
.iter()
.map(|e| format!("{:?}", e))
.collect::<Vec<_>>()
);
}
}
#[tokio::test]
async fn enforce_max_login_count_overflow_logout_mode_replaced() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let (dao, mut logic) = make_logic_with_dao(3600, 86400, false, "uuid", true, true);
Arc::make_mut(&mut logic.config).max_login_count = 2;
Arc::make_mut(&mut logic.config).overflow_logout_mode = OverflowLogoutMode::Replaced;
#[cfg(feature = "listener")]
let captured_events: Arc<Mutex<Vec<crate::listener::GarrisonEvent>>> =
Arc::new(Mutex::new(Vec::new()));
#[cfg(feature = "listener")]
{
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(Arc::new(RecordingListener {
events: captured_events.clone(),
}));
logic = logic.with_listener_manager(lm);
}
let t1 = logic
.login("overflow-replaced-user-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("overflow-replaced-user-001", &LoginParams::default())
.await
.unwrap();
let base = chrono::Utc::now().timestamp();
set_account_token_stamps(&dao, "overflow-replaced-user-001", &[base - 10, base - 5]).await;
let _t3 = logic
.login("overflow-replaced-user-001", &LoginParams::default())
.await
.unwrap();
let ts1 = logic.session.get_token_session(&t1).await.unwrap();
assert!(ts1.is_none(), "Replaced 模式:最旧 token 应被踢出");
#[cfg(feature = "listener")]
{
let events = captured_events.lock();
let has_replaced = events.iter().any(|e| match e {
crate::listener::GarrisonEvent::Replaced {
login_id,
token,
reason,
..
} => {
login_id == "overflow-replaced-user-001"
&& *token == crate::listener::mask_token_for_event(&t1)
&& reason == "超过最大登录数限制,被新会话顶替"
},
_ => false,
});
assert!(
has_replaced,
"Replaced 模式应广播 Replaced 事件(含 login_id/token/reason),实际事件: {:?}",
events
.iter()
.map(|e| format!("{:?}", e))
.collect::<Vec<_>>()
);
}
}
#[tokio::test]
async fn session_logic_refresh_default_returns_not_implemented() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.refresh_access_token("some-refresh-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"默认 refresh_access_token 应返回 NotImplemented,实际: {:?}",
result
);
}
#[cfg(all(feature = "protocol-jwt", feature = "db-sqlite"))]
#[tokio::test]
async fn refresh_access_token_returns_not_implemented_when_not_injected() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.refresh_access_token("some-refresh-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"未注入 RefreshTokenRotation 时应返回 NotImplemented,实际: {:?}",
result
);
}
#[cfg(not(all(feature = "protocol-jwt", feature = "db-sqlite")))]
#[tokio::test]
async fn refresh_access_token_returns_not_implemented_without_db_sqlite() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let result = logic.refresh_access_token("some-refresh-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"未启用 db-sqlite feature 时应返回 NotImplemented,实际: {:?}",
result
);
}
#[cfg(any(
feature = "protocol-jwt",
feature = "account-credential",
feature = "protocol-oauth2",
feature = "protocol-sso",
feature = "protocol-sign",
feature = "secure-sign",
feature = "protocol-httpdigest"
))]
#[tokio::test]
async fn login_auto_generates_device_fingerprint() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let params = LoginParams {
device: None,
ip: Some("192.168.1.100".to_string()),
user_agent: Some("Mozilla/5.0 Chrome".to_string()),
remember_me: false,
require_mfa: false,
};
let token = logic
.login("fingerprint-user-001", ¶ms)
.await
.expect("login 应成功");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("Token-Session 应存在");
assert!(ts.device.is_some(), "device 应自动生成");
assert_eq!(
ts.device.as_ref().unwrap().len(),
32,
"指纹应为 32 字符(16 字节 hex)"
);
assert_eq!(ts.ip.as_deref(), Some("192.168.1.100"));
assert_eq!(ts.user_agent.as_deref(), Some("Mozilla/5.0 Chrome"));
}
#[tokio::test]
async fn check_and_renew_returns_none_for_old_token_after_renewal() {
let (dao, logic) = make_logic_with_auth(10, 86400, "uuid", 90);
let token = logic
.login("high001-user-001", &LoginParams::default())
.await
.unwrap();
let key = token_key(&token);
dao.expire(&key, 1).await.unwrap();
let result1 = logic.check_and_renew(&token).await.unwrap();
assert!(result1.is_some(), "首次续签应返回新 token");
let new_token = result1.unwrap();
assert_ne!(new_token, token, "新 token 应不同于旧 token");
let result2 = logic.check_and_renew(&token).await;
assert!(
result2.is_ok(),
"对已续签的旧 token 调用 check_and_renew 不应返回 Err"
);
assert!(
result2.unwrap().is_none(),
"旧 token 已被续签删除,应返回 None"
);
assert!(
logic.session.is_valid(&new_token).await.unwrap(),
"新 token 应有效"
);
}
#[tokio::test]
async fn login_rolls_back_session_when_enforce_fails() {
use std::sync::atomic::{AtomicU32, Ordering};
struct FailInjectionDao {
inner: Arc<MockDao>,
call_count: AtomicU32,
}
#[async_trait]
impl GarrisonDao for FailInjectionDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
if key.starts_with("account:session:") {
let current = self.inner.get(key).await?;
let over_limit = current
.as_deref()
.map(|v| v.matches("\"token\"").count() >= 2)
.unwrap_or(false);
if over_limit {
let n = self.call_count.fetch_add(1, Ordering::SeqCst) + 1;
if n == 1 {
return Err(GarrisonError::Dao(
"injected failure for HIGH-002 test".to_string(),
));
}
}
return Ok(current);
}
self.inner.get(key).await
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
self.inner.set(key, value, ttl_seconds).await
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
self.inner.update(key, value).await
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
self.inner.expire(key, seconds).await
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.inner.delete(key).await
}
async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
self.inner.get_timeout(key).await
}
crate::atomic_test_fallback!();
}
let mock_dao = Arc::new(MockDao::new());
{
let d = FailInjectionDao {
inner: mock_dao.clone(),
call_count: AtomicU32::new(0),
};
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 fail_dao = Arc::new(FailInjectionDao {
inner: mock_dao.clone(),
call_count: AtomicU32::new(0),
});
let session = Arc::new(GarrisonSession::new(
fail_dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let mut config = GarrisonConfig::default_config();
config.token_style = "uuid".to_string();
config.is_concurrent = true;
config.max_login_count = 1; let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
fail_dao.clone(),
)),
);
let t1 = logic
.login("high002-user-001", &LoginParams::default())
.await
.expect("首次登录应成功");
assert!(
logic.session.is_valid(&t1).await.unwrap(),
"首次登录的 token 应有效"
);
let login_result = logic
.login("high002-user-001", &LoginParams::default())
.await;
assert!(
login_result.is_err(),
"enforce 失败时 login 应返回 Err,实际: {:?}",
login_result
);
let tokens = logic.session.get_tokens_by_login_id("high002-user-001");
assert_eq!(
tokens.len(),
1,
"回滚后应只剩 1 个 token(首次登录的),实际: {} 个: {:?}",
tokens.len(),
tokens
);
assert!(
logic.session.is_valid(&t1).await.unwrap(),
"回滚不应影响首次登录的 token"
);
}
#[cfg(feature = "session-extra")]
#[tokio::test]
async fn per_token_active_timeout_takes_effect() {
let logic = make_logic(3600, 3600, false, "uuid", true, true);
let token = logic
.login("1001", &LoginParams::default())
.await
.expect("login 应成功");
logic
.session
.set_active_timeout(&token, 1)
.await
.expect("set_active_timeout 应成功");
tokio::time::sleep(Duration::from_secs(2)).await;
let valid = with_token(&token, async { logic.check_login().await.unwrap() }).await;
assert!(
!valid,
"per-token active_timeout=1 秒后 token 应已过期(全局 active_timeout=3600 不影响)"
);
}
#[cfg(feature = "session-extra")]
#[tokio::test]
async fn per_token_active_timeout_none_falls_back_to_global() {
use crate::session::TokenSession;
use chrono::Utc;
let (dao, logic) = make_logic_with_dao(3600, 2, false, "uuid", true, true);
let token = logic
.login("1001", &LoginParams::default())
.await
.expect("login 应成功");
let token_dao_key = token_key(&token);
let json = dao.get(&token_dao_key).await.unwrap().unwrap();
let mut ts: TokenSession = serde_json::from_str(&json).unwrap();
ts.last_active_at = Utc::now().timestamp() - 5;
let new_json = serde_json::to_string(&ts).unwrap();
dao.update(&token_dao_key, &new_json).await.unwrap();
let valid = with_token(&token, async { logic.check_login().await.unwrap() }).await;
assert!(
!valid,
"per-token=None 时应回退到全局 active_timeout=2,token(last_active_at 5 秒前)应已过期"
);
}
#[tokio::test]
async fn revoke_all_sessions_terminates_all_tokens_for_login_id() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let t1 = logic.login("1001", &LoginParams::default()).await.unwrap();
let t2 = logic.login("1001", &LoginParams::default()).await.unwrap();
let count = logic.revoke_all_sessions("1001").await.unwrap();
assert_eq!(count, 2, "应吊销 2 个 token,实际: {}", count);
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none(),
"t1 应已失效"
);
assert!(
logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_none(),
"t2 应已失效"
);
assert!(
logic
.session
.get_account_session("1001")
.await
.unwrap()
.is_none(),
"Account-Session 应已清除"
);
}
#[tokio::test]
async fn revoke_all_sessions_returns_zero_for_unknown_user() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let count = logic.revoke_all_sessions("unknown").await.unwrap();
assert_eq!(count, 0, "未知用户应返回 0,实际: {}", count);
}
#[tokio::test]
async fn get_active_sessions_returns_valid_tokens() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let t1 = logic.login("1001", &LoginParams::default()).await.unwrap();
let t2 = logic.login("1001", &LoginParams::default()).await.unwrap();
let active = logic.get_active_sessions("1001").await.unwrap();
assert_eq!(
active.len(),
2,
"应有 2 个活跃 token,实际: {}",
active.len()
);
assert!(active.contains(&t1), "应包含 t1");
assert!(active.contains(&t2), "应包含 t2");
logic.session.logout(&t1).await.unwrap();
let active_after = logic.get_active_sessions("1001").await.unwrap();
assert_eq!(
active_after.len(),
1,
"登出 t1 后应有 1 个活跃 token,实际: {}",
active_after.len()
);
assert!(
active_after.contains(&t2),
"应仅包含 t2,实际: {:?}",
active_after
);
}
#[tokio::test]
async fn get_active_sessions_returns_empty_for_unknown_user() {
let logic = make_logic(3600, 86400, false, "uuid", true, true);
let active = logic.get_active_sessions("unknown").await.unwrap();
assert!(
active.is_empty(),
"未知用户应返回空 Vec,实际: {:?}",
active
);
}
#[test]
fn system_clock_default_returns_valid_time() {
let clock = SystemClock;
let before = chrono::Utc::now();
let now = clock.now();
let after = chrono::Utc::now();
assert!(
now >= before && now <= after,
"SystemClock::now() 应在调用前后时间范围内"
);
}
#[test]
fn system_clock_new_works() {
let clock = SystemClock::new();
let now = clock.now();
assert!(now <= chrono::Utc::now());
}
#[test]
fn mock_clock_set_time_updates_time() {
let initial = chrono::Utc::now();
let clock = MockClock::new(initial);
assert_eq!(clock.now(), initial);
let new_time = initial + chrono::Duration::seconds(3600);
clock.set_time(new_time);
assert_eq!(clock.now(), new_time, "set_time 后 now() 应返回新时间");
}
#[test]
fn mock_clock_advance_forward() {
let initial = chrono::Utc::now();
let clock = MockClock::new(initial);
clock.advance(chrono::Duration::seconds(100));
assert_eq!(clock.now(), initial + chrono::Duration::seconds(100));
}
#[test]
fn mock_clock_advance_backward() {
let initial = chrono::Utc::now();
let clock = MockClock::new(initial);
clock.advance(chrono::Duration::seconds(-50));
assert_eq!(clock.now(), initial + chrono::Duration::seconds(-50));
}
#[test]
fn mock_clock_clone_shares_state() {
let initial = chrono::Utc::now();
let clock1 = MockClock::new(initial);
let clock2 = clock1.clone();
clock1.set_time(initial + chrono::Duration::seconds(999));
assert_eq!(
clock2.now(),
initial + chrono::Duration::seconds(999),
"Clone 后应共享时间状态"
);
}