use super::{Credential, CredentialModel, CredentialType};
use crate::error::{GarrisonError, GarrisonResult};
use std::sync::Arc;
use tokio::sync::Semaphore;
use argon2::{
password_hash::{phc::PasswordHash, PasswordHasher as _, PasswordVerifier as _},
Algorithm, Argon2, Params, Version,
};
pub trait PasswordHasher: Send + Sync {
fn hash(&self, password: &str) -> GarrisonResult<String>;
fn verify(&self, password: &str, hash: &str) -> GarrisonResult<bool>;
fn concurrency_gate(&self) -> Option<&Arc<Semaphore>> {
None
}
fn verify_and_rehash(
&self,
password: &str,
hash: &str,
) -> GarrisonResult<(bool, Option<String>)> {
let matched = self.verify(password, hash)?;
Ok((matched, None))
}
}
pub struct Argon2Hasher {
m_cost: u32,
t_cost: u32,
p_cost: u32,
pool: Option<Arc<Semaphore>>,
}
impl Default for Argon2Hasher {
fn default() -> Self {
Self {
m_cost: 19456,
t_cost: 2,
p_cost: 1,
pool: None,
}
}
}
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,
pool: None,
}
}
pub fn with_pool(mut self, pool_size: usize) -> Self {
self.pool = Some(Arc::new(Semaphore::new(pool_size.max(1))));
self
}
}
impl PasswordHasher for Argon2Hasher {
fn concurrency_gate(&self) -> Option<&Arc<Semaphore>> {
self.pool.as_ref()
}
fn hash(&self, password: &str) -> GarrisonResult<String> {
#[cfg(feature = "credential-zeroize")]
let password_bytes = zeroize::Zeroizing::new(password.as_bytes().to_vec());
#[cfg(feature = "credential-zeroize")]
let password_ref: &[u8] = &password_bytes;
#[cfg(not(feature = "credential-zeroize"))]
let password_ref: &[u8] = password.as_bytes();
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)
.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 = "credential-zeroize")]
let password_bytes = zeroize::Zeroizing::new(password.as_bytes().to_vec());
#[cfg(feature = "credential-zeroize")]
let password_ref: &[u8] = &password_bytes;
#[cfg(not(feature = "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::PasswordInvalid) => Ok(false),
Err(e) => Err(GarrisonError::InvalidParam(format!(
"account-argon2-verify::{}",
e
))),
}
}
fn verify_and_rehash(
&self,
password: &str,
hash: &str,
) -> GarrisonResult<(bool, Option<String>)> {
let matched = self.verify(password, hash)?;
if !matched {
return Ok((false, None));
}
let parsed = PasswordHash::new(hash)
.map_err(|e| GarrisonError::InvalidParam(format!("account-argon2-format::{}", e)))?;
let stored = Params::try_from(&parsed.params)
.map_err(|e| GarrisonError::InvalidParam(format!("account-argon2-params::{}", e)))?;
let legacy_tier = (stored.m_cost(), stored.t_cost(), stored.p_cost());
let configured_tier = (self.m_cost, self.t_cost, self.p_cost);
if legacy_tier >= configured_tier {
return Ok((true, None));
}
let new_hash = self.hash(password)?;
Ok((true, Some(new_hash)))
}
}
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 {
let cost = cost.clamp(4, 31);
Self { cost }
}
}
impl PasswordHasher for BcryptHasher {
fn hash(&self, password: &str) -> GarrisonResult<String> {
#[cfg(feature = "credential-zeroize")]
let password_bytes = zeroize::Zeroizing::new(password.to_string());
#[cfg(feature = "credential-zeroize")]
let password_ref: &str = &password_bytes;
#[cfg(not(feature = "credential-zeroize"))]
let password_ref: &str = password;
bcrypt::hash(password_ref, self.cost)
.map_err(|e| GarrisonError::Internal(format!("account-bcrypt-hash::{}", e)))
}
fn verify(&self, password: &str, hash: &str) -> GarrisonResult<bool> {
#[cfg(feature = "credential-zeroize")]
let password_bytes = zeroize::Zeroizing::new(password.to_string());
#[cfg(feature = "credential-zeroize")]
let password_ref: &str = &password_bytes;
#[cfg(not(feature = "credential-zeroize"))]
let password_ref: &str = password;
bcrypt::verify(password_ref, hash)
.map_err(|e| GarrisonError::InvalidParam(format!("account-bcrypt-format::{}", e)))
}
}
async fn acquire_permit(
hasher: &dyn PasswordHasher,
) -> GarrisonResult<Option<tokio::sync::OwnedSemaphorePermit>> {
match hasher.concurrency_gate() {
Some(sem) => sem
.clone()
.acquire_owned()
.await
.map(Some)
.map_err(|_| GarrisonError::Internal("account-argon2-pool-closed::".to_string())),
None => Ok(None),
}
}
pub(crate) async fn verify_pooled(
hasher: &Arc<dyn PasswordHasher>,
password: &str,
hash: &str,
) -> GarrisonResult<bool> {
let permit = acquire_permit(hasher.as_ref()).await?;
let hasher = Arc::clone(hasher);
let password = password.to_string();
let hash = hash.to_string();
tokio::task::spawn_blocking(move || {
let _permit = permit;
hasher.verify(&password, &hash)
})
.await
.map_err(|e| GarrisonError::Internal(format!("credential-verify-blocking::{}", e)))?
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
pub(crate) async fn verify_and_rehash_pooled(
hasher: &Arc<dyn PasswordHasher>,
password: &str,
hash: &str,
) -> GarrisonResult<(bool, Option<String>)> {
let permit = acquire_permit(hasher.as_ref()).await?;
let hasher = Arc::clone(hasher);
let password = password.to_string();
let hash = hash.to_string();
tokio::task::spawn_blocking(move || {
let _permit = permit;
hasher.verify_and_rehash(&password, &hash)
})
.await
.map_err(|e| GarrisonError::Internal(format!("credential-verify-blocking::{}", 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: Arc<dyn PasswordHasher>,
}
#[cfg(feature = "credential-zeroize")]
impl Drop for PasswordCredential {
fn drop(&mut self) {
use zeroize::Zeroize;
self.model.zeroize();
}
}
impl PasswordCredential {
pub fn new(model: CredentialModel, hasher: Arc<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> {
verify_pooled(&self.hasher, input, &self.model.secret_data).await
}
}
#[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 argon2_verify_unknown_algorithm_returns_invalid_param() {
let hasher = Argon2Hasher::default();
let result = hasher.verify(
"password",
"$scrypt$ln=16,r=8,p=1$c2FsdDEyMzQ1Njc4$MDEyMzQ1Njc4OWFiY2RlZg",
);
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"verify 期算法未知应返回 InvalidParam,实际: {:?}",
result
);
}
#[test]
fn argon2_verify_unknown_algorithm_variant_returns_invalid_param() {
let hasher = Argon2Hasher::default();
let result = hasher.verify(
"password",
"$argon2x$v=19$m=19456,t=2,p=1$c2FsdDEyMzQ1Njc4$MDEyMzQ1Njc4OWFiY2RlZg",
);
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"verify 期 argon2 变体未知应返回 InvalidParam,实际: {:?}",
result
);
}
#[test]
fn argon2_verify_out_of_range_params_returns_invalid_param() {
let hasher = Argon2Hasher::default();
let result = hasher.verify(
"password",
"$argon2id$v=19$m=1,t=2,p=1$c2FsdDEyMzQ1Njc4$MDEyMzQ1Njc4OWFiY2RlZg",
);
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"verify 期参数越界应返回 InvalidParam,实际: {:?}",
result
);
}
#[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 = "protocol-httpbasic",
feature = "protocol-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 = "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, Arc::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, Arc::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 正确密码应校验通过");
}
#[tokio::test]
async fn password_credential_verify_concurrent_correctness() {
let hasher = Argon2Hasher::default().with_pool(1);
let hash = hasher.hash("pool-secret").expect("hash 应成功");
let model = CredentialModel {
id: "c3".to_string(),
user_id: "carol".to_string(),
credential_type: "password".to_string(),
secret_data: hash,
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = Arc::new(PasswordCredential::new(model, Arc::new(hasher)));
let mut handles = Vec::new();
for i in 0..3 {
let cred = Arc::clone(&cred);
handles.push(tokio::spawn(async move {
if i == 1 {
cred.verify("wrong").await
} else {
cred.verify("pool-secret").await
}
}));
}
assert!(handles.remove(0).await.unwrap().unwrap(), "正确密码应通过");
assert!(!handles.remove(0).await.unwrap().unwrap(), "错误密码应拒绝");
assert!(handles.remove(0).await.unwrap().unwrap(), "正确密码应通过");
}
#[cfg(feature = "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 启用时错误密码应校验失败");
}
struct GatedHasher {
pool: Option<Arc<tokio::sync::Semaphore>>,
entered_tx: tokio::sync::mpsc::UnboundedSender<()>,
release_rx: std::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<()>>,
in_flight: std::sync::atomic::AtomicUsize,
max_in_flight: std::sync::atomic::AtomicUsize,
}
impl GatedHasher {
fn new(
entered_tx: tokio::sync::mpsc::UnboundedSender<()>,
release_rx: tokio::sync::mpsc::UnboundedReceiver<()>,
pool_size: usize,
) -> Self {
Self {
pool: Some(Arc::new(tokio::sync::Semaphore::new(pool_size))),
entered_tx,
release_rx: std::sync::Mutex::new(release_rx),
in_flight: std::sync::atomic::AtomicUsize::new(0),
max_in_flight: std::sync::atomic::AtomicUsize::new(0),
}
}
fn max_in_flight(&self) -> usize {
self.max_in_flight.load(std::sync::atomic::Ordering::SeqCst)
}
}
impl PasswordHasher for GatedHasher {
fn hash(&self, password: &str) -> GarrisonResult<String> {
Ok(password.to_string())
}
fn verify(&self, _password: &str, _hash: &str) -> GarrisonResult<bool> {
use std::sync::atomic::Ordering as AOrd;
let n = self.in_flight.fetch_add(1, AOrd::SeqCst) + 1;
self.max_in_flight.fetch_max(n, AOrd::SeqCst);
let _ = self.entered_tx.send(());
let _released = self
.release_rx
.lock()
.expect("release_rx 锁不应中毒")
.blocking_recv();
self.in_flight.fetch_sub(1, AOrd::SeqCst);
Ok(true)
}
fn concurrency_gate(&self) -> Option<&Arc<tokio::sync::Semaphore>> {
self.pool.as_ref()
}
}
struct PassthroughHasher;
impl PasswordHasher for PassthroughHasher {
fn hash(&self, password: &str) -> GarrisonResult<String> {
Ok(password.to_string())
}
fn verify(&self, password: &str, hash: &str) -> GarrisonResult<bool> {
Ok(password == hash)
}
}
#[test]
fn gate_default_hashers_return_none() {
assert!(Argon2Hasher::default().concurrency_gate().is_none());
assert!(Argon2Hasher::with_params(8192, 1, 1)
.concurrency_gate()
.is_none());
assert!(BcryptHasher::default().concurrency_gate().is_none());
}
#[test]
fn with_pool_clamps_zero_to_one() {
let zero = Argon2Hasher::default().with_pool(0);
assert_eq!(
zero.concurrency_gate().unwrap().available_permits(),
1,
"with_pool(0) 应钳制为 1 permit"
);
let five = Argon2Hasher::default().with_pool(5);
assert_eq!(five.concurrency_gate().unwrap().available_permits(), 5);
}
#[tokio::test]
async fn pool_bounds_concurrent_executions() {
let (entered_tx, mut entered_rx) = tokio::sync::mpsc::unbounded_channel();
let (release_tx, release_rx) = tokio::sync::mpsc::unbounded_channel();
let gated = Arc::new(GatedHasher::new(entered_tx, release_rx, 1));
let hasher: Arc<dyn PasswordHasher> = gated.clone();
let mut handles = Vec::new();
for _ in 0..3 {
let h = Arc::clone(&hasher);
handles.push(tokio::spawn(async move {
verify_pooled(&h, "pw", "$argon2id$fake").await
}));
}
entered_rx.recv().await.expect("应有第 1 个进入信号");
assert_eq!(
gated.max_in_flight(),
1,
"池=1 时同时执行中的 verify 至多 1 个"
);
release_tx.send(()).expect("release 通道应存活");
entered_rx.recv().await.expect("第 2 个应在放行后进入");
release_tx.send(()).expect("release 通道应存活");
entered_rx.recv().await.expect("第 3 个应在放行后进入");
release_tx.send(()).expect("release 通道应存活");
for h in handles {
assert!(
h.await.expect("任务不应 panic").expect("verify 应成功"),
"排队不拒绝,3 个 verify 结果全对"
);
}
assert_eq!(
gated.max_in_flight(),
1,
"全程并发上界应精确等于 permit 数 1"
);
}
#[tokio::test]
async fn pool_permits_released_after_completion() {
let hasher = Arc::new(Argon2Hasher::default().with_pool(2));
let gate = hasher.concurrency_gate().unwrap().clone();
assert_eq!(gate.available_permits(), 2);
let hash = hasher.hash("pw").expect("hash 应成功");
let mut handles = Vec::new();
for _ in 0..2 {
let h: Arc<dyn PasswordHasher> = hasher.clone();
let hash = hash.clone();
handles.push(tokio::spawn(
async move { verify_pooled(&h, "pw", &hash).await },
));
}
for h in handles {
h.await.expect("任务不应 panic").expect("verify 应成功");
}
assert_eq!(
gate.available_permits(),
2,
"完成后 permits 应回到初值(无泄漏)"
);
}
#[tokio::test]
async fn pool_cancelled_caller_does_not_oversell() {
let (entered_tx, mut entered_rx) = tokio::sync::mpsc::unbounded_channel();
let (release_tx, release_rx) = tokio::sync::mpsc::unbounded_channel();
let gated = Arc::new(GatedHasher::new(entered_tx, release_rx, 1));
let gate = gated.concurrency_gate().unwrap().clone();
let hasher: Arc<dyn PasswordHasher> = gated.clone();
let h1 = Arc::clone(&hasher);
let task1 = tokio::spawn(async move { verify_pooled(&h1, "pw", "h").await });
entered_rx.recv().await.expect("task1 应已进入 verify");
task1.abort();
let h2 = Arc::clone(&hasher);
let task2 = tokio::spawn(async move { verify_pooled(&h2, "pw", "h").await });
assert!(
entered_rx.try_recv().is_err(),
"task1 的 verify 仍在执行时 task2 不得进入(permit 存活期绑定哈希执行期)"
);
release_tx.send(()).expect("release 通道应存活");
entered_rx
.recv()
.await
.expect("task2 应在 task1 完成后进入");
release_tx.send(()).expect("release 通道应存活");
assert!(
task2
.await
.expect("task2 不应 panic")
.expect("task2 verify 应成功"),
"task2 排队后应正常完成"
);
assert_eq!(
gate.available_permits(),
1,
"全部完成后 permits 应回到初值(取消时序下无泄漏)"
);
assert_eq!(gated.max_in_flight(), 1, "取消时序下并发上界仍为 1");
}
#[tokio::test]
async fn pool_closed_returns_error() {
let hasher = Arc::new(Argon2Hasher::default().with_pool(1));
hasher.concurrency_gate().unwrap().close();
let result = verify_pooled(&(hasher as Arc<dyn PasswordHasher>), "pw", "h").await;
match &result {
Err(GarrisonError::Internal(msg)) => assert!(
msg.contains("account-argon2-pool-closed"),
"错误串应含 account-argon2-pool-closed,实际: {}",
msg
),
other => panic!("池关闭应返回 Internal 错误,实际: {:?}", other),
}
}
#[tokio::test]
async fn gate_none_passes_through() {
let hasher: Arc<dyn PasswordHasher> = Arc::new(PassthroughHasher);
let hit = verify_pooled(&hasher, "pw", "pw").await.expect("应直通");
assert!(hit, "密码匹配应返回 true");
let miss = verify_pooled(&hasher, "pw", "other").await.expect("应直通");
assert!(!miss, "密码不匹配应返回 false");
}
#[test]
fn verify_and_rehash_default_impl_returns_verify_result_and_none() {
let hasher: Arc<dyn PasswordHasher> = Arc::new(PassthroughHasher);
let hit = hasher.verify_and_rehash("pw", "pw").expect("verify 应成功");
assert_eq!(hit, (true, None), "密码匹配应返回 (true, None)");
let miss = hasher
.verify_and_rehash("pw", "other")
.expect("verify 应成功");
assert_eq!(miss, (false, None), "密码不匹配应返回 (false, None)");
}
#[test]
fn verify_and_rehash_low_tier_hash_returns_upgraded_hash() {
let legacy = Argon2Hasher::with_params(8192, 2, 1);
let stored = legacy.hash("legacy-secret").expect("hash 应成功");
assert!(stored.contains("m=8192"), "存量哈希应为低档位 m=8192");
let hasher = Argon2Hasher::default();
let (verified, rehash) = hasher
.verify_and_rehash("legacy-secret", &stored)
.expect("verify_and_rehash 应成功");
assert!(verified, "正确密码应 verify 通过");
let new_hash = rehash.expect("低档位存量哈希应产出升级 hash");
assert!(
hasher
.verify("legacy-secret", &new_hash)
.expect("verify 应成功"),
"升级后的新 hash 应可通过当前配置 verify"
);
assert!(
new_hash.contains("m=19456"),
"新 hash 应使用当前配置档位 m=19456,实际: {}",
new_hash
);
}
#[test]
fn verify_and_rehash_current_tier_returns_none() {
let hasher = Argon2Hasher::default();
let stored = hasher.hash("same-tier").expect("hash 应成功");
let (verified, rehash) = hasher
.verify_and_rehash("same-tier", &stored)
.expect("verify_and_rehash 应成功");
assert!(verified, "正确密码应 verify 通过");
assert!(rehash.is_none(), "档位不低于配置时不应重哈希");
}
#[test]
fn verify_and_rehash_stronger_tier_does_not_downgrade() {
let strong = Argon2Hasher::with_params(32768, 3, 1);
let stored = strong.hash("strong-secret").expect("hash 应成功");
let hasher = Argon2Hasher::default();
let (verified, rehash) = hasher
.verify_and_rehash("strong-secret", &stored)
.expect("verify_and_rehash 应成功");
assert!(verified, "正确密码应 verify 通过");
assert!(rehash.is_none(), "存量档位高于配置时不得重哈希降级");
}
#[test]
fn verify_and_rehash_wrong_password_returns_false_and_none() {
let legacy = Argon2Hasher::with_params(8192, 2, 1);
let stored = legacy.hash("legacy-secret").expect("hash 应成功");
let hasher = Argon2Hasher::default();
let (verified, rehash) = hasher
.verify_and_rehash("wrong-password", &stored)
.expect("verify 应成功(返回 false 而非报错)");
assert!(!verified, "错误密码应 verify 失败");
assert!(rehash.is_none(), "verify 失败不得产出新 hash");
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[tokio::test]
async fn verify_and_rehash_pooled_upgrades_and_returns_permit() {
let legacy = Argon2Hasher::with_params(8192, 2, 1);
let stored = legacy.hash("legacy-secret").expect("hash 应成功");
let hasher = Arc::new(Argon2Hasher::default().with_pool(2));
let gate = hasher.concurrency_gate().unwrap().clone();
let h: Arc<dyn PasswordHasher> = hasher.clone();
let (verified, rehash) = verify_and_rehash_pooled(&h, "legacy-secret", &stored)
.await
.expect("verify_and_rehash 应成功");
assert!(verified, "正确密码应 verify 通过");
let new_hash = rehash.expect("低档位存量应经池产出升级 hash");
assert!(
verify_pooled(&h, "legacy-secret", &new_hash)
.await
.expect("verify 应成功"),
"升级后的新 hash 应可通过 verify"
);
assert_eq!(
gate.available_permits(),
2,
"完成后 permits 应回到初值(无泄漏)"
);
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[tokio::test]
async fn verify_and_rehash_pooled_current_tier_returns_none() {
let hasher = Arc::new(Argon2Hasher::default().with_pool(1));
let stored = hasher.hash("same-tier").expect("hash 应成功");
let h: Arc<dyn PasswordHasher> = hasher.clone();
let (verified, rehash) = verify_and_rehash_pooled(&h, "same-tier", &stored)
.await
.expect("verify_and_rehash 应成功");
assert!(verified, "正确密码应 verify 通过");
assert!(rehash.is_none(), "档位持平时池化出口同样不重哈希");
}
}