use super::GarrisonLogicDefault;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use super::LoginParams;
#[cfg(all(
feature = "listener",
feature = "account-credential",
feature = "db-sqlite"
))]
use crate::constants::EventReason;
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;
#[async_trait]
pub trait PasswordLogic: SessionLogic {
async fn login_with_password(
&self,
_login_id: &str,
_password: &str,
) -> GarrisonResult<String> {
Err(GarrisonError::NotImplemented(
"login_with_password 未实现:需启用 account-credential + db-sqlite feature".to_string(),
))
}
}
#[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> {
let hasher = self
.password_hasher
.as_ref()
.ok_or_else(|| GarrisonError::Config("password hasher not configured".to_string()))?;
let repo = self
.user_repository
.as_ref()
.ok_or_else(|| GarrisonError::Config("user repository not configured".to_string()))?;
let username = login_id.to_string();
let user = repo
.find_by_username(0, &username)
.await
.map_err(|e| GarrisonError::Dao(format!("stp-dao-find-by-id::{}", e)))?;
let user = match user {
Some(u) => u,
None => {
tracing::warn!(
login_id = login_id,
reason = EventReason::InvalidCredentials.as_str(),
"login_with_password 失败"
);
#[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;
}
return Err(GarrisonError::InvalidParam("invalid password".to_string()));
},
};
let verified = hasher.verify(password, &user.password_hash).map_err(|e| {
tracing::warn!(
login_id = login_id,
reason = EventReason::HashFormatError.as_str(),
error = %e,
"login_with_password 密码哈希格式不支持"
);
GarrisonError::InvalidParam("unsupported hash format".to_string())
})?;
if !verified {
tracing::warn!(
login_id = login_id,
reason = EventReason::InvalidCredentials.as_str(),
"login_with_password 失败"
);
#[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;
}
return Err(GarrisonError::InvalidParam("invalid password".to_string()));
}
self.login(login_id, &LoginParams::default()).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GarrisonConfig;
use crate::error::GarrisonResult;
use crate::stp::core::GarrisonCore;
use crate::stp::session::SessionLogic;
use std::sync::Arc;
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"))]
mod default_impl_coverage {
use super::*;
use crate::account::credential::{Argon2Hasher, PasswordHasher};
use crate::config::GarrisonConfig;
use crate::dao::repository::{NewUser, UpdateUser, UserRepository, UserRow};
use crate::dao::GarrisonDao;
use crate::listener::{GarrisonEvent, GarrisonListener, GarrisonListenerManager};
use crate::session::GarrisonSession;
use crate::stp::mock::{MockDao, MockFirewall, MockUserRepository};
use crate::strategy::GarrisonPermissionStrategy;
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(())
}
}
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,
}
}
fn make_logic_without_creds() -> GarrisonLogicDefault {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao, 3600, 86400));
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)
}
#[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 == "password hasher not configured"),
"未注入 hasher 应返回 Config(\"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 == "user repository not configured"),
"未注入 repo 应返回 Config(\"user repository 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 == "invalid password"),
"用户不存在应返回 InvalidParam(\"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 == "invalid password"),
"错误密码应返回 InvalidParam(\"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_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 == "unsupported hash format"),
"哈希格式不支持应返回 InvalidParam(\"unsupported hash format\"),实际: {:?}",
result
);
}
#[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 不应为空字符串");
}
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<UserRow>> {
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"),
}
}
}
}