use super::mock::MockDao;
use super::*;
use crate::core::token::UuidTokenStyle;
use crate::dao::GarrisonDao;
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));
let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
AuthLogicDefault::new(session, token_handler, timeout as i64)
}
#[allow(deprecated)]
fn make_auth_logic_allow_switch(timeout: u64, active_timeout: u64) -> AuthLogicDefault {
make_auth_logic(timeout, active_timeout).with_switch_to_guard(Arc::new(AllowAllSwitchToGuard))
}
#[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!(result.is_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_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
);
}
#[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("deny-all")),
"默认 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::InvalidParam(ref msg)) if msg.contains("core-auth-target-login-id-not-found")),
"切换到不存在的 target 应返回 InvalidParam,实际: {:?}",
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::InvalidParam(_))),
"target 不存在时应先返回 InvalidParam(而非 guard 的 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));
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 = format!("token:session:{}", 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
);
}
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 != format!("token:session:{}", 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 == format!("token:session:{}", 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
}
}
#[tokio::test]
async fn a9_renew_to_equivalent_creates_new_before_deleting_old() {
let tracking_dao = Arc::new(OrderTrackingDao::new());
let session = Arc::new(GarrisonSession::new(
tracking_dao.clone() as Arc<dyn GarrisonDao>,
3600,
86400,
));
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,
));
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));
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()
);
}