use super::GarrisonLogicDefault;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use super::LoginParams;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::account::credential::password::{verify_and_rehash_pooled, verify_pooled};
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::constants::EventReason;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::dao::repository::UpdateUser;
#[cfg(feature = "firewall-bruteforce")]
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
#[cfg(all(
feature = "listener",
feature = "account-credential",
feature = "db-sqlite"
))]
use crate::listener::GarrisonEvent;
use crate::stp::session::SessionLogic;
use async_trait::async_trait;
#[cfg(feature = "firewall-bruteforce")]
use std::sync::Arc;
#[async_trait]
pub trait PasswordLogic: SessionLogic {
async fn login_with_password(
&self,
_login_id: &str,
_password: &str,
) -> GarrisonResult<String> {
Err(GarrisonError::NotImplemented(format!(
"stp-not-implemented::{}",
"login_with_password"
)))
}
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
static DUMMY_ARGON2_HASH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
use crate::account::credential::password::{Argon2Hasher, PasswordHasher as _};
Argon2Hasher::default()
.hash("garrison-h1-timing-equalizer")
.expect("固定输入的 Argon2 hash 生成恒成功(H-1 时序对齐 dummy)")
});
#[cfg_attr(
not(all(feature = "account-credential", feature = "db-sqlite")),
allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
fn acct_count_key(login_id: &str) -> String {
format!(
"{}acct:{}:count",
crate::constants::DaoKeyPrefix::BruteForce,
login_id
)
}
#[cfg_attr(
not(all(feature = "account-credential", feature = "db-sqlite")),
allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
fn acct_lock_key(login_id: &str) -> String {
format!(
"{}acct:{}:lock",
crate::constants::DaoKeyPrefix::BruteForce,
login_id
)
}
#[cfg_attr(
not(all(feature = "account-credential", feature = "db-sqlite")),
allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
async fn is_password_locked(dao: &Arc<dyn GarrisonDao>, login_id: &str) -> GarrisonResult<bool> {
dao.get(&acct_lock_key(login_id))
.await
.map(|v| v.is_some())
.map_err(|e| GarrisonError::Dao(format!("stp-password-lock-check::{}", e)))
}
#[cfg_attr(
not(all(feature = "account-credential", feature = "db-sqlite")),
allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
async fn record_password_failure(dao: &Arc<dyn GarrisonDao>, login_id: &str) -> GarrisonResult<()> {
use crate::strategy::firewall::brute_force::BruteForceConfig;
let cfg = BruteForceConfig::default();
let count = dao
.incr(&acct_count_key(login_id), cfg.window_seconds)
.await
.map_err(|e| GarrisonError::Dao(format!("stp-password-lock-incr::{}", e)))?;
if count >= cfg.max_attempts as u64 {
dao.set(&acct_lock_key(login_id), "1", cfg.lock_seconds)
.await
.map_err(|e| GarrisonError::Dao(format!("stp-password-lock-set::{}", e)))?;
}
Ok(())
}
#[cfg_attr(
not(all(feature = "account-credential", feature = "db-sqlite")),
allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
async fn reset_password_failures(dao: &Arc<dyn GarrisonDao>, login_id: &str) {
if let Err(e) = dao.delete(&acct_count_key(login_id)).await {
tracing::warn!(
login_id = login_id,
error = %e,
"{}", crate::i18n::translate_detail("logs-stp-password-lockout-reset-failed", &[])
);
}
}
#[async_trait]
impl PasswordLogic for GarrisonLogicDefault {
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
async fn login_with_password(&self, login_id: &str, password: &str) -> GarrisonResult<String> {
#[cfg(feature = "firewall-bruteforce")]
match is_password_locked(self.session.dao(), login_id).await {
Ok(true) => {
tracing::warn!(
login_id = login_id,
"{}",
crate::i18n::translate_detail("logs-stp-password-account-locked", &[])
);
return Err(GarrisonError::FirewallBlocked(format!(
"stp-password-account-locked::{}",
login_id
)));
},
Err(e) => {
tracing::warn!(login_id = login_id, error = %e,
"{}", crate::i18n::translate_detail("logs-stp-password-lockout-check-failed", &[]));
},
Ok(false) => {},
}
let hasher = self.password_hasher.as_ref().ok_or_else(|| {
GarrisonError::Config("stp-password-hasher-not-configured::".to_string())
})?;
let repo = self
.user_repository
.as_ref()
.ok_or_else(|| GarrisonError::Config("stp-user-repo-not-configured::".to_string()))?;
let username = login_id.to_string();
let tenant_id = crate::context::tenant::TENANT
.try_get()
.map(|ctx| ctx.tenant_id)
.unwrap_or(0);
let user = repo
.find_by_username(tenant_id, &username)
.await
.map_err(|e| GarrisonError::Dao(format!("stp-dao-find-by-id::{}", e)))?;
let user = match user {
Some(u) => u,
None => {
let _verified_dummy = verify_pooled(hasher, password, &DUMMY_ARGON2_HASH).await?;
tracing::warn!(
login_id = login_id,
reason = EventReason::InvalidCredentials.as_str(),
"login_with_password failed"
);
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::LoginFailure {
login_id: login_id.to_string(),
reason: EventReason::InvalidCredentials.to_string(),
request_context: None,
})
.await;
}
#[cfg(feature = "firewall-bruteforce")]
if let Err(e) = record_password_failure(self.session.dao(), login_id).await {
tracing::warn!(login_id = login_id, error = %e,
"{}", crate::i18n::translate_detail("logs-stp-password-lockout-record-failed", &[]));
}
return Err(GarrisonError::InvalidParam(
"stp-invalid-password::".to_string(),
));
},
};
let (verified, rehash) = match verify_and_rehash_pooled(
hasher,
password,
&user.password_hash,
)
.await
{
Ok(v) => v,
Err(GarrisonError::InvalidParam(hash_err)) => {
let _verified_dummy = verify_pooled(hasher, password, &DUMMY_ARGON2_HASH).await?;
tracing::warn!(
login_id = login_id,
reason = EventReason::HashFormatError.as_str(),
error = %hash_err,
"login_with_password: unsupported password hash format"
);
#[cfg(feature = "firewall-bruteforce")]
if let Err(record_err) = record_password_failure(self.session.dao(), login_id).await
{
tracing::warn!(login_id = login_id, error = %record_err,
"{}", crate::i18n::translate_detail("logs-stp-password-lockout-record-failed", &[]));
}
return Err(GarrisonError::InvalidParam(
"stp-invalid-password::".to_string(),
));
},
Err(e) => return Err(e),
};
if !verified {
tracing::warn!(
login_id = login_id,
reason = EventReason::InvalidCredentials.as_str(),
"login_with_password failed"
);
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::LoginFailure {
login_id: login_id.to_string(),
reason: EventReason::InvalidCredentials.to_string(),
request_context: None,
})
.await;
}
#[cfg(feature = "firewall-bruteforce")]
if let Err(e) = record_password_failure(self.session.dao(), login_id).await {
tracing::warn!(login_id = login_id, error = %e,
"{}", crate::i18n::translate_detail("logs-stp-password-lockout-record-failed", &[]));
}
return Err(GarrisonError::InvalidParam(
"stp-invalid-password::".to_string(),
));
}
#[cfg(feature = "firewall-bruteforce")]
reset_password_failures(self.session.dao(), login_id).await;
if let Some(new_hash) = rehash {
match repo
.update(
tenant_id,
&user.id,
UpdateUser {
password_hash: Some(new_hash),
..UpdateUser::default()
},
)
.await
{
Ok(()) =>
{
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::PasswordRehashed {
login_id: login_id.to_string(),
request_context: None,
})
.await;
}
},
Err(e) => {
tracing::warn!(
login_id = login_id,
error = %e,
"{}", crate::i18n::translate_detail("logs-stp-password-rehash-persist-failed", &[])
);
},
}
}
self.login(login_id, &LoginParams::default()).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GarrisonConfig;
use crate::dao::repository::UserRow;
use crate::dao::GarrisonDao;
use crate::error::GarrisonResult;
use crate::session::GarrisonSession;
use crate::stp::core::GarrisonCore;
use crate::stp::mock::{MockDao, MockFirewall};
use crate::stp::session::SessionLogic;
use crate::strategy::GarrisonPermissionStrategy;
use std::sync::Arc;
#[cfg_attr(
not(all(
feature = "account-credential",
feature = "db-sqlite",
any(feature = "firewall-bruteforce", feature = "listener")
)),
allow(dead_code)
)]
fn make_logic_without_creds() -> 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 {
has_permission: true,
has_role: true,
});
GarrisonLogicDefault::new(
session,
Arc::new(config),
firewall,
Arc::new(crate::account::disable::DefaultDisableRepository::new(
dao.clone(),
)),
)
}
#[cfg_attr(
not(all(
feature = "account-credential",
feature = "db-sqlite",
any(feature = "firewall-bruteforce", feature = "listener")
)),
allow(dead_code)
)]
fn make_user_row(login_id: &str, password_hash: &str) -> UserRow {
UserRow {
id: format!("u-{}", login_id),
username: login_id.to_string(),
password_hash: password_hash.to_string(),
status: "active".to_string(),
tenant_id: 0,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
last_login_at: None,
}
}
#[cfg(all(
feature = "firewall-bruteforce",
feature = "account-credential",
feature = "db-sqlite"
))]
#[tokio::test]
async fn login_with_password_locks_account_after_max_failures() {
use crate::account::credential::{Argon2Hasher, PasswordHasher};
use crate::strategy::firewall::brute_force::BruteForceConfig;
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let correct = "correct-horse-battery";
let hash = hasher.hash(correct).expect("argon2 hash 生成应成功");
let repo = crate::stp::mock::MockUserRepository::new();
repo.insert(make_user_row("alice", &hash));
let logic = logic
.with_password_hasher(Arc::clone(&hasher) as Arc<dyn PasswordHasher>)
.with_user_repository(Arc::new(repo));
let cfg = BruteForceConfig::default();
for i in 0..cfg.max_attempts {
let result = logic.login_with_password("alice", "wrong-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"前 {} 次失败应为统一 invalid-password,实际: {:?}",
i + 1,
result
);
}
let result = logic.login_with_password("alice", correct).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(ref msg)) if msg.contains("stp-password-account-locked")),
"超过阈值后正确密码也应被锁定拒绝,实际: {:?}",
result
);
}
#[cfg(all(
feature = "firewall-bruteforce",
feature = "account-credential",
feature = "db-sqlite"
))]
#[tokio::test]
async fn login_with_password_verify_time_data_error_unified_and_counted() {
use crate::account::credential::{Argon2Hasher, PasswordHasher};
use crate::stp::mock::MockUserRepository;
let logic = make_logic_without_creds();
let dao = logic.session.dao().clone();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let repo = MockUserRepository::new();
let real_hash = hasher.hash("correct-password").expect("argon2 hash 应成功");
repo.insert(make_user_row("alice", &real_hash));
repo.insert(make_user_row(
"bob",
"$scrypt$ln=16,r=8,p=1$c2FsdDEyMzQ1Njc4$MDEyMzQ1Njc4OWFiY2RlZg",
));
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(Arc::new(repo));
let unified = |e: &GarrisonError| matches!(e, GarrisonError::InvalidParam(m) if m == "stp-invalid-password::");
let wrong_pw = logic
.login_with_password("alice", "wrong-password")
.await
.unwrap_err();
let legacy = logic
.login_with_password("bob", "any-password")
.await
.unwrap_err();
assert!(
unified(&wrong_pw) && unified(&legacy),
"verify 期数据类错误应与密码错误统一返回 stp-invalid-password,实际: {:?} vs {:?}",
wrong_pw,
legacy
);
assert_eq!(
dao.get(&acct_count_key("bob")).await.unwrap().as_deref(),
Some("1"),
"verify 期数据类错误应计入账号维度失败计数"
);
assert_eq!(
dao.get(&acct_count_key("alice")).await.unwrap().as_deref(),
Some("1"),
"密码错误对照组应计入账号维度失败计数"
);
}
struct MockPassword {
config: Arc<GarrisonConfig>,
}
impl GarrisonCore for MockPassword {
fn config(&self) -> Arc<GarrisonConfig> {
Arc::clone(&self.config)
}
}
#[async_trait]
impl SessionLogic for MockPassword {
async fn login(
&self,
_login_id: &str,
_params: &crate::stp::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()))
}
}
#[async_trait]
impl PasswordLogic for MockPassword {}
#[tokio::test]
async fn login_with_password_default_returns_not_implemented() {
let mock = MockPassword {
config: Arc::new(GarrisonConfig::default()),
};
let id = "alice";
let result = mock.login_with_password(id, "secret").await;
assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
}
#[tokio::test]
async fn mock_password_login_returns_token() {
let mock = MockPassword {
config: Arc::new(GarrisonConfig::default()),
};
let token = mock
.login("alice", &crate::stp::LoginParams::default())
.await
.unwrap();
assert_eq!(token, "mock-token");
}
#[tokio::test]
async fn mock_password_session_methods_return_ok() {
let mock = MockPassword {
config: Arc::new(GarrisonConfig::default()),
};
mock.login_with_token("alice", "tok").await.unwrap();
mock.logout().await.unwrap();
mock.logout_by_login_id("alice").await.unwrap();
mock.kickout("alice").await.unwrap();
mock.kickout_by_token("tok").await.unwrap();
mock.revoke_token("tok").await.unwrap();
}
#[tokio::test]
async fn mock_password_check_login_and_get_login_id() {
let mock = MockPassword {
config: Arc::new(GarrisonConfig::default()),
};
assert!(mock.check_login().await.unwrap());
let id = mock.get_login_id().await.unwrap();
assert_eq!(id.as_deref(), Some("42"));
}
#[tokio::test]
async fn mock_password_config_returns_arc_clone() {
let mock = MockPassword {
config: Arc::new(GarrisonConfig::default()),
};
let c1 = mock.config();
let c2 = mock.config();
assert!(Arc::ptr_eq(&c1, &c2), "两次 config() 应返回同一 Arc");
}
#[cfg(all(
feature = "account-credential",
feature = "db-sqlite",
feature = "listener"
))]
mod default_impl_coverage {
use super::*;
use crate::account::credential::{Argon2Hasher, PasswordHasher};
use crate::dao::repository::{NewUser, UpdateUser, UserListRow, UserRepository};
use crate::listener::{GarrisonEvent, GarrisonListener, GarrisonListenerManager};
use crate::stp::mock::MockUserRepository;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::sync::Arc;
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(())
}
}
#[tokio::test]
async fn login_with_password_missing_hasher_returns_config_error() {
let logic = make_logic_without_creds();
let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new());
let logic = logic.with_user_repository(repo);
let result = logic.login_with_password("alice", "any").await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg == "stp-password-hasher-not-configured::"),
"未注入 hasher 应返回 Config(\"stp-password-hasher-not-configured\"),实际: {:?}",
result
);
}
#[tokio::test]
async fn login_with_password_missing_repo_returns_config_error() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let logic = logic.with_password_hasher(hasher);
let result = logic.login_with_password("alice", "any").await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg == "stp-user-repo-not-configured::"),
"未注入 repo 应返回 Config(\"stp-user-repo-not-configured\"),实际: {:?}",
result
);
}
#[cfg(feature = "listener")]
#[tokio::test]
async fn login_with_password_user_not_found_broadcasts_login_failure() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new()); let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo)
.with_listener_manager(lm);
let result = logic.login_with_password("missing-user", "any").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"用户不存在应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
result
);
let events = recorder.captured();
let failure_count = events
.iter()
.filter(|e| matches!(e, GarrisonEvent::LoginFailure { .. }))
.count();
assert_eq!(
failure_count, 1,
"应广播 1 次 LoginFailure 事件,实际广播: {} 次",
failure_count
);
if let Some(GarrisonEvent::LoginFailure {
login_id, reason, ..
}) = events.first()
{
assert_eq!(login_id, "missing-user");
assert_eq!(
reason, "invalid_credentials",
"reason 应为 'invalid_credentials'(防用户枚举),实际: {}",
reason
);
}
}
#[cfg(feature = "listener")]
#[tokio::test]
async fn login_with_password_wrong_password_broadcasts_login_failure() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let hash = hasher.hash("correct-password").unwrap();
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1001", &hash));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo)
.with_listener_manager(lm);
let result = logic.login_with_password("1001", "wrong-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"错误密码应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
result
);
let events = recorder.captured();
if let Some(GarrisonEvent::LoginFailure {
login_id, reason, ..
}) = events.first()
{
assert_eq!(login_id, "1001");
assert_eq!(
reason, "invalid_credentials",
"reason 应为 'invalid_credentials',实际: {}",
reason
);
} else {
panic!("应广播 LoginFailure 事件,实际捕获: {:?}", events);
}
}
#[tokio::test]
async fn login_with_password_user_not_found_performs_dummy_verify() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountingHasher {
verify_calls: AtomicUsize,
}
impl PasswordHasher for CountingHasher {
fn hash(&self, _password: &str) -> GarrisonResult<String> {
Ok("$argon2id$v=19$m=19456,t=2,p=1$dummy$dummy".to_string())
}
fn verify(&self, _password: &str, _hash: &str) -> GarrisonResult<bool> {
self.verify_calls.fetch_add(1, Ordering::Relaxed);
Ok(false)
}
}
let logic = make_logic_without_creds();
let counter = Arc::new(CountingHasher {
verify_calls: AtomicUsize::new(0),
});
let hasher: Arc<dyn PasswordHasher> = counter.clone();
let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new()); let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("missing-user", "any").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"用户不存在应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
result
);
assert_eq!(
counter.verify_calls.load(Ordering::Relaxed),
1,
"用户不存在分支应恰好执行一次 dummy verify(H-1 时序对齐),实际 0 次"
);
}
#[tokio::test]
async fn login_with_password_unsupported_hash_format_returns_error() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1002", "not-a-valid-hash-format"));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("1002", "any-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"哈希格式不支持应与密码错误统一返回 stp-invalid-password,实际: {:?}",
result
);
}
#[tokio::test]
async fn login_with_password_bad_hash_format_performs_dummy_verify() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct FormatErrorCountingHasher {
verify_calls: AtomicUsize,
}
impl PasswordHasher for FormatErrorCountingHasher {
fn hash(&self, _password: &str) -> GarrisonResult<String> {
Ok("$argon2id$v=19$m=19456,t=2,p=1$dummy$dummy".to_string())
}
fn verify(&self, _password: &str, hash: &str) -> GarrisonResult<bool> {
self.verify_calls.fetch_add(1, Ordering::Relaxed);
if hash.starts_with("$argon2") {
Ok(false)
} else {
Err(GarrisonError::InvalidParam(
"unsupported hash format".to_string(),
))
}
}
}
let logic = make_logic_without_creds();
let counter = Arc::new(FormatErrorCountingHasher {
verify_calls: AtomicUsize::new(0),
});
let hasher: Arc<dyn PasswordHasher> = counter.clone();
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1002", "not-a-valid-hash-format"));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("1002", "any-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"哈希格式非法应统一返回 stp-invalid-password,实际: {:?}",
result
);
assert_eq!(
counter.verify_calls.load(Ordering::Relaxed),
2,
"哈希格式非法分支应恰好执行 1 次真实校验 + 1 次 dummy verify(共 2 次),实际: {}",
counter.verify_calls.load(Ordering::Relaxed)
);
}
#[tokio::test]
async fn login_with_password_correct_credentials_returns_token() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let hash = hasher.hash("correct-password").unwrap();
let mock_repo = MockUserRepository::new();
mock_repo.insert(make_user_row("1003", &hash));
let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("1003", "correct-password").await;
assert!(
result.is_ok(),
"用户存在 + 密码正确应返回 Ok(token),实际: {:?}",
result
);
let token = result.unwrap();
assert!(!token.is_empty(), "返回的 token 不应为空字符串");
}
#[tokio::test]
async fn login_with_password_rehashes_legacy_hash_and_broadcasts_event() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let legacy = Argon2Hasher::with_params(8192, 2, 1);
let stored = legacy.hash("correct-password").expect("hash 应成功");
let mock_repo = Arc::new(MockUserRepository::new());
mock_repo.insert(make_user_row("2001", &stored));
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = logic
.with_password_hasher(hasher.clone())
.with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
.with_listener_manager(lm);
let result = logic.login_with_password("2001", "correct-password").await;
assert!(
result.is_ok(),
"低档位账户正确密码应登录成功,实际: {:?}",
result
);
let upgraded = mock_repo
.find_by_username(0, "2001")
.await
.expect("查询应成功")
.expect("用户应存在");
assert_ne!(
upgraded.password_hash, stored,
"登录成功后库内 hash 应已被升级重写"
);
assert!(
upgraded.password_hash.contains("m=19456"),
"升级后 hash 应为当前配置档位 m=19456,实际: {}",
upgraded.password_hash
);
assert!(
hasher
.verify("correct-password", &upgraded.password_hash)
.expect("verify 应成功"),
"升级后 hash 应可用原密码 verify 通过"
);
let events = recorder.captured();
assert!(
events.iter().any(|e| matches!(
e,
GarrisonEvent::PasswordRehashed { login_id, .. } if login_id.as_str() == "2001"
)),
"登录升级后应广播 PasswordRehashed 事件,实际: {:?}",
events
);
}
#[tokio::test]
async fn login_with_password_failure_does_not_rehash() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let legacy = Argon2Hasher::with_params(8192, 2, 1);
let stored = legacy.hash("correct-password").expect("hash 应成功");
let mock_repo = Arc::new(MockUserRepository::new());
mock_repo.insert(make_user_row("2002", &stored));
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
.with_listener_manager(lm);
let result = logic.login_with_password("2002", "wrong-password").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
"错误密码应返回统一 invalid-password,实际: {:?}",
result
);
let row = mock_repo
.find_by_username(0, "2002")
.await
.expect("查询应成功")
.expect("用户应存在");
assert_eq!(row.password_hash, stored, "登录失败不得升级存量哈希");
assert!(
recorder
.captured()
.iter()
.all(|e| !matches!(e, GarrisonEvent::PasswordRehashed { .. })),
"登录失败不得广播 PasswordRehashed 事件"
);
}
#[tokio::test]
async fn login_with_password_current_tier_keeps_hash_and_skips_event() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let stored = hasher.hash("correct-password").expect("hash 应成功");
let mock_repo = Arc::new(MockUserRepository::new());
mock_repo.insert(make_user_row("2003", &stored));
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
.with_listener_manager(lm);
let result = logic.login_with_password("2003", "correct-password").await;
assert!(
result.is_ok(),
"当前档位正确密码应登录成功,实际: {:?}",
result
);
let row = mock_repo
.find_by_username(0, "2003")
.await
.expect("查询应成功")
.expect("用户应存在");
assert_eq!(row.password_hash, stored, "档位持平时登录不得重写 hash");
assert!(
recorder
.captured()
.iter()
.all(|e| !matches!(e, GarrisonEvent::PasswordRehashed { .. })),
"档位持平时不得广播 PasswordRehashed 事件"
);
}
#[tokio::test]
async fn login_with_password_rehash_persist_failure_does_not_fail_login() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let legacy = Argon2Hasher::with_params(8192, 2, 1);
let stored = legacy.hash("correct-password").expect("hash 应成功");
let mock_repo = Arc::new(MockUserRepository::new());
mock_repo.insert(make_user_row("2004", &stored));
mock_repo.set_update_error("dao-update 模拟故障");
let recorder = Arc::new(RecordingListener::new());
let lm = Arc::new(GarrisonListenerManager::new());
lm.register(recorder.clone() as Arc<dyn GarrisonListener>);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
.with_listener_manager(lm);
let result = logic.login_with_password("2004", "correct-password").await;
assert!(
result.is_ok(),
"升级落库失败不得导致登录失败(尽力而为),实际: {:?}",
result
);
let row = mock_repo
.find_by_username(0, "2004")
.await
.expect("查询应成功")
.expect("用户应存在");
assert_eq!(row.password_hash, stored, "落库失败时库内 hash 应保持原样");
assert!(
recorder
.captured()
.iter()
.all(|e| !matches!(e, GarrisonEvent::PasswordRehashed { .. })),
"落库失败不得广播 PasswordRehashed 事件(不虚报升级)"
);
}
struct ErrorUserRepository;
#[async_trait]
impl UserRepository for ErrorUserRepository {
async fn find_by_id(
&self,
_tenant_id: i64,
_id: &str,
) -> GarrisonResult<Option<UserRow>> {
Err(GarrisonError::Dao("find_by_id 模拟失败".to_string()))
}
async fn find_by_username(
&self,
_tenant_id: i64,
_username: &str,
) -> GarrisonResult<Option<UserRow>> {
Err(GarrisonError::Dao(
"find_by_username 模拟连接断开".to_string(),
))
}
async fn create(&self, _tenant_id: i64, _user: NewUser) -> GarrisonResult<String> {
Err(GarrisonError::Dao("create 模拟失败".to_string()))
}
async fn update(
&self,
_tenant_id: i64,
_id: &str,
_user: UpdateUser,
) -> GarrisonResult<()> {
Err(GarrisonError::Dao("update 模拟失败".to_string()))
}
async fn delete(&self, _tenant_id: i64, _id: &str) -> GarrisonResult<()> {
Err(GarrisonError::Dao("delete 模拟失败".to_string()))
}
async fn list(
&self,
_tenant_id: i64,
_offset: i64,
_limit: i64,
) -> GarrisonResult<Vec<UserListRow>> {
Err(GarrisonError::Dao("list 模拟失败".to_string()))
}
}
#[tokio::test]
async fn login_with_password_repo_query_error_propagates_dao_error() {
let logic = make_logic_without_creds();
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
let repo: Arc<dyn UserRepository> = Arc::new(ErrorUserRepository);
let logic = logic
.with_password_hasher(hasher)
.with_user_repository(repo);
let result = logic.login_with_password("alice", "any").await;
assert!(
result.is_err(),
"UserRepository 查询失败应传播错误,实际: {:?}",
result
);
match result {
Err(GarrisonError::Dao(msg)) => {
assert!(
msg.contains("stp-dao-find-by-id"),
"错误消息应包含 'login_with_password 查询用户失败',实际: {}",
msg
);
assert!(
msg.contains("find_by_username 模拟连接断开"),
"错误消息应包含原始错误描述,实际: {}",
msg
);
},
Err(other) => panic!("期望 Dao 错误,实际: {:?}", other),
Ok(_) => panic!("期望错误传播,实际返回 Ok"),
}
}
}
}