#[cfg(test)]
mod suite {
#![allow(clippy::useless_conversion)]
use crate::config::GarrisonConfig;
use crate::config::ReplacedLoginExitMode;
use crate::error::{GarrisonError, GarrisonResult};
use crate::stp::core::GarrisonCore;
use crate::stp::{GarrisonLogicDefault, JwtMode, LoginParams, SessionLogic};
use async_trait::async_trait;
use serial_test::serial;
use std::sync::Arc;
struct MockSession {
config: Arc<GarrisonConfig>,
}
impl GarrisonCore for MockSession {
fn config(&self) -> Arc<GarrisonConfig> {
Arc::clone(&self.config)
}
}
#[async_trait]
impl SessionLogic for MockSession {
async fn login(&self, _login_id: &str, _params: &LoginParams) -> GarrisonResult<String> {
Ok("mock-token".to_string())
}
async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn logout(&self) -> GarrisonResult<()> {
Ok(())
}
async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_login(&self) -> GarrisonResult<bool> {
Ok(true)
}
async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
Ok(Some("42".to_string()))
}
}
#[tokio::test]
async fn login_accepts_str_ref() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
let t1 = mock.login("42", &LoginParams::default()).await.unwrap();
let t2 = mock.login("alice", &LoginParams::default()).await.unwrap();
assert_eq!(t1, "mock-token");
assert_eq!(t2, "mock-token");
}
#[tokio::test]
async fn login_with_token_accepts_str_ref() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
mock.login_with_token("user-uuid", "tok").await.unwrap();
}
#[tokio::test]
async fn get_login_id_returns_string() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
let id = mock.get_login_id().await.unwrap().unwrap();
assert_eq!(id, "42");
}
#[tokio::test]
async fn login_by_token_default_returns_not_implemented() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
let result = mock.login_by_token("external").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn revoke_all_sessions_default_returns_not_implemented() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
let result = mock.revoke_all_sessions("1001").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn get_active_sessions_default_returns_not_implemented() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
let result = mock.get_active_sessions("1001").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn mock_session_all_methods_coverage() {
let mock = MockSession {
config: Arc::new(GarrisonConfig::default()),
};
let _ = mock.config();
mock.logout().await.unwrap();
mock.logout_by_login_id("u1").await.unwrap();
mock.kickout("u1").await.unwrap();
mock.kickout_by_token("t1").await.unwrap();
mock.revoke_token("t1").await.unwrap();
let _ = mock.check_login().await.unwrap();
}
#[cfg(feature = "security-extra")]
mod anomaly_integration {
use super::*;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::with_current_token;
use crate::strategy::alert::{
AlertListener, AlertListenerManager, AnomalyDetector, AnomalyType, SecurityAlertEvent,
};
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
struct MockDao {
store: Mutex<HashMap<String, (String, Option<Instant>)>>,
}
impl MockDao {
fn new() -> Self {
Self {
store: Mutex::new(HashMap::new()),
}
}
}
#[async_trait]
impl GarrisonDao for MockDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
let mut store = self.store.lock();
match store.get(key) {
Some((value, expire_at)) => {
if let Some(deadline) = expire_at {
if Instant::now() >= *deadline {
store.remove(key);
return Ok(None);
}
}
Ok(Some(value.clone()))
},
None => Ok(None),
}
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
let expire_at = if ttl_seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(ttl_seconds))
};
self.store
.lock()
.insert(key.to_string(), (value.to_string(), expire_at));
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let mut store = self.store.lock();
match store.get_mut(key) {
Some((existing, _)) => {
*existing = value.to_string();
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
let mut store = self.store.lock();
match store.get_mut(key) {
Some((_, expire_at)) => {
*expire_at = if seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(seconds))
};
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.store.lock().remove(key);
Ok(())
}
crate::atomic_test_fallback!();
}
struct MockFirewall;
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
struct MockAnomalyDetector {
login_call_count: AtomicUsize,
check_login_call_count: AtomicUsize,
login_events: Mutex<Vec<SecurityAlertEvent>>,
check_login_events: Mutex<Vec<SecurityAlertEvent>>,
fail_on_login: bool,
fail_on_check_login: bool,
}
impl MockAnomalyDetector {
fn new() -> Self {
Self {
login_call_count: AtomicUsize::new(0),
check_login_call_count: AtomicUsize::new(0),
login_events: Mutex::new(Vec::new()),
check_login_events: Mutex::new(Vec::new()),
fail_on_login: false,
fail_on_check_login: false,
}
}
fn with_login_event(event: SecurityAlertEvent) -> Self {
let det = Self::new();
det.login_events.lock().push(event);
det
}
fn with_check_login_event(event: SecurityAlertEvent) -> Self {
let det = Self::new();
det.check_login_events.lock().push(event);
det
}
fn failing_on_login() -> Self {
let mut det = Self::new();
det.fail_on_login = true;
det
}
fn failing_on_check_login() -> Self {
let mut det = Self::new();
det.fail_on_check_login = true;
det
}
fn login_calls(&self) -> usize {
self.login_call_count.load(Ordering::SeqCst)
}
fn check_login_calls(&self) -> usize {
self.check_login_call_count.load(Ordering::SeqCst)
}
}
#[async_trait]
impl AnomalyDetector for MockAnomalyDetector {
async fn check_on_login(
&self,
_login_id: &str,
_device_id: &str,
_ip: Option<&str>,
) -> GarrisonResult<Vec<SecurityAlertEvent>> {
self.login_call_count.fetch_add(1, Ordering::SeqCst);
if self.fail_on_login {
return Err(GarrisonError::Internal(
"stp-mock-login-detection-failed::".to_string(),
));
}
Ok(self.login_events.lock().clone())
}
async fn check_on_check_login(
&self,
_login_id: &str,
_token: &str,
) -> GarrisonResult<Vec<SecurityAlertEvent>> {
self.check_login_call_count.fetch_add(1, Ordering::SeqCst);
if self.fail_on_check_login {
return Err(GarrisonError::Internal(
"stp-mock-check-login-detection-failed::".to_string(),
));
}
Ok(self.check_login_events.lock().clone())
}
}
struct CountingAlertListener {
received: Mutex<Vec<SecurityAlertEvent>>,
}
impl CountingAlertListener {
fn new() -> Self {
Self {
received: Mutex::new(Vec::new()),
}
}
fn count(&self) -> usize {
self.received.lock().len()
}
fn events(&self) -> Vec<SecurityAlertEvent> {
self.received.lock().clone()
}
}
#[async_trait]
impl AlertListener for CountingAlertListener {
async fn on_alert(&self, event: &SecurityAlertEvent) -> GarrisonResult<()> {
self.received.lock().push(event.clone());
Ok(())
}
}
fn make_logic_with_anomaly(
detector: Arc<dyn AnomalyDetector>,
listener_manager: Arc<AlertListenerManager>,
) -> GarrisonLogicDefault {
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.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_anomaly_detector(detector)
.with_alert_listener_manager(listener_manager)
}
fn make_logic_without_anomaly() -> GarrisonLogicDefault {
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.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
}
fn sample_anomaly_event(login_id: &str) -> SecurityAlertEvent {
SecurityAlertEvent::AnomalyLogin {
login_id: login_id.to_string(),
anomaly_type: AnomalyType::IpChanged,
detail: "IP 变化检测".to_string(),
trace_id: "trace-t006".to_string(),
}
}
#[tokio::test]
async fn test_login_triggers_anomaly_alert() {
let listener = Arc::new(CountingAlertListener::new());
let manager = Arc::new(AlertListenerManager::new());
manager.add_listener(listener.clone() as Arc<dyn AlertListener>);
let detector = Arc::new(MockAnomalyDetector::with_login_event(sample_anomaly_event(
"1001",
)));
let logic = make_logic_with_anomaly(detector.clone(), manager);
let token = logic
.login("1001", &LoginParams::default())
.await
.expect("login 应成功");
assert!(!token.is_empty(), "login 应返回非空 token");
assert_eq!(detector.login_calls(), 1, "check_on_login 应被调用 1 次");
assert_eq!(listener.count(), 1, "应广播 1 个告警事件");
let events = listener.events();
assert!(
matches!(&events[0], SecurityAlertEvent::AnomalyLogin { login_id, .. } if login_id == "1001"),
"广播的事件应为 AnomalyLogin(login_id=1001)"
);
}
#[tokio::test]
async fn test_check_login_triggers_anomaly_alert() {
let listener = Arc::new(CountingAlertListener::new());
let manager = Arc::new(AlertListenerManager::new());
manager.add_listener(listener.clone() as Arc<dyn AlertListener>);
let detector = Arc::new(MockAnomalyDetector::with_check_login_event(
sample_anomaly_event("1001"),
));
let logic = Arc::new(make_logic_with_anomaly(detector.clone(), manager));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let valid =
with_current_token(token, async { logic.check_login().await.unwrap() }).await;
assert!(valid, "check_login 应返回 true(有效 token)");
assert_eq!(
detector.check_login_calls(),
1,
"check_on_check_login 应被调用 1 次"
);
assert_eq!(listener.count(), 1, "应广播 1 个告警事件");
}
#[tokio::test]
async fn test_login_detection_failure_does_not_interrupt() {
let listener = Arc::new(CountingAlertListener::new());
let manager = Arc::new(AlertListenerManager::new());
manager.add_listener(listener.clone() as Arc<dyn AlertListener>);
let detector = Arc::new(MockAnomalyDetector::failing_on_login());
let logic = make_logic_with_anomaly(detector.clone(), manager);
let token = logic
.login("1001", &LoginParams::default())
.await
.expect("检测失败时 login 仍应成功");
assert!(!token.is_empty(), "login 应返回非空 token");
assert_eq!(detector.login_calls(), 1, "check_on_login 应被调用 1 次");
assert_eq!(listener.count(), 0, "检测失败时不应广播事件");
}
#[tokio::test]
async fn test_check_login_detection_failure_does_not_interrupt() {
let listener = Arc::new(CountingAlertListener::new());
let manager = Arc::new(AlertListenerManager::new());
manager.add_listener(listener.clone() as Arc<dyn AlertListener>);
let detector = Arc::new(MockAnomalyDetector::failing_on_check_login());
let logic = Arc::new(make_logic_with_anomaly(detector.clone(), manager));
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let valid =
with_current_token(token, async { logic.check_login().await.unwrap() }).await;
assert!(valid, "检测失败时 check_login 仍应返回 true");
assert_eq!(
detector.check_login_calls(),
1,
"check_on_check_login 应被调用 1 次"
);
assert_eq!(listener.count(), 0, "检测失败时不应广播事件");
}
#[tokio::test]
async fn test_login_without_detector_skips_anomaly_check() {
let logic = make_logic_without_anomaly();
let token = logic
.login("1001", &LoginParams::default())
.await
.expect("未注入 detector 时 login 应正常工作");
assert!(!token.is_empty(), "login 应返回非空 token");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应已创建");
assert_eq!(ts.login_id, "1001");
}
#[tokio::test]
async fn test_check_login_without_detector_skips_anomaly_check() {
let logic = Arc::new(make_logic_without_anomaly());
let token = logic.login("1001", &LoginParams::default()).await.unwrap();
let valid =
with_current_token(token, async { logic.check_login().await.unwrap() }).await;
assert!(valid, "未注入 detector 时 check_login 应返回 true");
}
}
#[cfg(feature = "device-binding")]
mod device_binding_integration {
use super::*;
use crate::config::GarrisonConfig;
use crate::dao::tests::MockDao;
use crate::session::GarrisonSession;
use crate::strategy::alert::{AlertListener, AlertListenerManager, SecurityAlertEvent};
use crate::strategy::device_binding::{Disabled, LooseBinding, StrictBinding};
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::sync::Arc;
struct MockFirewall;
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
struct CountingAlertListener {
received: Mutex<Vec<SecurityAlertEvent>>,
}
impl CountingAlertListener {
fn new() -> Self {
Self {
received: Mutex::new(Vec::new()),
}
}
fn count(&self) -> usize {
self.received.lock().len()
}
fn events(&self) -> Vec<SecurityAlertEvent> {
self.received.lock().clone()
}
}
#[async_trait]
impl AlertListener for CountingAlertListener {
async fn on_alert(&self, event: &SecurityAlertEvent) -> GarrisonResult<()> {
self.received.lock().push(event.clone());
Ok(())
}
}
fn make_logic_base() -> GarrisonLogicDefault {
let dao: Arc<MockDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
}
#[tokio::test]
async fn test_strict_mode_new_device_triggers_mfa() {
let logic = make_logic_base();
let policy = Arc::new(StrictBinding::new(logic.session.clone()));
let logic = logic.with_device_binding_policy(policy);
let params = LoginParams {
device: Some("web-chrome".to_string()),
..Default::default()
};
let result = logic.login("1001", ¶ms).await;
assert!(
result.is_err(),
"strict 模式新设备 login 应被 hard block 阻断(A10 修复)"
);
match result {
Err(GarrisonError::NotPermission(msg)) => {
assert_eq!(
msg, "secondary auth required",
"错误消息应为 'secondary auth required'"
);
},
Err(other) => panic!("期望 NotPermission 错误,实际: {:?}", other),
Ok(_) => panic!("strict 模式新设备 login 不应成功(A10 hard block)"),
}
}
#[tokio::test]
async fn test_strict_mode_new_device_block_creates_no_session() {
let logic = make_logic_base();
let policy = Arc::new(StrictBinding::new(logic.session.clone()));
let logic = logic.with_device_binding_policy(policy);
let params = LoginParams {
device: Some("web-chrome".to_string()),
..Default::default()
};
let _ = logic.login("1001", ¶ms).await;
let tokens = logic.session.get_tokens_by_login_id("1001");
assert!(
tokens.is_empty(),
"hard block 后不应创建任何 session(无孤儿会话)"
);
}
#[tokio::test]
async fn test_strict_mode_old_device_no_mfa() {
let logic = make_logic_base();
let pre_params = LoginParams {
device: Some("web-chrome".to_string()),
..Default::default()
};
logic
.session
.create_token_session("1001", "pre-token-T2", &pre_params)
.await
.unwrap();
let policy = Arc::new(StrictBinding::new(logic.session.clone()));
let logic = logic.with_device_binding_policy(policy);
let params = LoginParams {
device: Some("web-chrome".to_string()),
..Default::default()
};
let token = logic
.login("1001", ¶ms)
.await
.expect("strict 模式旧设备 login 应成功");
assert!(!token.is_empty(), "login 应返回非空 token");
assert_ne!(token, "pre-token-T2", "应创建新 token(is_share=false)");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("新会话应已创建");
assert_eq!(ts.device.as_deref(), Some("web-chrome"));
}
#[tokio::test]
async fn test_loose_mode_new_device_alerts_no_block() {
let listener = Arc::new(CountingAlertListener::new());
let manager = Arc::new(AlertListenerManager::new());
manager.add_listener(listener.clone() as Arc<dyn AlertListener>);
let logic = make_logic_base();
let policy = Arc::new(LooseBinding::with_alert_manager(
logic.session.clone(),
manager,
));
let logic = logic.with_device_binding_policy(policy);
let params = LoginParams {
device: Some("mobile-ios".to_string()),
..Default::default()
};
let token = logic
.login("1001", ¶ms)
.await
.expect("loose 模式新设备 login 应成功(不阻断)");
assert!(!token.is_empty(), "login 应返回非空 token");
assert_eq!(
listener.count(),
1,
"loose 模式新设备应广播 1 次 NewDeviceLogin 告警"
);
let events = listener.events();
match &events[0] {
SecurityAlertEvent::NewDeviceLogin {
login_id,
device_id,
..
} => {
assert_eq!(login_id, "1001");
assert_eq!(device_id, "mobile-ios");
},
other => panic!("期望 NewDeviceLogin 事件,实际: {:?}", other),
}
}
#[tokio::test]
async fn test_disabled_mode_no_impact() {
let logic = make_logic_base();
let policy = Arc::new(Disabled);
let logic = logic.with_device_binding_policy(policy);
let params = LoginParams {
device: Some("any-device".to_string()),
..Default::default()
};
let token = logic
.login("1001", ¶ms)
.await
.expect("disabled 模式 login 应成功");
assert!(!token.is_empty(), "login 应返回非空 token");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应已创建");
assert_eq!(ts.login_id, "1001");
}
#[tokio::test]
async fn test_no_policy_skips_device_binding_check() {
let logic = make_logic_base();
let params = LoginParams {
device: Some("web-chrome".to_string()),
..Default::default()
};
let token = logic
.login("1001", ¶ms)
.await
.expect("未注入 policy 时 login 应正常工作");
assert!(!token.is_empty(), "login 应返回非空 token");
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应已创建");
assert_eq!(ts.login_id, "1001");
}
#[test]
fn test_require_mfa_default_false() {
let params = LoginParams::default();
assert!(
!params.require_mfa,
"LoginParams::default().require_mfa 应为 false"
);
}
}
#[cfg(feature = "three-tier-cache")]
mod three_tier_cache_integration {
use super::*;
use crate::cache::UserCacheService;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::with_current_token;
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
struct CountingDao {
store: Mutex<HashMap<String, (String, Option<Instant>)>>,
delete_count: AtomicU32,
delete_keys: Mutex<Vec<String>>,
}
impl CountingDao {
fn new() -> Self {
Self {
store: Mutex::new(HashMap::new()),
delete_count: AtomicU32::new(0),
delete_keys: Mutex::new(Vec::new()),
}
}
fn delete_count(&self) -> u32 {
self.delete_count.load(Ordering::SeqCst)
}
fn delete_keys(&self) -> Vec<String> {
self.delete_keys.lock().clone()
}
fn insert_direct(&self, key: &str, value: &str) {
self.store
.lock()
.insert(key.to_string(), (value.to_string(), None));
}
}
#[async_trait]
impl GarrisonDao for CountingDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
let mut store = self.store.lock();
match store.get(key) {
Some((value, expire_at)) => {
if let Some(deadline) = expire_at {
if Instant::now() >= *deadline {
store.remove(key);
return Ok(None);
}
}
Ok(Some(value.clone()))
},
None => Ok(None),
}
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
let expire_at = if ttl_seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(ttl_seconds))
};
self.store
.lock()
.insert(key.to_string(), (value.to_string(), expire_at));
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let mut store = self.store.lock();
match store.get_mut(key) {
Some((existing, _)) => {
*existing = value.to_string();
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
let mut store = self.store.lock();
match store.get_mut(key) {
Some((_, expire_at)) => {
*expire_at = if seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(seconds))
};
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.delete_count.fetch_add(1, Ordering::SeqCst);
self.delete_keys.lock().push(key.to_string());
self.store.lock().remove(key);
Ok(())
}
crate::atomic_test_fallback!();
}
struct MockFirewall;
#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
async fn check_permission(
&self,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_any(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_all(
&self,
_login_id: &str,
_roles: &[&str],
) -> GarrisonResult<bool> {
Ok(true)
}
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!["admin".to_string()])
}
async fn get_user_info(&self, _login_id: &str) -> GarrisonResult<Option<String>> {
Ok(Some("user-info".to_string()))
}
async fn check_permission_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_permission: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
async fn check_role_in_tenant(
&self,
_tenant_id: i64,
_login_id: &str,
_role: &str,
) -> GarrisonResult<bool> {
Ok(true)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(
&self,
_login_id: &str,
_ctx: &crate::strategy::hooks::LoginContext,
) -> GarrisonResult<()> {
Ok(())
}
}
fn make_logic_with_cache(dao: Arc<CountingDao>) -> GarrisonLogicDefault {
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
let cache_service = Arc::new(
UserCacheService::new(
dao.clone() as Arc<dyn GarrisonDao>,
firewall.clone(),
30,
300,
)
.expect("UserCacheService::new 应成功"),
);
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_user_cache_service(cache_service)
}
#[tokio::test]
async fn logout_invalidates_user_cache() {
{
let d = CountingDao::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 dao = Arc::new(CountingDao::new());
let logic = Arc::new(make_logic_with_cache(dao.clone()));
let token = logic
.login("1001", &LoginParams::default())
.await
.expect("login 应成功");
dao.insert_direct("perm:cache:1001", r#"["user:read"]"#);
dao.insert_direct("role:cache:1001", r#"["admin"]"#);
dao.insert_direct("user:cache:1001", r#""user-info""#);
assert_eq!(dao.delete_count(), 0, "预填充后 delete 次数应为 0");
with_current_token(token, async {
logic.logout().await.expect("logout 应成功");
})
.await;
let deleted = dao.delete_keys();
assert!(
deleted.contains(&"perm:cache:1001".to_string()),
"logout 应删除 perm:cache:1001,实际删除: {:?}",
deleted
);
assert!(
deleted.contains(&"role:cache:1001".to_string()),
"logout 应删除 role:cache:1001"
);
assert!(
deleted.contains(&"user:cache:1001".to_string()),
"logout 应删除 user:cache:1001"
);
}
#[tokio::test]
async fn logout_by_login_id_invalidates_user_cache() {
let dao = Arc::new(CountingDao::new());
let logic = Arc::new(make_logic_with_cache(dao.clone()));
let _token = logic
.login("2002", &LoginParams::default())
.await
.expect("login 应成功");
dao.insert_direct("perm:cache:2002", r#"["user:read"]"#);
dao.insert_direct("role:cache:2002", r#"["admin"]"#);
dao.insert_direct("user:cache:2002", r#""user-info""#);
logic
.logout_by_login_id("2002")
.await
.expect("logout_by_login_id 应成功");
let deleted = dao.delete_keys();
assert!(deleted.contains(&"perm:cache:2002".to_string()));
assert!(deleted.contains(&"role:cache:2002".to_string()));
assert!(deleted.contains(&"user:cache:2002".to_string()));
}
#[tokio::test]
async fn logout_without_cache_service_succeeds() {
let dao: Arc<dyn GarrisonDao> = Arc::new(CountingDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
let logic = Arc::new(GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(dao)),
));
let token = logic
.login("3003", &LoginParams::default())
.await
.expect("login 应成功");
with_current_token(token, async {
logic.logout().await.expect("logout 应成功(无缓存服务)");
})
.await;
}
}
mod session_coverage_tests {
use super::*;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::mock::{MockDao, MockFirewall};
use crate::stp::with_current_token;
use crate::strategy::GarrisonPermissionStrategy;
use std::sync::Arc;
fn make_logic(throw_on_not_login: bool) -> GarrisonLogicDefault {
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.throw_on_not_login = throw_on_not_login;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
}
#[cfg(feature = "protocol-jwt")]
fn make_jwt_logic(
throw_on_not_login: bool,
jwt_mode: JwtMode,
secret: &str,
) -> GarrisonLogicDefault {
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.throw_on_not_login = throw_on_not_login;
config.enable_jwt_revocation = true;
config.token_style = "jwt".to_string();
config.jwt_secret = secret.to_string().into();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_jwt_mode(jwt_mode)
}
#[tokio::test]
async fn check_login_no_token_throws_when_configured() {
let logic = make_logic(true);
let result = logic.check_login().await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg == "stp-not-login::"),
"无 token + throw_on_not_login=true 应返回 Err(Session(\"stp-not-login::\")),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_login_no_token_returns_false_when_not_throwing() {
let logic = make_logic(false);
let result = logic.check_login().await;
assert!(
result.is_ok(),
"无 token + throw_on_not_login=false 应返回 Ok,实际: {:?}",
result
);
assert!(
!result.unwrap(),
"无 token + throw_on_not_login=false 应返回 false"
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn check_login_stateless_valid_jwt_returns_true() {
let secret = "coverage-secret-stateless-valid-32bytes!!";
let logic = make_jwt_logic(true, JwtMode::Stateless, secret);
let handler = crate::protocol::jwt::JwtHandler::new(secret);
let jwt_token = handler
.sign("stateless-user-001", 3600)
.expect("JWT 签发应成功");
let result = with_current_token(jwt_token, async { logic.check_login().await }).await;
assert!(
result.is_ok(),
"Stateless + 有效 JWT 应返回 Ok,实际: {:?}",
result
);
assert!(result.unwrap(), "Stateless + 有效 JWT 应返回 true");
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn check_login_stateless_invalid_token_returns_error() {
let logic = make_jwt_logic(
true,
JwtMode::Stateless,
"coverage-secret-stateless-0123456789",
);
let result = with_current_token("invalid.jwt.token".to_string(), async {
logic.check_login().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidToken(_))),
"Stateless + 无效 JWT 应返回 Err(InvalidToken),实际: {:?}",
result
);
}
#[cfg(feature = "protocol-jwt")]
#[serial]
#[tokio::test]
async fn check_login_stateless_wrong_token_style_returns_config_error() {
let logic = make_logic(false).with_jwt_mode(JwtMode::Stateless);
let result =
with_current_token("any-token".to_string(), async { logic.check_login().await })
.await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("stp-stateless-requires")),
"Stateless + token_style=uuid 应返回 Err(Config(...Stateless...)),实际: {:?}",
result
);
}
#[cfg(feature = "protocol-jwt")]
#[serial]
#[tokio::test]
async fn check_login_stateless_without_revocation_rejected() {
let mut config = GarrisonConfig::default_config();
config.token_style = "jwt".to_string();
config.enable_jwt_revocation = false;
config.allow_stateless_jwt_no_revocation = false;
config.throw_on_not_login = false;
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let firewall = 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_jwt_mode(JwtMode::Stateless);
let result = with_current_token("any.token.here".to_string(), async {
logic.check_login().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("stp-stateless-jwt-requires-revocation")),
"stateless JWT 未启用撤销应 fail-closed 返回 Config 错误,实际: {:?}",
result
);
}
#[cfg(feature = "protocol-jwt")]
#[serial]
#[tokio::test]
async fn check_login_stateless_risk_accept_flag_allows() {
let secret = "coverage-secret-stateless-0123456789";
let mut config = GarrisonConfig::default_config();
config.token_style = "jwt".to_string();
config.enable_jwt_revocation = false;
config.allow_stateless_jwt_no_revocation = true;
config.throw_on_not_login = false;
config.jwt_secret = secret.to_string().into();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let firewall = 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_jwt_mode(JwtMode::Stateless);
let handler = crate::protocol::jwt::JwtHandler::new(secret);
let jwt_token = handler.sign("risk-accept-user", 3600).unwrap();
let result = with_current_token(jwt_token, async { logic.check_login().await }).await;
assert!(
matches!(result, Ok(true)),
"显式风险接受开关开启时 stateless JWT 应放行(有效 JWT),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_login_simple_invalid_token_returns_false() {
let logic = make_logic(false).with_jwt_mode(JwtMode::Simple);
let result = with_current_token("nonexistent-token".to_string(), async {
logic.check_login().await
})
.await;
assert!(
result.is_ok(),
"Simple + 无效 token + throw=false 应返回 Ok,实际: {:?}",
result
);
assert!(
!result.unwrap(),
"Simple + 无效 token + throw=false 应返回 false"
);
}
#[tokio::test]
async fn check_login_mixin_invalid_token_throws() {
let logic = make_logic(true).with_jwt_mode(JwtMode::Mixin);
let result = with_current_token("nonexistent-token".to_string(), async {
logic.check_login().await
})
.await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg == "stp-not-login::"),
"Mixin + 无效 token + throw=true 应返回 Err(Session(\"stp-not-login::\")),实际: {:?}",
result
);
}
#[tokio::test]
async fn check_and_renew_threshold_zero_returns_none() {
let logic = make_logic(false);
let result = logic.check_and_renew("any-token").await;
assert!(
result.is_ok(),
"threshold <= 0 应返回 Ok,实际: {:?}",
result
);
assert!(
result.unwrap().is_none(),
"threshold <= 0 应返回 None(未启用续签)"
);
}
#[tokio::test]
async fn check_and_renew_ttl_sufficient_returns_none() {
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.throw_on_not_login = false;
config.token_style = "uuid".to_string();
config.auto_renewal_threshold = 50;
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 token = logic
.login("renew-user-001", &LoginParams::default())
.await
.unwrap();
let result = logic.check_and_renew(&token).await;
assert!(result.is_ok(), "TTL 充足应返回 Ok,实际: {:?}", result);
assert!(result.unwrap().is_none(), "TTL 充足应返回 None(无需续签)");
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn check_and_renew_no_auth_logic_returns_config_error() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 5, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
config.auto_renewal_threshold = 95;
config.timeout = 5;
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("renew-user-002", &LoginParams::default())
.await
.unwrap();
tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
let result = logic.check_and_renew(&token).await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("stp-auto-renewal-no-auth-logic")),
"TTL 低 + 无 auth_logic 应返回 Err(Config(...auth_logic...)),实际: {:?}",
result
);
}
#[tokio::test]
async fn generate_token_unknown_style_returns_config_error() {
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.throw_on_not_login = false;
config.token_style = "unknown-style".to_string();
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 result = logic.login("test-user", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("stp-unknown-token-style")),
"未知 token_style 应返回 Err(Config(...stp-unknown-token-style...)),实际: {:?}",
result
);
}
#[tokio::test]
async fn refresh_access_token_returns_not_implemented() {
let logic = make_logic(false);
let result = logic.refresh_access_token("any-refresh-token").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"未注入 RefreshTokenRotation 应返回 Err(NotImplemented),实际: {:?}",
result
);
}
#[tokio::test]
async fn revoke_all_sessions_returns_zero_for_no_tokens() {
let logic = make_logic(false);
let count = logic.revoke_all_sessions("no-sessions-user").await.unwrap();
assert_eq!(count, 0, "无 token 时应返回 0,实际: {}", count);
}
#[tokio::test]
async fn revoke_all_sessions_revokes_all_tokens() {
let logic = make_logic(false);
let t1 = logic
.login("revoke-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("revoke-user-001", &LoginParams::default())
.await
.unwrap();
let t3 = logic
.login("revoke-user-001", &LoginParams::default())
.await
.unwrap();
let count = logic.revoke_all_sessions("revoke-user-001").await.unwrap();
assert_eq!(count, 3, "应吊销 3 个会话,实际: {}", 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_token_session(&t3)
.await
.unwrap()
.is_none(),
"t3 应被吊销"
);
}
#[tokio::test]
async fn get_active_sessions_filters_invalid_tokens() {
let logic = make_logic(false);
let t1 = logic
.login("active-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("active-user-001", &LoginParams::default())
.await
.unwrap();
logic.session.logout(&t1).await.unwrap();
let active = logic.get_active_sessions("active-user-001").await.unwrap();
assert_eq!(
active.len(),
1,
"应只有 1 个活跃会话(t2),实际: {}",
active.len()
);
assert_eq!(active[0], t2, "活跃会话应为 t2,实际: {:?}", active);
}
#[tokio::test]
async fn get_login_id_no_current_token_returns_none() {
let logic = make_logic(false);
let result = logic.get_login_id().await;
assert!(
result.is_ok(),
"无 current_token 应返回 Ok,实际: {:?}",
result
);
assert!(result.unwrap().is_none(), "无 current_token 应返回 None");
}
#[tokio::test]
async fn login_with_is_share_reuses_existing_token() {
let mut logic = make_logic(false);
Arc::make_mut(&mut logic.config).is_share = true;
let t1 = logic
.login("share-valid-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("share-valid-001", &LoginParams::default())
.await
.unwrap();
assert_eq!(t1, t2, "is_share=true 应复用现有有效 token");
}
#[tokio::test]
async fn login_with_is_share_creates_new_when_existing_invalid() {
let mut logic = make_logic(false);
Arc::make_mut(&mut logic.config).is_share = true;
let t1 = logic
.login("share-invalid-001", &LoginParams::default())
.await
.unwrap();
logic.session.logout(&t1).await.unwrap();
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none(),
"t1 应已失效"
);
let t2 = logic
.login("share-invalid-001", &LoginParams::default())
.await
.unwrap();
assert_ne!(t1, t2, "is_share=true 但旧 token 失效时应创建新 token");
assert!(
logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_some(),
"新 token 应有对应 session"
);
}
#[tokio::test]
async fn login_new_device_mode_allows_first_login() {
let mut logic = make_logic(false);
Arc::make_mut(&mut logic.config).is_concurrent = false;
Arc::make_mut(&mut logic.config).replaced_login_exit_mode =
ReplacedLoginExitMode::NewDevice;
let token = logic
.login("new-device-first-001", &LoginParams::default())
.await;
assert!(
token.is_ok(),
"NewDevice 模式 + 无旧会话应允许登录,实际: {:?}",
token
);
assert!(!token.unwrap().is_empty(), "应返回非空 token");
}
#[cfg(feature = "listener")]
mod listener_tests {
use super::*;
use crate::config::OverflowLogoutMode;
use crate::listener::{GarrisonEvent, GarrisonListener, GarrisonListenerManager};
use crate::stp::{Clock, MockClock};
use parking_lot::Mutex;
struct RecordingListener {
events: Mutex<Vec<GarrisonEvent>>,
}
impl RecordingListener {
fn new() -> Self {
Self {
events: Mutex::new(Vec::new()),
}
}
fn captured(&self) -> Vec<GarrisonEvent> {
self.events.lock().clone()
}
}
#[async_trait]
impl GarrisonListener for RecordingListener {
async fn on_event(
&self,
event: &GarrisonEvent,
) -> crate::error::GarrisonResult<()> {
self.events.lock().push(event.clone());
Ok(())
}
}
fn make_logic_with_listener(
throw_on_not_login: bool,
) -> (GarrisonLogicDefault, Arc<RecordingListener>) {
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.throw_on_not_login = throw_on_not_login;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_listener_manager(lm);
(logic, recorder)
}
#[tokio::test]
async fn logout_broadcasts_logout_event() {
let (logic, recorder) = make_logic_with_listener(false);
let token = logic
.login("logout-user-001", &LoginParams::default())
.await
.unwrap();
let result =
with_current_token(token.clone(), async { logic.logout().await }).await;
assert!(result.is_ok(), "logout 应返回 Ok,实际: {:?}", result);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::Logout {
login_id,
token: t,
..
} if login_id == "logout-user-001"
&& *t == crate::listener::mask_token_for_event(&token)
)),
"应广播 Logout 事件 (login_id=logout-user-001, token 掩码形式),实际事件: {:?}",
events
);
}
#[tokio::test]
async fn kickout_broadcasts_kickout_event() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let (logic, recorder) = make_logic_with_listener(false);
logic
.login("kickout-user-001", &LoginParams::default())
.await
.unwrap();
let result = logic.kickout("kickout-user-001").await;
assert!(result.is_ok(), "kickout 应返回 Ok,实际: {:?}", result);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::Kickout {
login_id,
reason,
..
} if login_id == "kickout-user-001" && reason == "管理员强制下线"
)),
"应广播 Kickout 事件 (login_id=kickout-user-001),实际事件: {:?}",
events
);
}
#[tokio::test]
async fn revoke_token_broadcasts_revoke_event() {
let (logic, recorder) = make_logic_with_listener(false);
let token = logic
.login("revoke-user-001", &LoginParams::default())
.await
.unwrap();
let result = logic.revoke_token(&token).await;
assert!(result.is_ok(), "revoke_token 应返回 Ok,实际: {:?}", result);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::RevokeToken { token: t, .. } if t == &token
)),
"应广播 RevokeToken 事件 (token={}),实际事件: {:?}",
token,
events
);
}
#[tokio::test]
async fn enforce_max_login_count_zero_is_noop() {
let logic = make_logic(false);
let token = logic
.login("max-user-001", &LoginParams::default())
.await
.unwrap();
let result = logic.enforce_max_login_count("max-user-001", 0).await;
assert!(result.is_ok(), "max=0 应返回 Ok,实际: {:?}", result);
assert!(
logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_some(),
"max=0 时 session 应仍然存在"
);
}
#[tokio::test]
async fn enforce_max_login_count_evicts_oldest_with_logout_mode() {
let (logic, recorder) = make_logic_with_listener(false);
let t1 = logic
.login("max-logout-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("max-logout-001", &LoginParams::default())
.await
.unwrap();
let _t3 = logic
.login("max-logout-001", &LoginParams::default())
.await
.unwrap();
let result = logic.enforce_max_login_count("max-logout-001", 1).await;
assert!(result.is_ok(), "enforce 应返回 Ok,实际: {:?}", result);
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none(),
"最旧 token 应已被踢出"
);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::Logout { login_id, token, .. } if login_id == "max-logout-001"
&& *token == crate::listener::mask_token_for_event(&t1)
)),
"应广播 Logout 事件 (最旧 token 被踢出, 掩码形式),实际事件: {:?}",
events
);
}
#[tokio::test]
async fn enforce_max_login_count_evicts_oldest_with_kickout_mode() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let (mut logic, recorder) = make_logic_with_listener(false);
Arc::make_mut(&mut logic.config).overflow_logout_mode = OverflowLogoutMode::Kickout;
let t1 = logic
.login("max-kickout-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("max-kickout-001", &LoginParams::default())
.await
.unwrap();
let result = logic.enforce_max_login_count("max-kickout-001", 1).await;
assert!(result.is_ok(), "enforce 应返回 Ok,实际: {:?}", result);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::Kickout {
login_id,
token,
reason,
..
} if login_id == "max-kickout-001"
&& *token == crate::listener::mask_token_for_event(&t1)
&& reason == "超过最大登录数限制"
)),
"应广播 Kickout 事件 (reason=超过最大登录数限制, token 掩码形式),实际事件: {:?}",
events
);
}
#[tokio::test]
async fn enforce_max_login_count_evicts_oldest_with_replaced_mode() {
let (mut logic, recorder) = make_logic_with_listener(false);
Arc::make_mut(&mut logic.config).overflow_logout_mode =
OverflowLogoutMode::Replaced;
let t1 = logic
.login("max-replaced-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("max-replaced-001", &LoginParams::default())
.await
.unwrap();
let result = logic.enforce_max_login_count("max-replaced-001", 1).await;
assert!(result.is_ok(), "enforce 应返回 Ok,实际: {:?}", result);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::Replaced {
login_id,
token,
reason,
..
} if login_id == "max-replaced-001"
&& *token == crate::listener::mask_token_for_event(&t1)
)),
"应广播 Replaced 事件 (token 掩码形式),实际事件: {:?}",
events
);
}
#[tokio::test]
async fn enforce_max_login_count_gate_reads_dao_not_local_map() {
let logic = make_logic(false);
let t1 = logic
.login("gate-user-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("gate-user-001", &LoginParams::default())
.await
.unwrap();
let t3 = logic
.login("gate-user-001", &LoginParams::default())
.await
.unwrap();
logic.session.remove_login_token("gate-user-001", &t1);
assert_eq!(
logic.session.get_tokens_by_login_id("gate-user-001").len(),
2,
"前置条件:本地 map 应只剩 2 个 token"
);
logic
.enforce_max_login_count("gate-user-001", 2)
.await
.unwrap();
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none(),
"DAO 中超限的最旧会话应被踢出(闸门不得读本地 map)"
);
assert!(
logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_some()
&& logic
.session
.get_token_session(&t3)
.await
.unwrap()
.is_some(),
"未超限的新会话应保留"
);
}
#[tokio::test]
async fn login_id_cache_hit_and_logout_invalidation() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountingGetDao {
inner: Arc<MockDao>,
get_calls: AtomicUsize,
}
#[async_trait]
impl GarrisonDao for CountingGetDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
self.get_calls.fetch_add(1, Ordering::SeqCst);
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
}
crate::atomic_test_fallback!();
}
let inner = Arc::new(MockDao::new());
let counting = Arc::new(CountingGetDao {
inner,
get_calls: AtomicUsize::new(0),
});
let dao: Arc<dyn GarrisonDao> = counting.clone();
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
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)),
);
use crate::stp::session::SessionLogic as _;
let token = logic
.login("reuse-user-001", &LoginParams::default())
.await
.unwrap();
crate::stp::with_login_id_scope(async {
crate::stp::with_current_token(token.clone(), async {
assert!(logic.check_login().await.unwrap(), "check_login 应通过");
let reads_after_check = counting.get_calls.load(Ordering::SeqCst);
let login_id = logic.get_login_id().await.unwrap();
assert_eq!(login_id.as_deref(), Some("reuse-user-001"));
assert_eq!(
counting.get_calls.load(Ordering::SeqCst),
reads_after_check,
"缓存命中时 get_login_id 不应触发 DAO 读取"
);
logic.logout().await.unwrap();
let login_id_after_logout = logic.get_login_id().await.unwrap();
assert_eq!(
login_id_after_logout, None,
"登出后缓存应立即失效(回退 DAO 返回 None)"
);
})
.await;
})
.await;
}
#[tokio::test]
async fn login_id_fallback_without_cache_scope() {
use crate::stp::session::SessionLogic as _;
let (logic, _recorder) = make_logic_with_listener(false);
let token = logic
.login("fallback-user-001", &LoginParams::default())
.await
.unwrap();
crate::stp::with_current_token(token.clone(), async {
assert!(logic.check_login().await.unwrap());
let login_id = logic.get_login_id().await.unwrap();
assert_eq!(login_id.as_deref(), Some("fallback-user-001"));
})
.await;
}
#[cfg(feature = "secure-simple-token")]
#[tokio::test]
async fn login_by_token_creates_session_and_broadcasts_login() {
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.throw_on_not_login = false;
config.token_style = "simple".to_string();
const SESSION_SIMPLE_TEST_SECRET: &str =
"stp-session-simple-test-secret-0123456789";
config.jwt_secret = SESSION_SIMPLE_TEST_SECRET.to_string().into();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_listener_manager(lm);
use crate::core::token::Token;
let style = crate::core::token::SimpleTokenStyle::new(
SESSION_SIMPLE_TEST_SECRET.to_string(),
);
let external_token = style.generate("externaluser001", 3600).unwrap();
let result = logic.login_by_token(&external_token).await;
assert!(
result.is_ok(),
"login_by_token 应返回 Ok,实际: {:?}",
result
);
assert!(
logic
.session
.get_token_session(&external_token)
.await
.unwrap()
.is_some(),
"login_by_token 后应存在 Token-Session"
);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::Login {
login_id,
token,
..
} if login_id == "externaluser001" && token == &external_token
)),
"应广播 Login 事件 (login_id=externaluser001),实际事件: {:?}",
events
);
}
#[tokio::test]
async fn check_and_update_hover_evicts_on_timeout() {
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.throw_on_not_login = false;
config.token_style = "uuid".to_string();
config.session_hover_timeout = 1; let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let clock = Arc::new(MockClock::new(chrono::Utc::now()));
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_listener_manager(lm)
.with_clock(clock.clone() as Arc<dyn Clock>);
let token = logic
.login("hover-user-001", &LoginParams::default())
.await
.unwrap();
let now_millis = clock.now().timestamp_millis();
logic
.session
.update_last_active_at("hover-user-001", now_millis);
clock.advance(chrono::Duration::seconds(2));
let result =
with_current_token(token.clone(), async { logic.check_login().await }).await;
assert!(
result.is_ok(),
"悬停超时 + throw=false 时 check_login 应返回 Ok,实际: {:?}",
result
);
assert!(!result.unwrap(), "悬停超时后 check_login 应返回 false");
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::SessionTimeout {
login_id,
token: t,
..
} if login_id == "hover-user-001" && t == &token
)),
"应广播 SessionTimeout 事件,实际事件: {:?}",
events
);
}
#[tokio::test]
async fn check_and_update_hover_evicts_on_timeout_throws() {
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.throw_on_not_login = true;
config.token_style = "uuid".to_string();
config.session_hover_timeout = 1;
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let clock = Arc::new(MockClock::new(chrono::Utc::now()));
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
.with_clock(clock.clone() as Arc<dyn Clock>);
let token = logic
.login("hover-user-002", &LoginParams::default())
.await
.unwrap();
let now_millis = clock.now().timestamp_millis();
logic
.session
.update_last_active_at("hover-user-002", now_millis);
clock.advance(chrono::Duration::seconds(2));
let result = with_current_token(token, async { logic.check_login().await }).await;
assert!(
matches!(result, Err(GarrisonError::Session(ref msg)) if msg == "stp-session-timeout::"),
"悬停超时 + throw=true 应返回 Err(Session(\"会话悬停超时\")),实际: {:?}",
result
);
}
}
#[tokio::test]
async fn login_with_token_creates_session() {
let logic = make_logic(false);
logic
.login_with_token("lwt-user-001", "custom-token-001")
.await
.unwrap();
let ts = logic
.session
.get_token_session("custom-token-001")
.await
.unwrap()
.expect("login_with_token 后应存在 Token-Session");
assert_eq!(ts.login_id, "lwt-user-001");
}
#[tokio::test]
async fn login_with_token_enforces_max_login_count_evicts_oldest() {
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.max_login_count = 2;
config.is_concurrent = true;
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(),
)),
);
logic
.login_with_token("quota-user", "qt-token-001")
.await
.unwrap();
logic
.login_with_token("quota-user", "qt-token-002")
.await
.unwrap();
logic
.login_with_token("quota-user", "qt-token-003")
.await
.unwrap();
let oldest = logic
.session
.get_token_session("qt-token-001")
.await
.unwrap();
assert!(
oldest.is_none(),
"第 max_login_count+1 个会话应踢出最旧 token qt-token-001,实际: {:?}",
oldest
);
assert!(
logic
.session
.get_token_session("qt-token-002")
.await
.unwrap()
.is_some(),
"qt-token-002 应保留"
);
assert!(
logic
.session
.get_token_session("qt-token-003")
.await
.unwrap()
.is_some(),
"qt-token-003 应保留"
);
}
#[tokio::test]
async fn login_with_token_returns_error_when_token_already_associated() {
let logic = make_logic(false);
logic
.login_with_token("alice-001", "shared-token-T1")
.await
.expect("alice 首次登录应成功");
let result = logic
.login_with_token("attacker-002", "shared-token-T1")
.await;
assert!(
result.is_err(),
"token 已关联 alice 时,attacker 重复关联应返回 Err,避免 dual-mapping。实际: {:?}",
result
);
let ts = logic
.session
.get_token_session("shared-token-T1")
.await
.unwrap()
.expect("T1 的 Token-Session 应保留");
assert_eq!(
ts.login_id, "alice-001",
"token 应仍归属原 login_id(alice),未被 attacker 抢占"
);
}
#[tokio::test]
async fn a8_login_with_token_rejects_empty_login_id() {
let logic = make_logic(false);
let result = logic.login_with_token("", "valid-token-001").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"空 login_id 应返回 InvalidParam,实际: {:?}",
result
);
assert!(
logic
.session
.get_token_session("valid-token-001")
.await
.unwrap()
.is_none(),
"校验失败时不应创建会话"
);
}
#[tokio::test]
async fn a8_login_with_token_rejects_empty_token() {
let logic = make_logic(false);
let result = logic.login_with_token("user-001", "").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"空 token 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn a8_login_with_token_rejects_too_short_token() {
let logic = make_logic(false);
let result = logic.login_with_token("user-001", "short12").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"过短 token 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn a8_login_with_token_rejects_too_long_token() {
let logic = make_logic(false);
let long_token = "a".repeat(257);
let result = logic.login_with_token("user-001", &long_token).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"超长 token 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn a8_login_with_token_rejects_token_with_control_chars() {
let logic = make_logic(false);
let result = logic
.login_with_token("user-001", "valid-token\r\nX-Evil: 1")
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"含控制字符的 token 应返回 InvalidParam,实际: {:?}",
result
);
let result2 = logic.login_with_token("user-001", "valid\0token").await;
assert!(
matches!(result2, Err(GarrisonError::InvalidParam(_))),
"含 NUL 字节的 token 应返回 InvalidParam,实际: {:?}",
result2
);
}
#[tokio::test]
async fn a8_login_with_token_accepts_min_length_token() {
let logic = make_logic(false);
logic
.login_with_token("user-001", "12345678")
.await
.expect("8 字节 token 应通过校验");
let ts = logic
.session
.get_token_session("12345678")
.await
.unwrap()
.expect("8 字节 token 应已创建会话");
assert_eq!(ts.login_id, "user-001");
}
#[tokio::test]
async fn a8_login_with_token_accepts_max_length_token() {
let logic = make_logic(false);
let max_token = "a".repeat(256);
logic
.login_with_token("user-001", &max_token)
.await
.expect("256 字节 token 应通过校验");
let ts = logic
.session
.get_token_session(&max_token)
.await
.unwrap()
.expect("256 字节 token 应已创建会话");
assert_eq!(ts.login_id, "user-001");
}
#[tokio::test]
async fn kickout_by_token_destroys_session() {
let logic = make_logic(false);
let token = logic
.login("kbt-user-001", &LoginParams::default())
.await
.unwrap();
assert!(
logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_some(),
"login 后应存在 session"
);
logic.kickout_by_token(&token).await.unwrap();
assert!(
logic
.session
.get_token_session(&token)
.await
.unwrap()
.is_none(),
"kickout_by_token 后 session 应被销毁"
);
}
#[tokio::test]
async fn logout_without_token_returns_ok() {
let logic = make_logic(false);
let result = logic.logout().await;
assert!(
result.is_ok(),
"无 current_token 时 logout 应幂等返回 Ok,实际: {:?}",
result
);
}
#[tokio::test]
async fn generate_token_random_64_style() {
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.throw_on_not_login = false;
config.token_style = "random_64".to_string();
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("r64-user-001", &LoginParams::default())
.await
.unwrap();
assert_eq!(
token.len(),
64,
"random_64 token 应为 64 字符,实际: {} 字符",
token.len()
);
assert!(
token.chars().all(|c| c.is_ascii_hexdigit()),
"random_64 token 应全部为十六进制字符"
);
}
#[cfg(feature = "secure-simple-token")]
#[tokio::test]
async fn generate_token_simple_style_is_hmac_and_verifiable() {
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.throw_on_not_login = false;
config.token_style = "simple".to_string();
config.jwt_secret = "gen-simple-secret-aaaabbbbccccdddd0".to_string().into();
let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
let logic = GarrisonLogicDefault::new(
session,
Arc::new(config.clone()),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
);
let token = logic
.login("simple-user-001", &LoginParams::default())
.await
.unwrap();
assert!(token.contains('\x1f'), "simple token 应包含 \\x1f 分隔符");
assert!(token.contains('.'), "simple token 应包含 HMAC 分隔点");
use crate::core::token::Token;
let style =
crate::core::token::SimpleTokenStyle::new(config.jwt_secret.as_str().to_string());
let verified = style.verify(&token).unwrap();
assert_eq!(
verified,
Some("simple-user-001".to_string()),
"simple token 应能被同一 SimpleTokenStyle::verify 通过并解析出 login_id"
);
let token2 = logic
.login("simple-user-001", &LoginParams::default())
.await
.unwrap();
assert_eq!(
style.verify(&token2).unwrap(),
Some("simple-user-001".to_string()),
"AuthLogic 路径产出的 simple token 应同样可被 SimpleTokenStyle::verify 通过"
);
}
#[cfg(not(feature = "secure-simple-token"))]
#[serial]
#[tokio::test]
async fn generate_token_simple_style_requires_feature() {
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.throw_on_not_login = false;
config.token_style = "simple".to_string();
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 result = logic
.login("simple-user-001", &LoginParams::default())
.await;
assert!(
matches!(result, Err(GarrisonError::Config(_))),
"未启用 secure-simple-token 时 simple token 生成应 fail-closed 返回 Config 错误"
);
}
#[cfg(feature = "protocol-jwt")]
#[serial]
#[tokio::test]
async fn generate_token_jwt_style() {
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.throw_on_not_login = false;
config.token_style = "jwt".to_string();
config.jwt_secret = "gen-jwt-secret-aaaabbbbccccdddd0".to_string().into();
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("jwt-user-001", &LoginParams::default())
.await
.unwrap();
assert_eq!(
token.matches('.').count(),
2,
"JWT token 应包含 2 个点,实际: {} 个",
token.matches('.').count()
);
}
#[serial]
#[tokio::test]
async fn check_login_mixin_valid_token_returns_true() {
let logic = make_logic(false).with_jwt_mode(JwtMode::Mixin);
let token = logic
.login("mixin-user-001", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token, async { logic.check_login().await }).await;
assert!(
result.is_ok(),
"Mixin + 有效 token 应返回 Ok,实际: {:?}",
result
);
assert!(result.unwrap(), "Mixin + 有效 token 应返回 true");
}
#[tokio::test]
async fn check_login_simple_valid_token_returns_true() {
let logic = make_logic(false).with_jwt_mode(JwtMode::Simple);
let token = logic
.login("simple-check-user-001", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token, async { logic.check_login().await }).await;
assert!(
result.is_ok(),
"Simple + 有效 token 应返回 Ok,实际: {:?}",
result
);
assert!(result.unwrap(), "Simple + 有效 token 应返回 true");
}
#[cfg(all(feature = "protocol-jwt", feature = "db-sqlite"))]
#[tokio::test]
async fn refresh_access_token_with_jwt_no_rotation_returns_not_implemented() {
let logic = make_logic(false);
let result = logic.refresh_access_token("any-refresh").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("stp-refresh-access-token-no-rotation")),
"未注入 RefreshTokenRotation 应返回 NotImplemented 包含 'stp-refresh-access-token-no-rotation',实际: {:?}",
result
);
}
#[tokio::test]
async fn login_new_device_mode_rejects_when_existing_session() {
let mut logic = make_logic(false);
Arc::make_mut(&mut logic.config).is_concurrent = false;
Arc::make_mut(&mut logic.config).replaced_login_exit_mode =
ReplacedLoginExitMode::NewDevice;
let _t1 = logic
.login("new-device-reject-001", &LoginParams::default())
.await
.unwrap();
let result = logic
.login("new-device-reject-001", &LoginParams::default())
.await;
assert!(
matches!(result, Err(GarrisonError::NotLogin(ref msg)) if msg.contains("stp-new-device-login-rejected")),
"NewDevice 模式 + 已有旧会话应返回 NotLogin 包含 'NewDevice',实际: {:?}",
result
);
}
#[tokio::test]
async fn login_old_device_mode_kickouts_old_session() {
let mut logic = make_logic(false);
Arc::make_mut(&mut logic.config).is_concurrent = false;
Arc::make_mut(&mut logic.config).replaced_login_exit_mode =
ReplacedLoginExitMode::OldDevice;
let t1 = logic
.login("old-device-001", &LoginParams::default())
.await
.unwrap();
let t2 = logic
.login("old-device-001", &LoginParams::default())
.await
.unwrap();
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_none(),
"OldDevice 模式下旧 token 应被踢出"
);
assert!(
logic
.session
.get_token_session(&t2)
.await
.unwrap()
.is_some(),
"新 token 应有效"
);
assert_ne!(t1, t2, "新旧 token 应不同");
}
#[tokio::test]
async fn enforce_max_login_count_within_limit_no_op() {
let logic = make_logic(false);
let t1 = logic
.login("max-nop-001", &LoginParams::default())
.await
.unwrap();
let _t2 = logic
.login("max-nop-001", &LoginParams::default())
.await
.unwrap();
logic
.enforce_max_login_count("max-nop-001", 5)
.await
.unwrap();
assert!(
logic
.session
.get_token_session(&t1)
.await
.unwrap()
.is_some(),
"tokens <= max 时 t1 应仍存在"
);
}
#[tokio::test]
async fn get_login_id_token_without_session_returns_none() {
let logic = make_logic(false);
let result = with_current_token("nonexistent-token".to_string(), async {
logic.get_login_id().await
})
.await;
assert!(
result.is_ok(),
"token 无对应 session 时应返回 Ok,实际: {:?}",
result
);
assert!(
result.unwrap().is_none(),
"token 无对应 session 时应返回 None"
);
}
}
#[cfg(feature = "protocol-jwt")]
mod jwt_revocation_tests {
use super::*;
use crate::dao::GarrisonDao;
use crate::session::GarrisonSession;
use crate::stp::mock::{MockDao, MockFirewall};
use crate::stp::with_current_token;
use crate::strategy::GarrisonPermissionStrategy;
use std::sync::Arc;
fn make_jwt_revocation_logic(
enable_revocation: bool,
) -> (GarrisonLogicDefault, Arc<MockDao>) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "jwt".to_string();
config.jwt_secret = "jwt-revocation-test-secret-32bytes!".to_string().into();
config.enable_jwt_revocation = enable_revocation;
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_jwt_mode(JwtMode::Stateless);
(logic, dao)
}
#[serial]
#[tokio::test]
async fn logout_writes_jti_to_blacklist() {
let (logic, dao) = make_jwt_revocation_logic(true);
let handler =
crate::protocol::jwt::JwtHandler::new("jwt-revocation-test-secret-32bytes!");
let token = logic
.login("user-1", &LoginParams::default())
.await
.unwrap();
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
let jti = claims.jti.expect("JWT 应包含 jti");
with_current_token(token, async {
logic.logout().await.expect("logout 应成功");
})
.await;
let key = format!("jwt:blacklist:{}", jti);
let value = dao.get(&key).await.unwrap();
assert!(value.is_some(), "logout 后 jti 应被写入黑名单");
assert_eq!(value.unwrap(), "1");
}
#[serial]
#[tokio::test]
async fn logout_by_login_id_writes_all_jtis_to_blacklist() {
let (logic, dao) = make_jwt_revocation_logic(true);
let handler =
crate::protocol::jwt::JwtHandler::new("jwt-revocation-test-secret-32bytes!");
let token1 = logic
.login("user-bl", &LoginParams::default())
.await
.unwrap();
let token2 = logic
.login("user-bl", &LoginParams::default())
.await
.unwrap();
let jti1 = handler
.verify(&token1)
.unwrap()
.jti
.expect("JWT 应包含 jti");
let jti2 = handler
.verify(&token2)
.unwrap()
.jti
.expect("JWT 应包含 jti");
logic
.logout_by_login_id("user-bl")
.await
.expect("logout_by_login_id 应成功");
for (label, jti) in [("token1", jti1), ("token2", jti2)] {
let key = format!("jwt:blacklist:{}", jti);
let value = dao.get(&key).await.unwrap();
assert!(value.is_some(), "{} 的 jti 应被写入黑名单", label);
}
}
#[serial]
#[tokio::test]
async fn revoke_token_writes_jti_to_blacklist() {
let (logic, dao) = make_jwt_revocation_logic(true);
let handler =
crate::protocol::jwt::JwtHandler::new("jwt-revocation-test-secret-32bytes!");
let token = logic
.login("user-rt", &LoginParams::default())
.await
.unwrap();
let jti = crate::protocol::jwt::tests::verify_ok(&handler, &token)
.jti
.expect("JWT 应包含 jti");
logic
.revoke_token(&token)
.await
.expect("revoke_token 应成功");
let key = format!("jwt:blacklist:{}", jti);
let value = dao.get(&key).await.unwrap();
assert!(value.is_some(), "revoke_token 后 jti 应被写入黑名单");
}
#[tokio::test]
async fn blacklist_write_retries_then_succeeds() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct FlakySetDao {
set_calls: AtomicUsize,
fail_first: usize,
}
#[async_trait]
impl GarrisonDao for FlakySetDao {
async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
async fn set(
&self,
_key: &str,
_value: &str,
_ttl_seconds: u64,
) -> GarrisonResult<()> {
let n = self.set_calls.fetch_add(1, Ordering::SeqCst) + 1;
if n <= self.fail_first {
Err(GarrisonError::Dao("flaky-set::transient".to_string()))
} else {
Ok(())
}
}
async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> GarrisonResult<()> {
Ok(())
}
crate::atomic_test_fallback!();
}
let flaky = Arc::new(FlakySetDao {
set_calls: AtomicUsize::new(0),
fail_first: 2,
});
let dao: Arc<dyn GarrisonDao> = flaky.clone();
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "jwt".to_string();
config.jwt_secret = "jwt-revocation-test-secret-32bytes!".to_string().into();
config.enable_jwt_revocation = true;
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)),
)
.with_jwt_mode(JwtMode::Stateless);
let handler =
crate::protocol::jwt::JwtHandler::new("jwt-revocation-test-secret-32bytes!");
let token = handler.sign("user-retry", 3600).unwrap();
logic.blacklist_jwt_jti(&token).await;
assert_eq!(
flaky.set_calls.load(Ordering::SeqCst),
3,
"前 2 次失败应重试,第 3 次成功(共 3 次调用)"
);
}
#[tokio::test]
async fn blacklist_write_bounded_retry_on_persistent_failure() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct AlwaysFailSetDao {
set_calls: AtomicUsize,
}
#[async_trait]
impl GarrisonDao for AlwaysFailSetDao {
async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
async fn set(
&self,
_key: &str,
_value: &str,
_ttl_seconds: u64,
) -> GarrisonResult<()> {
self.set_calls.fetch_add(1, Ordering::SeqCst);
Err(GarrisonError::Dao("flaky-set::persistent".to_string()))
}
async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> GarrisonResult<()> {
Ok(())
}
crate::atomic_test_fallback!();
}
let flaky = Arc::new(AlwaysFailSetDao {
set_calls: AtomicUsize::new(0),
});
let dao: Arc<dyn GarrisonDao> = flaky.clone();
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "jwt".to_string();
config.jwt_secret = "jwt-revocation-test-secret-32bytes!".to_string().into();
config.enable_jwt_revocation = true;
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)),
)
.with_jwt_mode(JwtMode::Stateless);
let handler =
crate::protocol::jwt::JwtHandler::new("jwt-revocation-test-secret-32bytes!");
let token = handler.sign("user-retry-persistent", 3600).unwrap();
logic.blacklist_jwt_jti(&token).await;
assert_eq!(
flaky.set_calls.load(Ordering::SeqCst),
3,
"持续失败时应恰好尝试 3 次(1 次初始 + 2 次重试)"
);
}
#[serial]
#[tokio::test]
async fn stateless_rejects_revoked_jwt() {
let (logic, _dao) = make_jwt_revocation_logic(true);
let token = logic
.login("user-2", &LoginParams::default())
.await
.unwrap();
with_current_token(token.clone(), async {
logic.logout().await.expect("logout 应成功");
})
.await;
let result = with_current_token(token, async { logic.check_login().await }).await;
assert!(
matches!(&result, Err(GarrisonError::TokenRevoked(_))),
"已撤销 JWT 应返回 TokenRevoked,实际: {:?}",
result
);
}
#[serial]
#[tokio::test]
async fn stateless_accepts_valid_jwt() {
let (logic, _dao) = make_jwt_revocation_logic(true);
let token = logic
.login("user-3", &LoginParams::default())
.await
.unwrap();
let result = with_current_token(token, async { logic.check_login().await }).await;
assert!(result.is_ok(), "有效 JWT 应返回 Ok,实际: {:?}", result);
assert!(result.unwrap(), "有效 JWT 应返回 true");
}
#[serial]
#[tokio::test]
async fn no_blacklist_when_revocation_disabled() {
let (logic, dao) = make_jwt_revocation_logic(false);
let handler =
crate::protocol::jwt::JwtHandler::new("jwt-revocation-test-secret-32bytes!");
let token = logic
.login("user-4", &LoginParams::default())
.await
.unwrap();
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
let jti = claims.jti.expect("JWT 应包含 jti");
with_current_token(token, async {
logic.logout().await.expect("logout 应成功");
})
.await;
let key = format!("jwt:blacklist:{}", jti);
let value = dao.get(&key).await.unwrap();
assert!(
value.is_none(),
"enable_jwt_revocation=false 时 logout 不应写入黑名单"
);
}
#[test]
fn jwt_blacklist_retry_delay_matches_legacy_schedule() {
use crate::stp::session::helpers::jwt_blacklist_retry_delay;
use std::time::Duration;
assert_eq!(
jwt_blacklist_retry_delay(1),
Duration::from_millis(100),
"第 1 次重试前应等 100ms"
);
assert_eq!(
jwt_blacklist_retry_delay(2),
Duration::from_millis(300),
"第 2 次重试前应等 300ms"
);
}
}
}
#[cfg(all(test, feature = "firewall-bruteforce"))]
mod firewall_tests {
use crate::config::GarrisonConfig;
use crate::dao::tests::MockDao;
use crate::error::GarrisonError;
use crate::manager::GarrisonManager;
use crate::stp::mock::MockInterface;
use crate::stp::{with_current_ip, with_current_token, GarrisonUtil, LoginParams};
use serial_test::serial;
async fn setup() {
GarrisonManager::reset_for_test();
let dao: std::sync::Arc<dyn crate::dao::GarrisonDao> = std::sync::Arc::new(MockDao::new());
let mut config = GarrisonConfig::default();
config.throw_on_not_login = false;
let config = std::sync::Arc::new(config);
let interface: std::sync::Arc<dyn crate::stp::GarrisonInterface> =
std::sync::Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao)
.config(config)
.interface(interface)
.build()
.await
.unwrap();
}
#[tokio::test]
#[serial]
async fn brute_force_blocks_ip_after_repeated_failed_check_login() {
setup().await;
let ip = "203.0.113.5".to_string();
let blocked = with_current_ip(ip.clone(), async {
with_current_token("bogus-token".to_string(), async {
let mut blocked = false;
for _ in 0..12 {
if let Err(GarrisonError::FirewallBlocked(_)) =
GarrisonUtil::check_login().await
{
blocked = true;
break;
}
}
blocked
})
.await
})
.await;
assert!(
blocked,
"重复认证失败应触发 IP 封禁(返回 FirewallBlocked)"
);
}
#[tokio::test]
#[serial]
async fn successful_login_resets_failure_count() {
setup().await;
let ip = "198.51.100.7".to_string();
with_current_ip(ip.clone(), async {
for _ in 0..3 {
with_current_token("bogus".to_string(), async {
let _ = GarrisonUtil::check_login().await;
})
.await;
}
let _ = GarrisonUtil::login("legit-user", &LoginParams::default()).await;
})
.await;
let blocked_immediately = with_current_ip(ip.clone(), async {
with_current_token("bogus2".to_string(), async {
let mut blocked = false;
if let Err(GarrisonError::FirewallBlocked(_)) = GarrisonUtil::check_login().await {
blocked = true;
}
blocked
})
.await
})
.await;
assert!(
!blocked_immediately,
"成功登录后失败计数应被清零,单次失败不应立即封禁"
);
}
#[tokio::test]
#[serial]
async fn builder_auto_wires_firewall_hook() {
setup().await;
let injected = crate::manager::GarrisonManager::logic()
.unwrap()
.firewall_hook_injected();
assert!(
injected,
"firewall feature 启用时 builder 应自动注入 firewall_hook(避免 dead-code)"
);
}
}
#[cfg(test)]
mod tenant_binding_tests {
use crate::config::GarrisonConfig;
use crate::context::tenant::{TenantContext, TenantSource, TENANT};
use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
use crate::session::GarrisonSession;
use crate::stp::mock::{MockDao, MockFirewall};
use crate::stp::session::SessionLogic;
use crate::stp::{with_current_token, GarrisonLogicDefault, LoginParams};
use std::sync::Arc;
fn tenant_ctx(tenant_id: i64) -> TenantContext {
TenantContext {
tenant_id,
resolved_from: TenantSource::Header,
}
}
fn make_logic() -> GarrisonLogicDefault {
make_logic_with(|_| {})
}
fn make_logic_with(configure: impl FnOnce(&mut GarrisonConfig)) -> GarrisonLogicDefault {
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.throw_on_not_login = false;
config.token_style = "uuid".to_string();
configure(&mut config);
let firewall: Arc<dyn crate::strategy::GarrisonPermissionStrategy> =
Arc::new(MockFirewall {
has_permission: true,
has_role: true,
});
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(dao)),
)
}
#[tokio::test]
async fn login_under_tenant_scope_binds_session_and_same_tenant_passes() {
let logic = make_logic();
let token = TENANT
.scope(tenant_ctx(0), async {
logic
.login("tb-user-1", &LoginParams::default())
.await
.unwrap()
})
.await;
let bound = logic
.session
.get(&token, crate::context::tenant::SESSION_TENANT_ATTR_KEY)
.await
.unwrap();
assert_eq!(bound.as_deref(), Some("0"), "登录租户上下文应绑定到会话");
let ok = with_current_token(token.clone(), async {
TENANT.scope(tenant_ctx(0), logic.check_login()).await
})
.await
.unwrap();
assert!(ok, "同租户 check_login 应放行(隔离锚点)");
}
#[tokio::test]
async fn check_login_cross_tenant_binding_rejected() {
let logic = make_logic();
let token = TENANT
.scope(tenant_ctx(0), async {
logic
.login("tb-user-2", &LoginParams::default())
.await
.unwrap()
})
.await;
let result = with_current_token(token, async {
TENANT.scope(tenant_ctx(1), logic.check_login()).await
})
.await;
match result {
Err(GarrisonError::Session(msg)) => {
assert!(
msg.contains("stp-check-login-tenant-mismatch"),
"应返回租户不匹配的显性拒绝,实际: {msg}"
);
},
other => panic!("跨租户 check_login 应被拒绝,实际: {:?}", other.map(|_| ())),
}
}
#[tokio::test]
async fn check_login_unbound_session_under_tenant_context_allowed() {
let logic = make_logic();
let token = logic
.login("tb-user-3", &LoginParams::default())
.await
.unwrap();
let bound = logic
.session
.get(&token, crate::context::tenant::SESSION_TENANT_ATTR_KEY)
.await
.unwrap();
assert!(bound.is_none(), "无租户上下文登录不应写绑定");
let ok = with_current_token(token, async {
TENANT.scope(tenant_ctx(0), logic.check_login()).await
})
.await
.unwrap();
assert!(ok, "无绑定会话在租户上下文内应放行(升级兼容对照)");
}
#[tokio::test]
async fn check_login_unbound_session_rejected_when_binding_required() {
let logic = make_logic_with(|c| c.require_session_tenant_binding = true);
let token = logic
.login("tb-user-5", &LoginParams::default())
.await
.unwrap();
assert!(
logic
.session
.get(&token, crate::context::tenant::SESSION_TENANT_ATTR_KEY)
.await
.unwrap()
.is_none(),
"前置:无租户上下文登录应不写绑定"
);
let result = with_current_token(token, async {
TENANT.scope(tenant_ctx(0), logic.check_login()).await
})
.await;
match result {
Err(GarrisonError::Session(msg)) => assert!(
msg.contains("stp-check-login-session-tenant-unbound"),
"应为会话侧未绑定的显性报错,实际: {msg}"
),
other => panic!("严格档下无绑定会话不得放行,实际: {:?}", other.map(|_| ())),
}
let relaxed = make_logic();
let relaxed_token = relaxed
.login("tb-user-6", &LoginParams::default())
.await
.unwrap();
let ok = with_current_token(relaxed_token, async {
TENANT.scope(tenant_ctx(0), relaxed.check_login()).await
})
.await
.unwrap();
assert!(ok, "非严格档(默认)无绑定会话应继续放行");
}
#[tokio::test]
async fn check_login_without_tenant_context_unchanged() {
let logic = make_logic();
let token = TENANT
.scope(tenant_ctx(0), async {
logic
.login("tb-user-4", &LoginParams::default())
.await
.unwrap()
})
.await;
let ok = with_current_token(token, logic.check_login()).await;
assert!(
ok.is_ok() && ok.unwrap(),
"无租户上下文 check_login 行为不变"
);
}
#[tokio::test]
async fn check_login_tenant_binding_reuses_snapshot_without_extra_dao_read() {
use crate::error::GarrisonResult;
use std::sync::atomic::{AtomicUsize, Ordering};
struct GetCountingDao {
inner: MockDao,
get_calls: AtomicUsize,
}
#[async_trait::async_trait]
impl GarrisonDao for GetCountingDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
self.get_calls.fetch_add(1, Ordering::SeqCst);
GarrisonDao::get(&self.inner, key).await
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
GarrisonDao::set(&self.inner, key, value, ttl_seconds).await
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
GarrisonDao::update(&self.inner, key, value).await
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
GarrisonDao::expire(&self.inner, key, seconds).await
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
GarrisonDao::delete(&self.inner, key).await
}
async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<std::time::Duration>> {
GarrisonDao::get_timeout(&self.inner, key).await
}
crate::atomic_test_fallback!();
}
let dao = Arc::new(GetCountingDao {
inner: MockDao::new(),
get_calls: AtomicUsize::new(0),
});
let dao_dyn: Arc<dyn GarrisonDao> = dao.clone();
let session = Arc::new(GarrisonSession::new(dao_dyn.clone(), 3600, 86400, 0));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
let firewall: Arc<dyn crate::strategy::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_dyn,
)),
);
let token = TENANT
.scope(tenant_ctx(0), async {
logic
.login("tb-count-1", &LoginParams::default())
.await
.unwrap()
})
.await;
let before = dao.get_calls.load(Ordering::SeqCst);
let ok = with_current_token(token, async {
TENANT.scope(tenant_ctx(0), logic.check_login()).await
})
.await
.unwrap();
let after = dao.get_calls.load(Ordering::SeqCst);
assert!(ok, "同租户 check_login 应放行");
assert_eq!(
after - before,
2,
"check_login 只应整读一次 TokenSession(is_valid_with_session 的 \
Token-Session + Account-Session 两次 get),租户绑定校验须复用快照,\
不得追加第二次整读,实际追加 {} 次",
after - before - 2
);
}
}
#[cfg(test)]
mod session_token_security_tests {
use crate::config::GarrisonConfig;
#[cfg(feature = "protocol-jwt")]
use crate::context::tenant::TENANT;
use crate::context::tenant::{TenantContext, TenantSource};
#[cfg(feature = "protocol-jwt")]
use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
#[cfg(feature = "protocol-jwt")]
use crate::session::token_key;
use crate::session::GarrisonSession;
use crate::stp::core::GarrisonCore;
use crate::stp::mock::{MockDao, MockFirewall};
use crate::stp::session::SessionLogic;
#[cfg(feature = "protocol-jwt")]
use crate::stp::{with_current_token, JwtMode};
use crate::stp::{GarrisonLogicDefault, LoginParams};
use crate::strategy::GarrisonPermissionStrategy;
use std::sync::Arc;
#[cfg_attr(not(feature = "protocol-jwt"), allow(dead_code))]
fn tenant_ctx(tenant_id: i64) -> TenantContext {
TenantContext {
tenant_id,
resolved_from: TenantSource::Header,
}
}
fn make_logic_custom(
mutate: impl FnOnce(&mut GarrisonConfig),
) -> (GarrisonLogicDefault, Arc<MockDao>) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 7_776_000));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "uuid".to_string();
mutate(&mut config);
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(),
)),
);
(logic, dao)
}
#[cfg(feature = "protocol-jwt")]
fn make_jwt_stateless_logic(
mutate: impl FnOnce(&mut GarrisonConfig),
) -> (GarrisonLogicDefault, Arc<MockDao>) {
let dao = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 7_776_000));
let mut config = GarrisonConfig::default_config();
config.throw_on_not_login = false;
config.token_style = "jwt".to_string();
config.jwt_secret = "session-token-security-test-32bytes".to_string().into();
config.enable_jwt_revocation = true;
mutate(&mut config);
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_jwt_mode(JwtMode::Stateless);
(logic, dao)
}
#[tokio::test]
async fn login_remember_me_ignored_when_config_disabled() {
let (logic, _dao) = make_logic_custom(|c| {
c.remember_me_enabled = false;
c.remember_me_timeout = 7_776_000;
});
let params = LoginParams {
remember_me: true,
..LoginParams::default()
};
let token = logic.login("sec-remember-1", ¶ms).await.unwrap();
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应存在");
assert!(
ts.effective_timeout.is_none(),
"remember_me_enabled=false 时 remember_me=true 不得写 effective_timeout,实际: {:?}",
ts.effective_timeout
);
}
#[tokio::test]
async fn login_remember_me_applies_when_config_enabled() {
let (logic, _dao) = make_logic_custom(|c| {
c.remember_me_enabled = true;
c.remember_me_timeout = 7_776_000;
});
let params = LoginParams {
remember_me: true,
..LoginParams::default()
};
let token = logic.login("sec-remember-2", ¶ms).await.unwrap();
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应存在");
assert_eq!(
ts.effective_timeout,
Some(7_776_000),
"remember_me_enabled=true 时应写 90 天 effective_timeout"
);
}
#[tokio::test]
async fn login_remember_me_false_stays_default_timeout() {
let (logic, _dao) = make_logic_custom(|c| {
c.remember_me_enabled = true;
});
let token = logic
.login("sec-remember-3", &LoginParams::default())
.await
.unwrap();
let ts = logic
.session
.get_token_session(&token)
.await
.unwrap()
.expect("会话应存在");
assert!(ts.effective_timeout.is_none());
}
#[tokio::test]
async fn login_seeds_primary_amr_by_default() {
let (logic, _dao) = make_logic_custom(|_| {});
assert!(logic.config().seed_primary_amr, "配置默认应为 true");
let token = logic
.login("sec-amr-1", &LoginParams::default())
.await
.unwrap();
let ts = logic
.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 login_skips_amr_seeding_when_disabled() {
let (logic, _dao) = make_logic_custom(|c| {
c.seed_primary_amr = false;
});
let token = logic
.login("sec-amr-2", &LoginParams::default())
.await
.unwrap();
let ts = logic
.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");
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn jwt_login_skips_amr_claims_when_seeding_disabled() {
let (logic, _dao) = make_jwt_stateless_logic(|c| {
c.seed_primary_amr = false;
});
let token = logic
.login("sec-amr-3", &LoginParams::default())
.await
.unwrap();
let handler = crate::protocol::jwt::JwtHandler::new("session-token-security-test-32bytes");
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
assert!(claims.amr.is_none(), "开关关闭时 JWT 不得携带 amr claim");
assert!(
claims.auth_time.is_none(),
"开关关闭时 JWT 不得携带 auth_time claim"
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn jwt_login_keeps_amr_claims_when_seeding_default() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = logic
.login("sec-amr-4", &LoginParams::default())
.await
.unwrap();
let handler = crate::protocol::jwt::JwtHandler::new("session-token-security-test-32bytes");
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
assert_eq!(claims.amr, Some(vec!["pwd".to_string()]));
assert!(claims.auth_time.is_some());
}
#[tokio::test]
async fn login_rejects_empty_login_id() {
let (logic, _dao) = make_logic_custom(|_| {});
let result = logic.login("", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-empty")),
"空 login_id 应拒绝,实际: {:?}",
result
);
}
#[tokio::test]
async fn login_rejects_whitespace_only_login_id() {
let (logic, _dao) = make_logic_custom(|_| {});
let result = logic.login(" ", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-whitespace")),
"纯空白 login_id 应拒绝,实际: {:?}",
result
);
}
#[tokio::test]
async fn login_rejects_unit_separator_login_id() {
let (logic, _dao) = make_logic_custom(|_| {});
let result = logic.login("\x1fadmin", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-sep")),
"含 \\x1f 的 login_id 应拒绝,实际: {:?}",
result
);
}
#[tokio::test]
async fn login_rejects_control_char_login_id() {
let (logic, _dao) = make_logic_custom(|_| {});
let result = logic.login("admin\nroot", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-control-char")),
"含控制字符的 login_id 应拒绝,实际: {:?}",
result
);
}
#[tokio::test]
async fn login_rejects_login_id_over_default_max_len() {
let (logic, _dao) = make_logic_custom(|_| {});
let long_id = "L".repeat(256);
let result = logic.login(&long_id, &LoginParams::default()).await;
match result {
Err(GarrisonError::InvalidParam(m)) => {
assert!(
m.contains("stp-login-id-too-long"),
"256 字节 login_id 应拒绝,实际: {m}"
);
assert!(!m.contains(&long_id), "错误信息不得回显超长输入内容");
},
other => panic!("256 字节 login_id 应拒绝,实际: {:?}", other.map(|_| ())),
}
}
#[tokio::test]
async fn login_accepts_login_id_at_default_max_len() {
let (logic, _dao) = make_logic_custom(|_| {});
let id = "L".repeat(255);
let result = logic.login(&id, &LoginParams::default()).await;
assert!(
result.is_ok(),
"255 字节 login_id 应通过,实际: {:?}",
result.err()
);
}
#[tokio::test]
async fn login_unlimited_when_max_len_zero() {
let (logic, _dao) = make_logic_custom(|c| {
c.login_id_max_len = 0;
});
let id = "L".repeat(2000);
let result = logic.login(&id, &LoginParams::default()).await;
assert!(
result.is_ok(),
"login_id_max_len=0 时不限长度,实际: {:?}",
result.err()
);
}
#[tokio::test]
async fn login_respects_custom_max_len() {
let (logic, _dao) = make_logic_custom(|c| {
c.login_id_max_len = 8;
});
let result = logic.login("123456789", &LoginParams::default()).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-too-long")),
"超出自定上限应拒绝,实际: {:?}",
result
);
}
#[tokio::test]
async fn login_with_token_rejects_invalid_login_id() {
let (logic, _dao) = make_logic_custom(|_| {});
let r1 = logic.login_with_token(" ", "token-abc-123").await;
assert!(
matches!(r1, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-whitespace")),
"login_with_token 空白 login_id 应拒绝,实际: {:?}",
r1
);
let long_id = "L".repeat(300);
let r2 = logic.login_with_token(&long_id, "token-abc-123").await;
assert!(
matches!(r2, Err(GarrisonError::InvalidParam(ref m)) if m.contains("stp-login-id-too-long")),
"login_with_token 超限 login_id 应拒绝,实际: {:?}",
r2
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn kickout_blacklist_races_with_login_are_closed() {
let (logic, dao) = make_jwt_stateless_logic(|_| {});
let logic = Arc::new(logic);
const ITERATIONS: usize = 200;
for i in 0..ITERATIONS {
let login_logic = Arc::clone(&logic);
let kick_logic = Arc::clone(&logic);
let login_task = tokio::spawn(async move {
login_logic
.login("race-victim", &LoginParams::default())
.await
});
let kick_task = tokio::spawn(async move { kick_logic.kickout("race-victim").await });
let token = login_task.await.unwrap().expect("login 应成功");
kick_task.await.unwrap().expect("kickout 应成功");
let session_alive = dao.get(&token_key(&token)).await.unwrap().is_some();
let check =
with_current_token(token.clone(), async { logic.check_login().await }).await;
if !session_alive {
assert!(
!matches!(check, Ok(true)),
"迭代 {}:token session 已被踢出删除但 check_login 仍有效(TOCTOU 未闭合)",
i
);
}
}
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn stateless_revoked_token_rejected_in_same_tenant() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-tenant-1", &LoginParams::default()).await
})
.await
.unwrap();
TENANT
.scope(tenant_ctx(7), async { logic.kickout("sec-tenant-1").await })
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Err(GarrisonError::TokenRevoked(_))),
"同租户已吊销 token 应拒绝,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn stateless_revoked_token_rejected_under_switched_tenant_header() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-tenant-2", &LoginParams::default()).await
})
.await
.unwrap();
TENANT
.scope(tenant_ctx(7), async { logic.kickout("sec-tenant-2").await })
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(8), logic.check_login()).await
})
.await;
match check {
Err(GarrisonError::Session(msg)) => assert!(
msg.contains("stp-check-login-tenant-mismatch"),
"换租户头应命中租户绑定拒绝,实际: {msg}"
),
Err(GarrisonError::TokenRevoked(_)) => {}, other => panic!("换租户头不得逃逸吊销,实际: {:?}", other.map(|_| ())),
}
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn stateless_live_token_rejected_under_other_tenant_header() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-tenant-3", &LoginParams::default()).await
})
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(8), logic.check_login()).await
})
.await;
assert!(
matches!(check, Err(GarrisonError::Session(ref m)) if m.contains("stp-check-login-tenant-mismatch")),
"存活 token 换租户头应被绑定校验拒绝,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn stateless_unbound_token_allowed_under_tenant_context() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = logic
.login("sec-tenant-4", &LoginParams::default())
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Ok(true)),
"无绑定 token 应向后兼容放行,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn stateless_tenant_bound_token_unchanged_without_tenant_context() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-tenant-5", &LoginParams::default()).await
})
.await
.unwrap();
let check = with_current_token(token, logic.check_login()).await;
assert!(
matches!(check, Ok(true)),
"无租户上下文 check_login 行为不变,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn stateless_relogin_after_kickout_works_in_same_tenant() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
TENANT
.scope(tenant_ctx(7), async { logic.kickout("sec-tenant-6").await })
.await
.unwrap();
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-tenant-6", &LoginParams::default()).await
})
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Ok(true)),
"踢出后同租户新登录应可用,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn tenant_context_login_issues_claims_with_tid_roundtrip() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-tid-1", &LoginParams::default()).await
})
.await
.unwrap();
let handler = crate::protocol::jwt::JwtHandler::new("session-token-security-test-32bytes");
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
assert_eq!(claims.tid, Some(7), "租户上下文签发应写 tid claim");
assert_eq!(claims.login_id, "sec-tid-1", "既有 claim 不受 tid 接线影响");
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Ok(true)),
"同租户 tid token 应放行,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn no_tenant_context_login_omits_tid_claim() {
let (logic, _dao) = make_jwt_stateless_logic(|_| {});
let token = logic
.login("sec-tid-2", &LoginParams::default())
.await
.unwrap();
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
let payload = token.split('.').nth(1).unwrap();
let json = URL_SAFE_NO_PAD
.decode(payload)
.map(|b| String::from_utf8(b).unwrap())
.unwrap();
assert!(
!json.contains("\"tid\""),
"无租户上下文签发载荷不应含 tid,实际: {}",
json
);
let handler = crate::protocol::jwt::JwtHandler::new("session-token-security-test-32bytes");
let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
assert_eq!(claims.tid, None);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn require_tenant_bound_jwt_rejects_unbound_token_under_tenant() {
let (logic, _dao) = make_jwt_stateless_logic(|c| c.require_tenant_bound_jwt = true);
let token = logic
.login("sec-unbound-1", &LoginParams::default())
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Err(GarrisonError::Session(ref m)) if m.contains("stp-check-login-tenant-unbound")),
"开启严格开关后无 tid token 应显性拒绝,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn require_session_tenant_binding_does_not_affect_stateless() {
let (logic, _dao) = make_jwt_stateless_logic(|c| c.require_session_tenant_binding = true);
let token = logic
.login("sec-unbound-5", &LoginParams::default())
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Ok(true)),
"会话侧开关不应作用于 Stateless(无会话存储不等于无绑定),实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn require_tenant_bound_jwt_allows_tid_matching_token() {
let (logic, _dao) = make_jwt_stateless_logic(|c| c.require_tenant_bound_jwt = true);
let token = TENANT
.scope(tenant_ctx(7), async {
logic.login("sec-unbound-2", &LoginParams::default()).await
})
.await
.unwrap();
let check = with_current_token(token, async {
TENANT.scope(tenant_ctx(7), logic.check_login()).await
})
.await;
assert!(
matches!(check, Ok(true)),
"带匹配 tid 的 token 应放行,实际: {:?}",
check
);
}
#[cfg(feature = "protocol-jwt")]
#[tokio::test]
async fn require_tenant_bound_jwt_no_tenant_context_unchanged() {
let (logic, _dao) = make_jwt_stateless_logic(|c| c.require_tenant_bound_jwt = true);
let token = logic
.login("sec-unbound-3", &LoginParams::default())
.await
.unwrap();
let check = with_current_token(token, logic.check_login()).await;
assert!(
matches!(check, Ok(true)),
"无租户上下文行为不变,实际: {:?}",
check
);
}
}