use super::mock::MockDao;
use super::*;
use crate::core::token::UuidTokenStyle;
use crate::dao::GarrisonDao;
use crate::session::token_key;
use async_trait::async_trait;
use std::time::Duration;
fn make_auth_logic(timeout: u64, active_timeout: u64) -> AuthLogicDefault {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao, timeout, active_timeout, 0));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
AuthLogicDefault::new(session, token_handler, timeout as i64)
}
struct TestAllowAllGuard;
#[async_trait::async_trait]
impl SwitchToGuard for TestAllowAllGuard {
async fn check(&self, _original: &str, _target: &str) -> GarrisonResult<()> {
Ok(())
}
}
fn make_auth_logic_allow_switch(timeout: u64, active_timeout: u64) -> AuthLogicDefault {
make_auth_logic(timeout, active_timeout).with_switch_to_guard(Arc::new(TestAllowAllGuard))
}
#[tokio::test]
async fn login_generates_token_and_session() {
let auth = make_auth_logic(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
assert!(!token.is_empty());
assert!(auth.is_login(&token).await.unwrap());
}
#[tokio::test]
async fn login_associates_login_id() {
let auth = make_auth_logic(3600, 86400);
let token = auth.login("2002", None).await.unwrap();
let login_id = auth.get_login_id(&token).await.unwrap();
assert_eq!(login_id, Some("2002".to_string()));
}
#[tokio::test]
async fn login_generates_unique_tokens() {
let auth = make_auth_logic(3600, 86400);
let t1 = auth.login("1001", None).await.unwrap();
let t2 = auth.login("1001", None).await.unwrap();
assert_ne!(t1, t2);
}
#[tokio::test]
async fn logout_destroys_session() {
let auth = make_auth_logic(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
assert!(auth.is_login(&token).await.unwrap());
auth.logout(&token).await.unwrap();
assert!(!auth.is_login(&token).await.unwrap());
}
#[tokio::test]
async fn logout_idempotent_for_invalid_token() {
let auth = make_auth_logic(3600, 86400);
let result = auth.logout("non-existent-token").await;
assert_eq!(
result.unwrap(),
(),
"不存在的 token logout 应返回 Ok(())(幂等)"
);
}
#[tokio::test]
async fn logout_preserves_other_tokens() {
let auth = make_auth_logic(3600, 86400);
let t1 = auth.login("1001", None).await.unwrap();
let t2 = auth.login("1001", None).await.unwrap();
auth.logout(&t1).await.unwrap();
assert!(auth.is_login(&t2).await.unwrap());
assert!(!auth.is_login(&t1).await.unwrap());
}
#[tokio::test]
async fn is_login_valid_token_returns_true() {
let auth = make_auth_logic(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
assert!(auth.is_login(&token).await.unwrap());
}
#[tokio::test]
async fn is_login_invalid_token_returns_false() {
let auth = make_auth_logic(3600, 86400);
assert!(!auth.is_login("invalid-token").await.unwrap());
}
#[tokio::test]
async fn get_login_id_valid_token_returns_some() {
let auth = make_auth_logic(3600, 86400);
let token = auth.login("3003", None).await.unwrap();
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("3003".to_string())
);
}
#[tokio::test]
async fn get_login_id_invalid_token_returns_none() {
let auth = make_auth_logic(3600, 86400);
assert_eq!(auth.get_login_id("invalid").await.unwrap(), None);
}
#[tokio::test]
async fn verify_token_valid_returns_login_id() {
let auth = make_auth_logic(3600, 86400);
let token = auth.login("4004", None).await.unwrap();
assert_eq!(auth.verify_token(&token).await.unwrap(), "4004".to_string());
}
#[tokio::test]
async fn verify_token_invalid_returns_error() {
let auth = make_auth_logic(3600, 86400);
let result = auth.verify_token("invalid-token").await;
assert!(result.is_err());
match result.err() {
Some(GarrisonError::InvalidToken(_)) => {},
other => panic!("期望 InvalidToken,实际: {:?}", other),
}
}
#[tokio::test]
async fn verify_token_expired_returns_error() {
let auth = make_auth_logic(1, 1);
let token = auth.login("5005", None).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let result = auth.verify_token(&token).await;
assert!(result.is_err());
}
#[tokio::test]
async fn switch_to_updates_login_id_and_stores_switched_from() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
auth.switch_to(&token, "2002").await.unwrap();
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("2002".to_string())
);
let switched_from = auth.session.get(&token, "switched_from").await.unwrap();
assert_eq!(switched_from, Some("1001".to_string()));
}
#[tokio::test]
async fn switch_to_resets_amr_ledger_and_auth_time() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
auth.session
.append_amr_entry(&token, "otp", 2, chrono::Utc::now().timestamp())
.await
.unwrap();
let before = auth
.session
.get_token_session(&token)
.await
.unwrap()
.unwrap();
assert_eq!(before.amr_ledger.len(), 2, "前置:账本应含 pwd + otp");
assert!(before.auth_time.is_some(), "前置:auth_time 应已播种");
auth.switch_to(&token, "2002").await.unwrap();
let after = auth
.session
.get_token_session(&token)
.await
.unwrap()
.unwrap();
assert!(
after.amr_ledger.is_empty(),
"身份切换后因子账本应清空(原主体 step-up 不得继承),实际: {:?}",
after.amr_ledger
);
assert_eq!(
after.auth_time, None,
"身份切换后 auth_time 应置 None(freshness 判 Stale 强制重新 step-up)"
);
}
#[tokio::test]
async fn switch_to_preserves_token_validity() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
auth.switch_to(&token, "2002").await.unwrap();
assert!(auth.is_login(&token).await.unwrap());
}
#[tokio::test]
async fn switch_to_invalid_token_returns_not_login() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let result = auth.switch_to("invalid-token", "2002").await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"无效 token 应返回 NotLogin,实际: {:?}",
result
);
}
#[tokio::test]
async fn switch_to_empty_target_returns_invalid_param() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let result = auth.switch_to(&token, "").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"空 target_login_id 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn switch_to_verify_token_returns_new_login_id() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("9999", None).await.unwrap();
auth.switch_to(&token, "9999").await.unwrap();
assert_eq!(auth.verify_token(&token).await.unwrap(), "9999");
}
#[tokio::test]
async fn switch_to_multiple_times_updates_switched_from() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
let _ = auth.login("3003", None).await.unwrap();
auth.switch_to(&token, "2002").await.unwrap();
assert_eq!(
auth.session.get(&token, "switched_from").await.unwrap(),
Some("1001".to_string())
);
auth.switch_to(&token, "3003").await.unwrap();
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("3003".to_string())
);
assert_eq!(
auth.session.get(&token, "switched_from").await.unwrap(),
Some("2002".to_string())
);
}
#[tokio::test]
async fn switch_to_preserves_existing_attrs() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
auth.session.set(&token, "device", "web").await.unwrap();
auth.switch_to(&token, "2002").await.unwrap();
let device = auth.session.get(&token, "device").await.unwrap();
assert_eq!(device, Some("web".to_string()));
let switched_from = auth.session.get(&token, "switched_from").await.unwrap();
assert_eq!(switched_from, Some("1001".to_string()));
}
#[tokio::test]
async fn switch_to_removes_token_from_original_account_session() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
let original_before = auth
.session
.get_account_session("1001")
.await
.unwrap()
.expect("切换前 original AccountSession 应存在");
assert!(
original_before.tokens.iter().any(|ti| ti.token == token),
"切换前 original AccountSession 应包含该 token"
);
auth.switch_to(&token, "2002").await.unwrap();
let original_after = auth
.session
.get_account_session("1001")
.await
.unwrap()
.expect("切换后 original AccountSession 应仍存在");
assert!(
!original_after.tokens.iter().any(|ti| ti.token == token),
"切换后 original AccountSession 不应再包含该 token(H1 数据一致性),实际 tokens: {:?}",
original_after.tokens
);
let target_after = auth
.session
.get_account_session("2002")
.await
.unwrap()
.expect("切换后 target AccountSession 应存在");
assert!(
target_after.tokens.iter().any(|ti| ti.token == token),
"切换后 target AccountSession 应包含该 token,实际 tokens: {:?}",
target_after.tokens
);
}
#[tokio::test]
async fn switch_to_removes_token_from_original_login_token_map() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
let tokens_before: Vec<String> = auth.session.get_tokens_by_login_id("1001");
assert!(
tokens_before.iter().any(|t| t == &token),
"切换前 original 内存索引应包含该 token"
);
auth.switch_to(&token, "2002").await.unwrap();
let tokens_after: Vec<String> = auth.session.get_tokens_by_login_id("1001");
assert!(
!tokens_after.iter().any(|t| t == &token),
"切换后 original 内存索引不应再包含该 token(H1 内存索引一致性),实际: {:?}",
tokens_after
);
let target_tokens: Vec<String> = auth.session.get_tokens_by_login_id("2002");
assert!(
target_tokens.iter().any(|t| t == &token),
"切换后 target 内存索引应包含该 token,实际: {:?}",
target_tokens
);
}
#[tokio::test]
async fn switch_to_default_impl_returns_not_implemented() {
struct NoSwitchAuth;
#[async_trait]
impl AuthLogic for NoSwitchAuth {
async fn login(&self, _id: &str, _params: Option<&str>) -> GarrisonResult<String> {
Ok("token".to_string())
}
async fn logout(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn is_login(&self, _token: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn get_login_id(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(Some("id".to_string()))
}
async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
Ok("id".to_string())
}
}
let auth = NoSwitchAuth;
let result = auth.switch_to("token", "target").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
let _ = auth.login("u1", None).await.unwrap();
auth.logout("t").await.unwrap();
let _ = auth.is_login("t").await.unwrap();
let _ = auth.get_login_id("t").await.unwrap();
let _ = auth.verify_token("t").await.unwrap();
}
#[tokio::test]
async fn switch_to_default_guard_denies_all_switches() {
let auth = make_auth_logic(3600, 86400); let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("2002", None).await.unwrap();
let result = auth.switch_to(&token, "2002").await;
assert!(
matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("core-switch-to-denied")),
"默认 guard 应拒绝切换并返回 NotPermission,实际: {:?}",
result
);
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("1001".to_string())
);
}
#[tokio::test]
async fn switch_to_custom_guard_denies_preserves_session() {
struct DenyTargetGuard;
#[async_trait]
impl SwitchToGuard for DenyTargetGuard {
async fn check(&self, _original: &str, target: &str) -> GarrisonResult<()> {
if target == "admin" {
return Err(GarrisonError::NotPermission(format!(
"禁止切换到管理员身份: {}",
target
)));
}
Ok(())
}
}
let auth = make_auth_logic(3600, 86400).with_switch_to_guard(Arc::new(DenyTargetGuard));
let token = auth.login("1001", None).await.unwrap();
let _ = auth.login("user-2002", None).await.unwrap();
let _ = auth.login("admin", None).await.unwrap();
let result = auth.switch_to(&token, "admin").await;
assert!(
matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("禁止切换")),
"切换到 admin 应被拒绝,实际: {:?}",
result
);
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("1001".to_string())
);
auth.switch_to(&token, "user-2002").await.unwrap();
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("user-2002".to_string())
);
}
#[tokio::test]
async fn switch_to_nonexistent_target_returns_invalid_param() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let result = auth.switch_to(&token, "ghost-user").await;
assert!(
matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("core-auth-switch-to-denied")),
"切换到不存在的 target 应返回统一的模糊 NotPermission(issue 2663 反枚举),实际: {:?}",
result
);
assert_eq!(
auth.get_login_id(&token).await.unwrap(),
Some("1001".to_string())
);
}
#[tokio::test]
async fn switch_to_target_check_precedes_guard() {
let auth = make_auth_logic_allow_switch(3600, 86400);
let token = auth.login("1001", None).await.unwrap();
let result = auth.switch_to(&token, "ghost").await;
assert!(
matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("core-auth-switch-to-denied")),
"target 不存在时应优先返回统一的模糊 NotPermission,实际: {:?}",
result
);
}
#[tokio::test]
async fn renew_to_equivalent_returns_new_valid_token_with_same_login_id() {
let auth = make_auth_logic(3600, 86400);
let old_token = auth.login("1001", None).await.unwrap();
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
assert!(!new_token.is_empty());
assert!(auth.is_login(&new_token).await.unwrap());
assert_eq!(
auth.get_login_id(&new_token).await.unwrap(),
Some("1001".to_string())
);
}
#[tokio::test]
async fn renew_to_equivalent_generates_different_token_string() {
let auth = make_auth_logic(3600, 86400);
let old_token = auth.login("1001", None).await.unwrap();
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
assert_ne!(old_token, new_token);
}
#[tokio::test]
async fn renew_to_equivalent_invalidates_old_token() {
let auth = make_auth_logic(3600, 86400);
let old_token = auth.login("1001", None).await.unwrap();
assert!(auth.is_login(&old_token).await.unwrap());
let _new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
assert!(!auth.is_login(&old_token).await.unwrap());
}
#[tokio::test]
async fn renew_to_equivalent_preserves_attrs() {
let auth = make_auth_logic(3600, 86400);
let old_token = auth.login("1001", None).await.unwrap();
auth.session
.set(&old_token, "device", "web-chrome")
.await
.unwrap();
auth.session.set(&old_token, "role", "admin").await.unwrap();
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
let device = auth.session.get(&new_token, "device").await.unwrap();
assert_eq!(device, Some("web-chrome".to_string()));
let role = auth.session.get(&new_token, "role").await.unwrap();
assert_eq!(role, Some("admin".to_string()));
}
#[tokio::test]
async fn renew_to_equivalent_preserves_device() {
let auth = make_auth_logic(3600, 86400);
let old_token = auth.login("1001", None).await.unwrap();
auth.session
.set_device(&old_token, "mobile-ios")
.await
.unwrap();
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
let ts = auth.session.get_token_session(&new_token).await.unwrap();
assert!(ts.is_some(), "新 token session 应存在");
assert_eq!(ts.unwrap().device, Some("mobile-ios".to_string()));
}
#[tokio::test]
async fn renew_to_equivalent_invalid_token_returns_not_login() {
let auth = make_auth_logic(3600, 86400);
let result = auth.renew_to_equivalent("invalid-token").await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(_))),
"无效 token 应返回 NotLogin,实际: {:?}",
result
);
}
#[tokio::test]
async fn renew_to_equivalent_preserves_remaining_ttl() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
let auth = AuthLogicDefault::new(session, token_handler, 3600);
let old_token = auth.login("1001", None).await.unwrap();
let token_session_key = token_key(&old_token);
dao.expire(&token_session_key, 100).await.unwrap();
let old_ttl = auth.session.get_token_timeout(&old_token).await.unwrap();
assert!(old_ttl.is_some(), "旧 token 应有 TTL");
let old_secs = old_ttl.unwrap().as_secs();
assert!(old_secs <= 100, "旧 TTL 应 ≤ 100s,实际: {}", old_secs);
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
let new_ttl = auth.session.get_token_timeout(&new_token).await.unwrap();
assert!(new_ttl.is_some(), "新 token 应有 TTL");
let new_secs = new_ttl.unwrap().as_secs();
assert!(
new_secs <= 100,
"新 TTL 应继承剩余 TTL (≤100s),实际: {}(可能被重置为 3600s)",
new_secs
);
}
#[tokio::test]
async fn renew_to_equivalent_default_impl_returns_not_implemented() {
struct NoRenewAuth;
#[async_trait]
impl AuthLogic for NoRenewAuth {
async fn login(&self, _id: &str, _params: Option<&str>) -> GarrisonResult<String> {
Ok("token".to_string())
}
async fn logout(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn is_login(&self, _token: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn get_login_id(&self, _token: &str) -> GarrisonResult<Option<String>> {
Ok(Some("id".to_string()))
}
async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
Ok("id".to_string())
}
}
let auth = NoRenewAuth;
let result = auth.renew_to_equivalent("token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
let _ = auth.login("u1", None).await.unwrap();
auth.logout("t").await.unwrap();
let _ = auth.is_login("t").await.unwrap();
let _ = auth.get_login_id("t").await.unwrap();
let _ = auth.verify_token("t").await.unwrap();
}
struct OrderTrackingDao {
inner: MockDao,
tracking_state: std::sync::Mutex<OrderTrackingState>,
}
struct OrderTrackingState {
enabled: bool,
old_token: String,
new_token_created: bool,
old_token_deleted: bool,
dos_gap_violation: bool,
}
impl OrderTrackingDao {
fn new() -> Self {
Self {
inner: MockDao::new(),
tracking_state: std::sync::Mutex::new(OrderTrackingState {
enabled: false,
old_token: String::new(),
new_token_created: false,
old_token_deleted: false,
dos_gap_violation: false,
}),
}
}
fn start_tracking(&self, old_token: String) {
let mut state = self.tracking_state.lock().unwrap();
state.enabled = true;
state.old_token = old_token;
state.new_token_created = false;
state.old_token_deleted = false;
state.dos_gap_violation = false;
}
fn was_dos_gap_violation(&self) -> bool {
self.tracking_state.lock().unwrap().dos_gap_violation
}
fn was_old_token_deleted(&self) -> bool {
self.tracking_state.lock().unwrap().old_token_deleted
}
}
#[async_trait]
impl GarrisonDao for OrderTrackingDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
self.inner.get(key).await
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
{
let mut state = self.tracking_state.lock().unwrap();
if state.enabled
&& key.starts_with("token:session:")
&& key != token_key(&state.old_token)
{
state.new_token_created = true;
}
}
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<()> {
{
let mut state = self.tracking_state.lock().unwrap();
if state.enabled && key == token_key(&state.old_token) {
if !state.new_token_created {
state.dos_gap_violation = true;
}
state.old_token_deleted = true;
}
}
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!();
}
#[tokio::test]
async fn a9_renew_to_equivalent_creates_new_before_deleting_old() {
{
let d = OrderTrackingDao::new();
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 tracking_dao = Arc::new(OrderTrackingDao::new());
let session = Arc::new(GarrisonSession::new(
tracking_dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
let auth = AuthLogicDefault::new(session, token_handler, 3600);
let old_token = auth.login("1001", None).await.unwrap();
tracking_dao.start_tracking(old_token.clone());
let new_token = auth.renew_to_equivalent(&old_token).await;
assert!(
new_token.is_ok(),
"renew 应成功,实际: {:?}",
new_token.err()
);
assert!(
!tracking_dao.was_dos_gap_violation(),
"A9 违规:旧 token 在新 token 创建前被删除(DoS gap window),\
应先创建新 token 再删除旧 token"
);
assert!(
tracking_dao.was_old_token_deleted(),
"A9 清理校验:旧 token session 应在 renew 完成后被删除"
);
}
#[tokio::test]
async fn a9_renew_to_equivalent_old_token_valid_until_new_created() {
let tracking_dao = Arc::new(OrderTrackingDao::new());
let session = Arc::new(GarrisonSession::new(
tracking_dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
let auth = AuthLogicDefault::new(session, token_handler, 3600);
let old_token = auth.login("1002", None).await.unwrap();
tracking_dao.start_tracking(old_token.clone());
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
assert!(
!auth.is_login(&old_token).await.unwrap(),
"renew 后旧 token 应失效"
);
assert!(
auth.is_login(&new_token).await.unwrap(),
"renew 后新 token 应有效"
);
assert_eq!(
auth.get_login_id(&new_token).await.unwrap(),
Some("1002".to_string()),
"新 token 的 login_id 应与旧 token 相同"
);
assert!(
!tracking_dao.was_dos_gap_violation(),
"A9 违规:renew 过程中存在 DoS gap(旧 token 先于新 token 创建被删除)"
);
}
fn make_auth_logic_with_remember_me(
timeout: u64,
active_timeout: u64,
rm_enabled: bool,
rm_timeout: i64,
) -> AuthLogicDefault {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao, timeout, active_timeout, 0));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
AuthLogicDefault::new(session, token_handler, timeout as i64)
.with_remember_me(rm_enabled, rm_timeout)
}
#[tokio::test]
async fn login_with_remember_me_true_uses_extended_timeout() {
let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
let token = auth.login("1001", Some("remember_me=true")).await.unwrap();
assert!(auth.is_login(&token).await.unwrap());
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some(), "Token-Session 应有 TTL");
let secs = ttl.unwrap().as_secs();
assert!(
secs > 3_600 && secs <= 7_776_000,
"remember_me TTL 应接近 7776000s,实际: {}s",
secs
);
}
#[tokio::test]
async fn login_with_remember_me_true_but_disabled_uses_default_timeout() {
let auth = make_auth_logic_with_remember_me(3600, 86400, false, 7_776_000);
let token = auth.login("1001", Some("remember_me=true")).await.unwrap();
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some());
let secs = ttl.unwrap().as_secs();
assert!(
secs <= 3600,
"disabled 时 TTL 应为默认 3600s,实际: {}s",
secs
);
}
#[tokio::test]
async fn login_with_remember_me_false_uses_default_timeout() {
let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
let token = auth.login("1001", Some("remember_me=false")).await.unwrap();
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some());
let secs = ttl.unwrap().as_secs();
assert!(
secs <= 3600,
"remember_me=false 时 TTL 应为默认 3600s,实际: {}s",
secs
);
}
#[tokio::test]
async fn login_with_none_params_uses_default_timeout() {
let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
let token = auth.login("1001", None).await.unwrap();
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some());
let secs = ttl.unwrap().as_secs();
assert!(
secs <= 3600,
"None params 时 TTL 应为默认 3600s,实际: {}s",
secs
);
}
#[tokio::test]
async fn login_with_empty_params_uses_default_timeout() {
let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
let token = auth.login("1001", Some("")).await.unwrap();
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some());
let secs = ttl.unwrap().as_secs();
assert!(
secs <= 3600,
"empty params 时 TTL 应为默认 3600s,实际: {}s",
secs
);
}
#[tokio::test]
async fn login_with_remember_me_and_other_params() {
let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
let token = auth
.login("1001", Some("remember_me=true&device=web"))
.await
.unwrap();
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some());
let secs = ttl.unwrap().as_secs();
assert!(
secs > 3_600 && secs <= 7_776_000,
"组合参数中 remember_me=true 应使用扩展 TTL,实际: {}s",
secs
);
}
#[tokio::test]
async fn login_with_malformed_params_uses_default_timeout() {
let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
let token = auth.login("1001", Some("malformed")).await.unwrap();
let ttl = auth.session.get_token_timeout(&token).await.unwrap();
assert!(ttl.is_some());
let secs = ttl.unwrap().as_secs();
assert!(
secs <= 3600,
"malformed params 时 TTL 应为默认 3600s,实际: {}s",
secs
);
}
#[test]
fn parse_remember_me_param_various_inputs() {
assert!(parse_remember_me_param(Some("remember_me=true")));
assert!(!parse_remember_me_param(Some("remember_me=false")));
assert!(parse_remember_me_param(Some("remember_me=true&device=web")));
assert!(parse_remember_me_param(Some("device=web&remember_me=true")));
assert!(!parse_remember_me_param(Some("")));
assert!(!parse_remember_me_param(None));
assert!(!parse_remember_me_param(Some("remember_me=1")));
assert!(!parse_remember_me_param(Some("malformed")));
}
#[tokio::test(flavor = "multi_thread")]
async fn renew_to_equivalent_concurrent_serialization() {
let auth = Arc::new(make_auth_logic(3600, 86400));
let old_token = auth.login("race-user", None).await.unwrap();
let auth1 = auth.clone();
let auth2 = auth.clone();
let auth3 = auth.clone();
let old1 = old_token.clone();
let old2 = old_token.clone();
let old3 = old_token.clone();
let h1 = tokio::spawn(async move { auth1.renew_to_equivalent(&old1).await });
let h2 = tokio::spawn(async move { auth2.renew_to_equivalent(&old2).await });
let h3 = tokio::spawn(async move { auth3.renew_to_equivalent(&old3).await });
let res1 = h1.await.expect("h1 join failed");
let res2 = h2.await.expect("h2 join failed");
let res3 = h3.await.expect("h3 join failed");
let results = [res1, res2, res3];
let success_count = results.iter().filter(|r| r.is_ok()).count();
let err_count = results.iter().filter(|r| r.is_err()).count();
assert_eq!(
success_count, 1,
"并发 renew 应恰好 1 个成功,实际 {} 个成功 — 揭示 CWE-362 TOCTOU 竞态未修复",
success_count
);
assert_eq!(
err_count, 2,
"并发 renew 应 2 个失败,实际 {} 个失败",
err_count
);
}
#[tokio::test]
async fn renew_locks_entry_cleaned_after_successful_renew() {
let auth = Arc::new(make_auth_logic(3600, 86400));
let old_token = auth.login("cleanup-user", None).await.unwrap();
assert!(
auth.renew_locks.is_empty(),
"renew 前 renew_locks 应为空,实际有 {} 个 entry",
auth.renew_locks.len()
);
let new_token = auth
.renew_to_equivalent(&old_token)
.await
.expect("renew 应成功");
assert!(
auth.renew_locks.is_empty(),
"renew 后 renew_locks 应被清理为空,实际残留 {} 个 entry",
auth.renew_locks.len()
);
assert!(
!auth.is_login(&old_token).await.unwrap(),
"旧 token 应已失效"
);
assert!(auth.is_login(&new_token).await.unwrap(), "新 token 应有效");
}
#[tokio::test]
async fn renew_locks_entry_cleaned_after_failed_renew() {
let auth = Arc::new(make_auth_logic(3600, 86400));
for i in 0..5 {
let fake_token = format!("fake-token-{}", i);
let result = auth.renew_to_equivalent(&fake_token).await;
assert!(result.is_err(), "fake token renew 应失败(迭代 {})", i);
assert!(
auth.renew_locks.is_empty(),
"失败 renew 后 renew_locks 应清理为空(迭代 {}),实际残留 {} 个 entry",
i,
auth.renew_locks.len()
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn renew_locks_entry_cleaned_after_concurrent_renew() {
let auth = Arc::new(make_auth_logic(3600, 86400));
let old_token = auth.login("concurrent-cleanup-user", None).await.unwrap();
let auth1 = auth.clone();
let auth2 = auth.clone();
let auth3 = auth.clone();
let old1 = old_token.clone();
let old2 = old_token.clone();
let old3 = old_token.clone();
let h1 = tokio::spawn(async move { auth1.renew_to_equivalent(&old1).await });
let h2 = tokio::spawn(async move { auth2.renew_to_equivalent(&old2).await });
let h3 = tokio::spawn(async move { auth3.renew_to_equivalent(&old3).await });
let _ = h1.await.expect("h1 join failed");
let _ = h2.await.expect("h2 join failed");
let _ = h3.await.expect("h3 join failed");
assert!(
auth.renew_locks.is_empty(),
"并发 renew 全部完成后 renew_locks 应清理为空,实际残留 {} 个 entry",
auth.renew_locks.len()
);
}
use std::sync::atomic::{AtomicBool, Ordering};
struct FailingDao {
inner: MockDao,
fail_token_session_set: AtomicBool,
fail_account_session_set: AtomicBool,
fail_token_session_delete: AtomicBool,
}
impl FailingDao {
fn new() -> Self {
Self {
inner: MockDao::new(),
fail_token_session_set: AtomicBool::new(false),
fail_account_session_set: AtomicBool::new(false),
fail_token_session_delete: AtomicBool::new(false),
}
}
}
#[async_trait]
impl GarrisonDao for FailingDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
self.inner.get(key).await
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
if key.starts_with("token:session:") && self.fail_token_session_set.load(Ordering::SeqCst) {
return Err(GarrisonError::Dao(format!("failing-dao-set::{}", key)));
}
if key.starts_with("account:session:")
&& self.fail_account_session_set.load(Ordering::SeqCst)
{
return Err(GarrisonError::Dao(format!("failing-dao-set::{}", key)));
}
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<()> {
if key.starts_with("token:session:")
&& self.fail_token_session_delete.load(Ordering::SeqCst)
{
return Err(GarrisonError::Dao(format!("failing-dao-delete::{}", key)));
}
self.inner.delete(key).await
}
async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
self.inner.get_timeout(key).await
}
async fn get_with_ttl(&self, key: &str) -> GarrisonResult<Option<(String, Option<Duration>)>> {
self.inner.get_with_ttl(key).await
}
crate::atomic_test_fallback!();
}
fn make_auth_logic_with_failing_dao(dao: Arc<FailingDao>) -> AuthLogicDefault {
let session = Arc::new(GarrisonSession::new(
dao as Arc<dyn GarrisonDao>,
3600,
86400,
0,
));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
AuthLogicDefault::new(session, token_handler, 3600)
}
#[tokio::test]
async fn renew_create_new_token_session_fails_old_token_untouched() {
{
let d = FailingDao::new();
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 failing = Arc::new(FailingDao::new());
let auth = make_auth_logic_with_failing_dao(failing.clone());
let old_token = auth.login("1001", None).await.unwrap();
failing.fail_token_session_set.store(true, Ordering::SeqCst);
let result = auth.renew_to_equivalent(&old_token).await;
assert!(
matches!(result, Err(GarrisonError::Internal(ref msg))
if msg.contains("core-auth-token-renew-create-failed")),
"创建新 Token-Session 失败应返回 Internal,实际: {:?}",
result
);
assert!(
auth.is_login(&old_token).await.unwrap(),
"步骤 3 失败后旧 token 必须仍有效(A9 无 DoS 契约)"
);
}
#[tokio::test]
async fn renew_add_to_account_session_fails_rolls_back_new_token() {
let failing = Arc::new(FailingDao::new());
let auth = make_auth_logic_with_failing_dao(failing.clone());
let old_token = auth.login("1001", None).await.unwrap();
failing
.fail_account_session_set
.store(true, Ordering::SeqCst);
let result = auth.renew_to_equivalent(&old_token).await;
assert!(
matches!(result, Err(GarrisonError::Internal(ref msg))
if msg.contains("core-auth-token-renew-add-to-account-failed")),
"加入 Account-Session 失败应返回 Internal,实际: {:?}",
result
);
assert!(
auth.is_login(&old_token).await.unwrap(),
"步骤 5 失败回滚后旧 token 必须仍有效"
);
let account = auth
.session
.get_account_session("1001")
.await
.unwrap()
.expect("Account-Session 应存在");
assert_eq!(
account.tokens.len(),
1,
"回滚后 Account-Session 应仅剩旧 token(无残留),实际: {:?}",
account.tokens
);
assert_eq!(account.tokens[0].token, old_token);
}
#[tokio::test]
async fn renew_old_token_cleanup_failure_still_returns_new_token() {
let failing = Arc::new(FailingDao::new());
let auth = make_auth_logic_with_failing_dao(failing.clone());
let old_token = auth.login("1001", None).await.unwrap();
failing
.fail_token_session_delete
.store(true, Ordering::SeqCst);
let result = auth.renew_to_equivalent(&old_token).await;
let new_token = result.expect("步骤 6 失败不应改变 renew 的 Ok 契约(告警而非失败)");
assert_ne!(old_token, new_token);
assert!(
auth.is_login(&new_token).await.unwrap(),
"新 token 必须有效(A9:新 token 已完全建立后才失效旧 token)"
);
}
#[cfg(feature = "protocol-jwt")]
mod amr_claim_issuance {
use super::mock::MockDao;
use super::*;
use crate::core::token::JwtTokenStyle;
fn make_jwt_auth_logic() -> (AuthLogicDefault, Arc<GarrisonSession>) {
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(JwtTokenStyle::new("0123456789abcdef0123456789abcdef"));
(
AuthLogicDefault::new(Arc::clone(&session), token_handler, 3600),
session,
)
}
fn verify_claims(token: &str) -> crate::protocol::jwt::GarrisonJwtClaims {
crate::protocol::jwt::JwtHandler::new("0123456789abcdef0123456789abcdef")
.verify(token)
.unwrap()
}
#[tokio::test]
async fn jwt_login_carries_primary_amr_and_auth_time() {
let (auth, _session) = make_jwt_auth_logic();
let token = auth.login("1001", None).await.unwrap();
let claims = verify_claims(&token);
assert_eq!(
claims.amr,
Some(vec![crate::stp::mfa::PRIMARY_FACTOR_AMR.to_string()]),
"主登录签发应带主因子 amr"
);
assert!(claims.auth_time.is_some(), "主登录签发应带 auth_time");
}
#[tokio::test]
async fn renew_to_equivalent_preserves_ledger_claims() {
let (auth, session) = make_jwt_auth_logic();
let old_token = auth.login("1001", None).await.unwrap();
let ts_auth_time = {
let ts = session
.get_token_session(&old_token)
.await
.unwrap()
.unwrap();
ts.auth_time.unwrap()
};
session
.append_amr_entry(&old_token, "otp", 2, ts_auth_time + 30)
.await
.unwrap();
let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
let claims = verify_claims(&new_token);
assert_eq!(
claims.amr,
Some(vec!["pwd".to_string(), "otp".to_string()]),
"renew 后 amr 应从账本映射(含 step-up 因子)"
);
assert_eq!(
claims.auth_time,
Some(ts_auth_time),
"renew 后 auth_time 应延续会话 auth_time"
);
}
}
fn make_auth_logic_with_seed(seed_enabled: bool) -> AuthLogicDefault {
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);
AuthLogicDefault::new(session, token_handler, 3600).with_seed_primary_amr(seed_enabled)
}
#[tokio::test]
async fn core_login_seeds_primary_amr_by_default() {
let auth = make_auth_logic_with_seed(true);
let token = auth.login("seed-user-1", None).await.unwrap();
let ts = auth
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应存在");
assert_eq!(ts.amr_ledger.len(), 1, "默认应播种主因子");
assert_eq!(ts.amr_ledger[0].method, "pwd");
assert_eq!(ts.amr_ledger[0].aal, 1);
assert!(ts.auth_time.is_some(), "默认应写 auth_time");
}
#[tokio::test]
async fn core_login_skips_amr_seeding_when_disabled() {
let auth = make_auth_logic_with_seed(false);
let token = auth.login("seed-user-2", None).await.unwrap();
let ts = auth
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应存在");
assert!(
ts.amr_ledger.is_empty(),
"开关关闭时不得播种 pwd 账本,实际: {:?}",
ts.amr_ledger
);
assert!(ts.auth_time.is_none(), "开关关闭时 auth_time 应为 None");
}