use super::{Credential, CredentialModel, CredentialType};
use crate::error::{GarrisonError, GarrisonResult};
use argon2::{
password_hash::{PasswordHash, PasswordHasher as _, PasswordVerifier as _, SaltString},
Algorithm, Argon2, Params, Version,
};
use rand::rngs::OsRng;
pub trait PasswordHasher: Send + Sync {
fn hash(&self, password: &str) -> GarrisonResult<String>;
fn verify(&self, password: &str, hash: &str) -> GarrisonResult<bool>;
}
pub struct Argon2Hasher {
m_cost: u32,
t_cost: u32,
p_cost: u32,
}
impl Default for Argon2Hasher {
fn default() -> Self {
Self {
m_cost: 19456,
t_cost: 2,
p_cost: 1,
}
}
}
impl Argon2Hasher {
pub fn new() -> Self {
Self::default()
}
pub fn with_params(m_cost: u32, t_cost: u32, p_cost: u32) -> Self {
Self {
m_cost,
t_cost,
p_cost,
}
}
}
impl PasswordHasher for Argon2Hasher {
fn hash(&self, password: &str) -> GarrisonResult<String> {
#[cfg(feature = "account-credential-zeroize")]
let password_bytes = zeroize::Zeroizing::new(password.as_bytes().to_vec());
#[cfg(feature = "account-credential-zeroize")]
let password_ref: &[u8] = &password_bytes;
#[cfg(not(feature = "account-credential-zeroize"))]
let password_ref: &[u8] = password.as_bytes();
let salt = SaltString::generate(&mut OsRng);
let params = Params::new(self.m_cost, self.t_cost, self.p_cost, Some(32))
.map_err(|e| GarrisonError::InvalidParam(format!("account-argon2-param::{}", e)))?;
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let hash = argon2
.hash_password(password_ref, &salt)
.map_err(|e| GarrisonError::Internal(format!("account-argon2-hash::{}", e)))?
.to_string();
Ok(hash)
}
fn verify(&self, password: &str, hash: &str) -> GarrisonResult<bool> {
#[cfg(feature = "account-credential-zeroize")]
let password_bytes = zeroize::Zeroizing::new(password.as_bytes().to_vec());
#[cfg(feature = "account-credential-zeroize")]
let password_ref: &[u8] = &password_bytes;
#[cfg(not(feature = "account-credential-zeroize"))]
let password_ref: &[u8] = password.as_bytes();
let parsed = PasswordHash::new(hash)
.map_err(|e| GarrisonError::InvalidParam(format!("account-argon2-format::{}", e)))?;
let argon2 = Argon2::default();
match argon2.verify_password(password_ref, &parsed) {
Ok(()) => Ok(true),
Err(argon2::password_hash::Error::Password) => Ok(false),
Err(e) => Err(GarrisonError::Internal(format!(
"account-argon2-verify::{}",
e
))),
}
}
}
pub struct BcryptHasher {
cost: u32,
}
impl Default for BcryptHasher {
fn default() -> Self {
Self { cost: 12 }
}
}
impl BcryptHasher {
pub fn new() -> Self {
Self::default()
}
pub fn with_cost(cost: u32) -> Self {
Self { cost }
}
}
impl PasswordHasher for BcryptHasher {
fn hash(&self, password: &str) -> GarrisonResult<String> {
bcrypt::hash(password, self.cost)
.map_err(|e| GarrisonError::Internal(format!("account-bcrypt-hash::{}", e)))
}
fn verify(&self, password: &str, hash: &str) -> GarrisonResult<bool> {
bcrypt::verify(password, hash)
.map_err(|e| GarrisonError::InvalidParam(format!("account-bcrypt-format::{}", e)))
}
}
pub struct PasswordVerifier;
impl PasswordVerifier {
pub fn verify(password: &str, hash: &str) -> GarrisonResult<bool> {
if hash.starts_with("$argon2") {
Argon2Hasher::default().verify(password, hash)
} else if hash.starts_with("$2b$") || hash.starts_with("$2a$") || hash.starts_with("$2y$") {
BcryptHasher::default().verify(password, hash)
} else {
Err(GarrisonError::InvalidParam(format!(
"account-password-unsupported-hash-format::{}",
&hash[..hash.len().min(10)]
)))
}
}
}
pub struct PasswordCredential {
model: CredentialModel,
hasher: Box<dyn PasswordHasher>,
}
#[cfg(feature = "account-credential-zeroize")]
impl Drop for PasswordCredential {
fn drop(&mut self) {
use zeroize::Zeroize;
self.model.zeroize();
}
}
impl PasswordCredential {
pub fn new(model: CredentialModel, hasher: Box<dyn PasswordHasher>) -> Self {
Self { model, hasher }
}
}
#[async_trait::async_trait]
impl Credential for PasswordCredential {
fn credential_type(&self) -> CredentialType {
"password"
}
fn to_model(&self) -> CredentialModel {
self.model.clone()
}
async fn verify(&self, input: &str) -> GarrisonResult<bool> {
self.hasher.verify(input, &self.model.secret_data)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn password_hasher_is_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Argon2Hasher>();
assert_send_sync::<BcryptHasher>();
assert_send_sync::<PasswordVerifier>();
}
#[test]
fn argon2_hash_returns_argon2id_prefix() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("password").unwrap();
assert!(
hash.starts_with("$argon2id$"),
"Argon2 哈希应以 $argon2id$ 开头,实际: {}",
hash
);
}
#[test]
fn argon2_hash_same_password_produces_different_results() {
let hasher = Argon2Hasher::default();
let h1 = hasher.hash("password").unwrap();
let h2 = hasher.hash("password").unwrap();
assert_ne!(h1, h2, "相同密码两次 hash 应产生不同结果(盐随机)");
}
#[test]
fn argon2_verify_correct_password_returns_true() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("password").unwrap();
let result = hasher.verify("password", &hash).unwrap();
assert!(result, "正确密码应返回 Ok(true)");
}
#[test]
fn argon2_verify_wrong_password_returns_false() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("password").unwrap();
let result = hasher.verify("wrong", &hash).unwrap();
assert!(!result, "错误密码应返回 Ok(false)");
}
#[test]
fn argon2_with_params_customizes_costs() {
let hasher = Argon2Hasher::with_params(8192, 1, 1);
assert_eq!(hasher.m_cost, 8192);
assert_eq!(hasher.t_cost, 1);
assert_eq!(hasher.p_cost, 1);
let hash = hasher.hash("test").unwrap();
assert!(hash.starts_with("$argon2id$"));
assert!(hasher.verify("test", &hash).unwrap());
}
#[test]
fn bcrypt_hash_returns_2b_prefix() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
assert!(
hash.starts_with("$2b$"),
"Bcrypt 哈希应以 $2b$ 开头,实际: {}",
hash
);
}
#[test]
fn bcrypt_verify_correct_password_returns_true() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
let result = hasher.verify("password", &hash).unwrap();
assert!(result, "正确密码应返回 Ok(true)");
}
#[test]
fn bcrypt_verify_wrong_password_returns_false() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
let result = hasher.verify("wrong", &hash).unwrap();
assert!(!result, "错误密码应返回 Ok(false)");
}
#[test]
fn bcrypt_verify_recognizes_2a_format() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
let hash_2a = hash.replacen("$2b$", "$2a$", 1);
let result = hasher.verify("password", &hash_2a).unwrap();
assert!(result, "BcryptHasher 应识别 $2a$ 格式");
}
#[test]
fn bcrypt_verify_recognizes_2y_format() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
let hash_2y = hash.replacen("$2b$", "$2y$", 1);
let result = hasher.verify("password", &hash_2y).unwrap();
assert!(result, "BcryptHasher 应识别 $2y$ 格式");
}
#[test]
fn bcrypt_with_cost_customizes_cost() {
let hasher = BcryptHasher::with_cost(4);
assert_eq!(hasher.cost, 4);
let hash = hasher.hash("test").unwrap();
assert!(hash.starts_with("$2b$"));
assert!(hasher.verify("test", &hash).unwrap());
}
#[test]
fn password_verifier_delegates_to_argon2() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("password").unwrap();
let result = PasswordVerifier::verify("password", &hash).unwrap();
assert!(result, "PasswordVerifier 应委托 Argon2Hasher 校验正确密码");
let wrong = PasswordVerifier::verify("wrong", &hash).unwrap();
assert!(!wrong, "PasswordVerifier 应委托 Argon2Hasher 校验错误密码");
}
#[test]
fn password_verifier_delegates_to_bcrypt() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
let result = PasswordVerifier::verify("password", &hash).unwrap();
assert!(result, "PasswordVerifier 应委托 BcryptHasher 校验正确密码");
let wrong = PasswordVerifier::verify("wrong", &hash).unwrap();
assert!(!wrong, "PasswordVerifier 应委托 BcryptHasher 校验错误密码");
}
#[test]
fn password_verifier_unsupported_format_returns_invalid_param() {
let result = PasswordVerifier::verify("password", "$unknown$hash");
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"不支持的 hash 格式应返回 InvalidParam,实际: {:?}",
result
);
}
#[test]
fn password_verifier_delegates_to_bcrypt_2a_format() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("password").unwrap();
let hash_2a = hash.replacen("$2b$", "$2a$", 1);
let result = PasswordVerifier::verify("password", &hash_2a).unwrap();
assert!(result, "PasswordVerifier 应识别 $2a$ 格式");
}
#[cfg(any(
feature = "protocol-oauth2",
feature = "protocol-sso",
feature = "protocol-sign",
feature = "secure-sign",
feature = "secure-httpbasic",
feature = "secure-httpdigest",
feature = "social-alipay",
feature = "web-csrf"
))]
#[test]
fn hash_produces_32_byte_output() {
let hasher = Argon2Hasher::default();
let hash = hasher.hash("test-password").expect("hash 应成功");
let parts: Vec<&str> = hash.split('$').collect();
assert!(
parts.len() >= 6,
"PHC hash 字符串应至少 6 段,实际: {} (hash={})",
parts.len(),
hash
);
let hash_b64 = parts[5];
use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine as _};
let hash_bytes = STANDARD_NO_PAD
.decode(hash_b64)
.expect("hash 末段应是合法 base64 (无 padding)");
assert_eq!(
hash_bytes.len(),
32,
"Argon2 输出应为 32 字节,实际: {} (hash={})",
hash_bytes.len(),
hash
);
}
#[cfg(feature = "account-credential-zeroize")]
#[test]
fn password_param_zeroed_after_hash() {
use zeroize::{Zeroize, Zeroizing};
let hasher = Argon2Hasher::default();
let password = "my-secret-password";
let hash = hasher.hash(password).expect("hash 应成功");
assert!(
hash.starts_with("$argon2id$"),
"hash 应以 $argon2id$ 开头,实际: {}",
hash
);
assert!(
hasher
.verify(password, &hash)
.expect("verify 正确密码应成功"),
"正确密码应校验通过"
);
assert!(
!hasher
.verify("wrong", &hash)
.expect("verify 错误密码应成功"),
"错误密码应校验失败"
);
let mut local_copy: Vec<u8> = password.as_bytes().to_vec();
local_copy.zeroize();
assert_eq!(local_copy.len(), 0, "Vec::zeroize 后 length 应为 0 (clear)");
let mut arr: [u8; 18] = [0; 18];
arr.copy_from_slice(password.as_bytes());
arr.zeroize();
assert!(
arr.iter().all(|&b| b == 0),
"数组 zeroize 后所有字节应为 0,实际: {:?}",
arr
);
let wrapped = Zeroizing::new(password.to_string());
let hash2 = hasher.hash(wrapped.as_str()).expect("hash 应成功");
assert!(
hasher
.verify(wrapped.as_str(), &hash2)
.expect("verify 应成功"),
"wrapped password 校验应通过"
);
}
fn make_password_cred(id: &str, user: &str, password: &str) -> (PasswordCredential, String) {
let hasher = Argon2Hasher::default();
let hash = hasher.hash(password).expect("hash 应成功");
let model = CredentialModel {
id: id.to_string(),
user_id: user.to_string(),
credential_type: "password".to_string(),
secret_data: hash,
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = PasswordCredential::new(model, Box::new(hasher));
(cred, password.to_string())
}
#[test]
fn password_credential_type_returns_password() {
let (cred, _) = make_password_cred("c1", "alice", "secret");
assert_eq!(cred.credential_type(), "password");
}
#[test]
fn password_credential_to_model_returns_original() {
let (cred, _) = make_password_cred("c1", "alice", "secret");
let model = cred.to_model();
assert_eq!(model.id, "c1");
assert_eq!(model.user_id, "alice");
assert_eq!(model.credential_type, "password");
assert!(
model.secret_data.starts_with("$argon2id$"),
"secret_data 应为 argon2 hash"
);
}
#[tokio::test]
async fn password_credential_verify_correct_password() {
let (cred, password) = make_password_cred("c1", "alice", "my-secret");
let result = cred.verify(&password).await.expect("verify 应成功");
assert!(result, "正确密码应校验通过");
}
#[tokio::test]
async fn password_credential_verify_wrong_password() {
let (cred, _) = make_password_cred("c1", "alice", "my-secret");
let result = cred
.verify("wrong-password")
.await
.expect("verify 应成功(返回 false 而非报错)");
assert!(!result, "错误密码应校验失败");
}
#[tokio::test]
async fn password_credential_works_with_bcrypt_hasher() {
let hasher = BcryptHasher::default();
let hash = hasher.hash("bcrypt-secret").expect("hash 应成功");
let model = CredentialModel {
id: "c2".to_string(),
user_id: "bob".to_string(),
credential_type: "password".to_string(),
secret_data: hash,
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = PasswordCredential::new(model, Box::new(hasher));
assert!(
cred.verify("bcrypt-secret").await.expect("verify 应成功"),
"Bcrypt 正确密码应校验通过"
);
assert!(
!cred.verify("wrong").await.expect("verify 应成功"),
"Bcrypt 错误密码应校验失败"
);
}
#[tokio::test]
async fn password_credential_usable_as_dyn_credential() {
let (cred, password) = make_password_cred("c1", "alice", "secret");
let dyn_cred: Box<dyn Credential> = Box::new(cred);
assert_eq!(dyn_cred.credential_type(), "password");
let result = dyn_cred.verify(&password).await.expect("verify 应成功");
assert!(result, "dyn Credential 正确密码应校验通过");
}
#[cfg(feature = "account-credential-zeroize")]
#[tokio::test]
async fn password_credential_zeroize_integration() {
let (cred, password) = make_password_cred("c1", "alice", "zeroize-secret");
let result = cred.verify(&password).await.expect("verify 应成功");
assert!(result, "zeroize feature 启用时正确密码应校验通过");
let wrong = cred.verify("wrong").await.expect("verify 应成功");
assert!(!wrong, "zeroize feature 启用时错误密码应校验失败");
}
}