use argon2::{
Algorithm, Argon2, Params, PasswordHash, PasswordHasher as Argon2PasswordHasher,
PasswordVerifier as _, Version, password_hash::phc::Output,
};
use thiserror::Error;
use crate::result::{ClassifyError, ErrorKind};
pub const DEFAULT_MAX_PASSWORD_BYTES: usize = 1024;
pub const DEFAULT_ARGON2ID_MEMORY_COST_KIB: u32 = 19 * 1024;
pub const DEFAULT_ARGON2ID_TIME_COST: u32 = 2;
pub const DEFAULT_ARGON2ID_PARALLELISM: u32 = 1;
pub const DEFAULT_ARGON2ID_OUTPUT_BYTES: usize = 32;
pub const ARGON2_VERSION_13: u32 = 0x13;
const DUMMY_PASSWORD_SALT: &[u8] = b"password-enumeration-timing-guard";
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PasswordError {
#[error("password must not exceed {max} bytes")]
PasswordTooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("password policy is invalid")]
InvalidPasswordPolicy,
#[error("password hash profile is invalid")]
InvalidPasswordHashProfile,
#[error("password hash failed")]
HashFailed,
#[error("password hash is invalid")]
InvalidPasswordHash,
#[error("password hash algorithm is unsupported")]
UnsupportedPasswordHash,
#[error("password verification failed")]
VerificationFailed,
#[error("password verification {parameter} {actual} exceeds the configured limit {max}")]
VerificationCostExceeded {
parameter: &'static str,
actual: u32,
max: u32,
},
}
impl ClassifyError for PasswordError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::PasswordTooLong { .. }
| Self::InvalidPasswordPolicy
| Self::InvalidPasswordHashProfile
| Self::InvalidPasswordHash
| Self::UnsupportedPasswordHash
| Self::VerificationCostExceeded { .. } => ErrorKind::Validation,
Self::HashFailed | Self::VerificationFailed => ErrorKind::Internal,
}
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::PasswordTooLong { .. } => "password_too_long",
Self::InvalidPasswordPolicy => "invalid_password_policy",
Self::InvalidPasswordHashProfile => "invalid_password_hash_profile",
Self::HashFailed => "password_hash_failed",
Self::InvalidPasswordHash => "invalid_password_hash",
Self::UnsupportedPasswordHash => "unsupported_password_hash",
Self::VerificationFailed => "password_verification_failed",
Self::VerificationCostExceeded { .. } => "password_verification_cost_exceeded",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordPolicy {
max_password_bytes: usize,
verification_limits: Option<PasswordVerificationLimits>,
}
impl PasswordPolicy {
pub const fn new(max_password_bytes: usize) -> Result<Self, PasswordError> {
if max_password_bytes == 0 {
return Err(PasswordError::InvalidPasswordPolicy);
}
Ok(Self {
max_password_bytes,
verification_limits: None,
})
}
#[must_use]
pub const fn max_password_bytes(&self) -> usize {
self.max_password_bytes
}
#[must_use]
pub const fn with_verification_limits(
mut self,
limits: Option<PasswordVerificationLimits>,
) -> Self {
self.verification_limits = limits;
self
}
#[must_use]
pub const fn verification_limits(&self) -> Option<PasswordVerificationLimits> {
self.verification_limits
}
pub(super) fn validate_password(self, password: &str) -> Result<(), PasswordError> {
if password.len() > self.max_password_bytes {
return Err(PasswordError::PasswordTooLong {
max: self.max_password_bytes,
});
}
Ok(())
}
}
impl Default for PasswordPolicy {
fn default() -> Self {
Self {
max_password_bytes: DEFAULT_MAX_PASSWORD_BYTES,
verification_limits: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordVerificationLimits {
max_memory_cost_kib: u32,
max_time_cost: u32,
max_parallelism: u32,
}
impl PasswordVerificationLimits {
pub const fn new(
max_memory_cost_kib: u32,
max_time_cost: u32,
max_parallelism: u32,
) -> Result<Self, PasswordError> {
if max_memory_cost_kib < Params::MIN_M_COST
|| max_time_cost < Params::MIN_T_COST
|| max_parallelism < Params::MIN_P_COST
{
return Err(PasswordError::InvalidPasswordPolicy);
}
Ok(Self {
max_memory_cost_kib,
max_time_cost,
max_parallelism,
})
}
#[must_use]
pub const fn max_memory_cost_kib(&self) -> u32 {
self.max_memory_cost_kib
}
#[must_use]
pub const fn max_time_cost(&self) -> u32 {
self.max_time_cost
}
#[must_use]
pub const fn max_parallelism(&self) -> u32 {
self.max_parallelism
}
fn validate(self, metadata: PasswordHashMetadata) -> Result<(), PasswordError> {
for (parameter, actual, max) in [
(
"memory_cost_kib",
metadata.memory_cost_kib,
self.max_memory_cost_kib,
),
("time_cost", metadata.time_cost, self.max_time_cost),
("parallelism", metadata.parallelism, self.max_parallelism),
] {
if let Some(actual) = actual
&& actual > max
{
return Err(PasswordError::VerificationCostExceeded {
parameter,
actual,
max,
});
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Argon2idProfile {
memory_cost_kib: u32,
time_cost: u32,
parallelism: u32,
output_bytes: usize,
}
impl Argon2idProfile {
pub const fn new(
memory_cost_kib: u32,
time_cost: u32,
parallelism: u32,
output_bytes: usize,
) -> Result<Self, PasswordError> {
if output_bytes < Output::MIN_LENGTH
|| output_bytes > Output::MAX_LENGTH
|| Params::new(memory_cost_kib, time_cost, parallelism, Some(output_bytes)).is_err()
{
return Err(PasswordError::InvalidPasswordHashProfile);
}
Ok(Self {
memory_cost_kib,
time_cost,
parallelism,
output_bytes,
})
}
#[must_use]
pub const fn owasp_minimum() -> Self {
Self {
memory_cost_kib: DEFAULT_ARGON2ID_MEMORY_COST_KIB,
time_cost: DEFAULT_ARGON2ID_TIME_COST,
parallelism: DEFAULT_ARGON2ID_PARALLELISM,
output_bytes: DEFAULT_ARGON2ID_OUTPUT_BYTES,
}
}
#[must_use]
pub const fn memory_cost_kib(&self) -> u32 {
self.memory_cost_kib
}
#[must_use]
pub const fn time_cost(&self) -> u32 {
self.time_cost
}
#[must_use]
pub const fn parallelism(&self) -> u32 {
self.parallelism
}
#[must_use]
pub const fn output_bytes(&self) -> usize {
self.output_bytes
}
fn params(self) -> Result<Params, PasswordError> {
Params::new(
self.memory_cost_kib,
self.time_cost,
self.parallelism,
Some(self.output_bytes),
)
.map_err(|_| PasswordError::InvalidPasswordHashProfile)
}
}
impl Default for Argon2idProfile {
fn default() -> Self {
Self::owasp_minimum()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PasswordHashAlgorithm {
Argon2d,
Argon2i,
Argon2id,
Unknown,
}
impl PasswordHashAlgorithm {
#[must_use]
pub const fn is_argon2id(self) -> bool {
matches!(self, Self::Argon2id)
}
fn from_identifier(identifier: &str) -> Self {
match identifier {
"argon2d" => Self::Argon2d,
"argon2i" => Self::Argon2i,
"argon2id" => Self::Argon2id,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordHashMetadata {
algorithm: PasswordHashAlgorithm,
version: Option<u32>,
memory_cost_kib: Option<u32>,
time_cost: Option<u32>,
parallelism: Option<u32>,
output_bytes: Option<usize>,
}
impl PasswordHashMetadata {
#[must_use]
pub const fn algorithm(&self) -> PasswordHashAlgorithm {
self.algorithm
}
#[must_use]
pub const fn version(&self) -> Option<u32> {
self.version
}
#[must_use]
pub const fn memory_cost_kib(&self) -> Option<u32> {
self.memory_cost_kib
}
#[must_use]
pub const fn time_cost(&self) -> Option<u32> {
self.time_cost
}
#[must_use]
pub const fn parallelism(&self) -> Option<u32> {
self.parallelism
}
#[must_use]
pub const fn output_bytes(&self) -> Option<usize> {
self.output_bytes
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordHashAssessment {
metadata: PasswordHashMetadata,
needs_rehash: bool,
}
impl PasswordHashAssessment {
#[must_use]
pub const fn metadata(&self) -> PasswordHashMetadata {
self.metadata
}
#[must_use]
pub const fn needs_rehash(&self) -> bool {
self.needs_rehash
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordVerification {
assessment: PasswordHashAssessment,
verified: bool,
}
impl PasswordVerification {
#[must_use]
pub const fn verified(&self) -> bool {
self.verified
}
#[must_use]
pub const fn needs_rehash(&self) -> bool {
self.verified && self.assessment.needs_rehash
}
#[must_use]
pub const fn assessment(&self) -> PasswordHashAssessment {
self.assessment
}
}
#[derive(Debug, Clone, Default)]
pub struct PasswordService {
profile: Argon2idProfile,
policy: PasswordPolicy,
}
impl PasswordService {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_policy(mut self, policy: PasswordPolicy) -> Self {
self.policy = policy;
self
}
#[must_use]
pub fn with_profile(mut self, profile: Argon2idProfile) -> Self {
self.profile = profile;
self
}
#[must_use]
pub const fn policy(&self) -> PasswordPolicy {
self.policy
}
#[must_use]
pub const fn profile(&self) -> Argon2idProfile {
self.profile
}
pub fn hash_password(&self, password: &str) -> Result<String, PasswordError> {
self.policy.validate_password(password)?;
self.argon2()?
.hash_password(password.as_bytes())
.map(|hash| hash.to_string())
.map_err(|_| PasswordError::HashFailed)
}
pub fn dummy_password_hash(&self) -> Result<String, PasswordError> {
self.argon2()?
.hash_password_with_salt(b"", DUMMY_PASSWORD_SALT)
.map(|hash| hash.to_string())
.map_err(|_| PasswordError::HashFailed)
}
pub fn verify_password(
&self,
password: &str,
password_hash: &str,
) -> Result<bool, PasswordError> {
self.verify_and_assess(password, password_hash)
.map(|verification| verification.verified())
}
pub fn verify_and_assess(
&self,
password: &str,
password_hash: &str,
) -> Result<PasswordVerification, PasswordError> {
self.policy.validate_password(password)?;
let parsed =
PasswordHash::new(password_hash).map_err(|_| PasswordError::InvalidPasswordHash)?;
let assessment = self.assess_parsed_hash(&parsed);
if let Some(limits) = self.policy.verification_limits {
limits.validate(assessment.metadata)?;
}
match self.argon2()?.verify_password(password.as_bytes(), &parsed) {
Ok(()) => Ok(PasswordVerification {
assessment,
verified: true,
}),
Err(argon2::password_hash::Error::PasswordInvalid) => Ok(PasswordVerification {
assessment,
verified: false,
}),
Err(argon2::password_hash::Error::Algorithm) => {
Err(PasswordError::UnsupportedPasswordHash)
}
Err(_) => Err(PasswordError::VerificationFailed),
}
}
pub fn assess_password_hash(
&self,
password_hash: &str,
) -> Result<PasswordHashAssessment, PasswordError> {
let parsed =
PasswordHash::new(password_hash).map_err(|_| PasswordError::InvalidPasswordHash)?;
Ok(self.assess_parsed_hash(&parsed))
}
fn assess_parsed_hash(&self, parsed: &PasswordHash) -> PasswordHashAssessment {
let metadata = password_hash_metadata(parsed);
PasswordHashAssessment {
metadata,
needs_rehash: self.hash_needs_rehash(metadata),
}
}
fn hash_needs_rehash(&self, metadata: PasswordHashMetadata) -> bool {
let profile = self.profile;
!metadata.algorithm.is_argon2id()
|| metadata.version != Some(ARGON2_VERSION_13)
|| metadata
.memory_cost_kib
.is_none_or(|value| value < profile.memory_cost_kib())
|| metadata
.time_cost
.is_none_or(|value| value < profile.time_cost())
|| metadata
.parallelism
.is_none_or(|value| value < profile.parallelism())
|| metadata
.output_bytes
.is_none_or(|value| value < profile.output_bytes())
}
fn argon2(&self) -> Result<Argon2<'_>, PasswordError> {
Ok(Argon2::new(
Algorithm::Argon2id,
Version::V0x13,
self.profile.params()?,
))
}
}
fn password_hash_metadata(parsed: &PasswordHash) -> PasswordHashMetadata {
let params = Params::try_from(parsed).ok();
PasswordHashMetadata {
algorithm: PasswordHashAlgorithm::from_identifier(parsed.algorithm.as_str()),
version: parsed.version,
memory_cost_kib: params.as_ref().map(Params::m_cost),
time_cost: params.as_ref().map(Params::t_cost),
parallelism: params.as_ref().map(Params::p_cost),
output_bytes: params.and_then(|params| params.output_len()),
}
}
#[cfg(test)]
mod tests {
use super::{
Argon2idProfile, PasswordError, PasswordHashAlgorithm, PasswordPolicy, PasswordService,
PasswordVerificationLimits,
};
#[test]
fn verification_limits_are_optional_and_independent_cost_ceilings() {
assert_eq!(PasswordPolicy::default().verification_limits(), None);
assert_eq!(PasswordPolicy::new(32).unwrap().verification_limits(), None);
for (memory, time, parallelism) in [(0, 1, 1), (7, 1, 1), (8, 0, 1), (8, 1, 0)] {
assert_eq!(
PasswordVerificationLimits::new(memory, time, parallelism),
Err(PasswordError::InvalidPasswordPolicy)
);
}
let limits = PasswordVerificationLimits::new(8, 1, 2).unwrap();
assert_eq!(limits.max_memory_cost_kib(), 8);
assert_eq!(limits.max_time_cost(), 1);
assert_eq!(limits.max_parallelism(), 2);
let policy = PasswordPolicy::new(32)
.unwrap()
.with_verification_limits(Some(limits));
assert_eq!(policy.max_password_bytes(), 32);
assert_eq!(policy.verification_limits(), Some(limits));
assert_eq!(
policy.with_verification_limits(None).verification_limits(),
None
);
}
#[test]
fn verification_limits_accept_boundaries_and_report_each_exceeded_cost() {
use crate::result::{ClassifyError, ErrorKind};
let hash = PasswordService::new()
.with_profile(Argon2idProfile::new(32, 2, 2, 16).unwrap())
.hash_password("test password")
.unwrap();
let verifier =
PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
for (memory, time, parallelism, exceeded) in [
(32, 2, 2, None),
(16, 2, 2, Some(("memory_cost_kib", 32, 16))),
(32, 1, 2, Some(("time_cost", 2, 1))),
(32, 2, 1, Some(("parallelism", 2, 1))),
] {
let limits = PasswordVerificationLimits::new(memory, time, parallelism).unwrap();
let service = verifier
.clone()
.with_policy(PasswordPolicy::default().with_verification_limits(Some(limits)));
let result = service.verify_and_assess("test password", &hash);
if let Some((parameter, actual, max)) = exceeded {
let error = result.unwrap_err();
assert_eq!(
error,
PasswordError::VerificationCostExceeded {
parameter,
actual,
max
}
);
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "password_verification_cost_exceeded");
} else {
let verification = result.unwrap();
assert!(verification.verified());
assert!(!verification.needs_rehash());
assert!(!service.verify_password("wrong password", &hash).unwrap());
}
}
}
#[test]
fn excessive_phc_parameters_are_checked_without_computing_a_hash() {
for (costs, limits, parameter, actual, max) in [
(
format!("m={},t=1,p=1", u32::MAX),
PasswordVerificationLimits::new(32, 2, 2).unwrap(),
"memory_cost_kib",
u32::MAX,
32,
),
(
format!("m=8,t={},p=1", u32::MAX),
PasswordVerificationLimits::new(32, 2, 2).unwrap(),
"time_cost",
u32::MAX,
2,
),
(
format!(
"m={},t=1,p={}",
8 * argon2::Params::MAX_P_COST,
argon2::Params::MAX_P_COST
),
PasswordVerificationLimits::new(u32::MAX, 2, 2).unwrap(),
"parallelism",
argon2::Params::MAX_P_COST,
2,
),
] {
let hash = format!(
"$argon2id$v=19${costs}$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0"
);
let metadata = PasswordService::new()
.assess_password_hash(&hash)
.unwrap()
.metadata();
assert_eq!(
limits.validate(metadata),
Err(PasswordError::VerificationCostExceeded {
parameter,
actual,
max
})
);
}
}
#[test]
fn old_algorithms_and_higher_historical_costs_remain_verifiable() {
use argon2::{Algorithm, Argon2, Params, PasswordHasher as _, Version};
let hash = Argon2::new(
Algorithm::Argon2i,
Version::V0x10,
Params::new(16, 2, 2, Some(16)).unwrap(),
)
.hash_password(b"legacy password")
.unwrap()
.to_string();
for limits in [
None,
Some(PasswordVerificationLimits::new(16, 2, 2).unwrap()),
] {
let service = PasswordService::new()
.with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap())
.with_policy(PasswordPolicy::default().with_verification_limits(limits));
let verification = service.verify_and_assess("legacy password", &hash).unwrap();
assert!(verification.verified());
assert!(verification.needs_rehash());
}
}
#[test]
fn verification_limits_leave_generation_assessment_and_rehash_independent() {
let weak = PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
let old_hash = weak.hash_password("test password").unwrap();
let service =
PasswordService::new()
.with_profile(Argon2idProfile::new(16, 1, 1, 16).unwrap())
.with_policy(PasswordPolicy::default().with_verification_limits(Some(
PasswordVerificationLimits::new(8, 1, 1).unwrap(),
)));
let verification = service
.verify_and_assess("test password", &old_hash)
.unwrap();
assert!(verification.verified());
assert!(verification.needs_rehash());
for hash in [
service.hash_password("test password").unwrap(),
service.dummy_password_hash().unwrap(),
] {
let assessment = service.assess_password_hash(&hash).unwrap();
assert_eq!(assessment.metadata().memory_cost_kib(), Some(16));
assert!(!assessment.needs_rehash());
assert!(matches!(
service.verify_password("test password", &hash),
Err(PasswordError::VerificationCostExceeded { .. })
));
}
}
#[test]
fn verification_limits_preserve_invalid_hash_errors() {
let service =
PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
let bounded = service.clone().with_policy(
PasswordPolicy::default()
.with_verification_limits(Some(PasswordVerificationLimits::new(8, 1, 1).unwrap())),
);
for (hash, expected) in [
("invalid PHC", PasswordError::InvalidPasswordHash),
(
"$argon2id$v=19$m=0,t=1,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0",
PasswordError::VerificationFailed,
),
(
"$unknown$v=19$m=8,t=1,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0",
PasswordError::UnsupportedPasswordHash,
),
] {
assert_eq!(
service.verify_password("password", hash).unwrap_err(),
expected
);
assert_eq!(
bounded.verify_password("password", hash).unwrap_err(),
expected
);
}
}
#[test]
fn hashes_with_explicit_argon2id_profile() {
let service = PasswordService::new();
let password_hash = service
.hash_password("correct horse battery staple")
.expect("test password should hash");
let assessment = service
.assess_password_hash(&password_hash)
.expect("test password hash should parse");
let metadata = assessment.metadata();
assert_eq!(metadata.algorithm(), PasswordHashAlgorithm::Argon2id);
assert_eq!(metadata.version(), Some(super::ARGON2_VERSION_13));
assert_eq!(
metadata.memory_cost_kib(),
Some(super::DEFAULT_ARGON2ID_MEMORY_COST_KIB)
);
assert_eq!(
metadata.time_cost(),
Some(super::DEFAULT_ARGON2ID_TIME_COST)
);
assert_eq!(
metadata.parallelism(),
Some(super::DEFAULT_ARGON2ID_PARALLELISM)
);
assert_eq!(
metadata.output_bytes(),
Some(super::DEFAULT_ARGON2ID_OUTPUT_BYTES)
);
assert!(!assessment.needs_rehash());
}
#[test]
fn verifies_hashes_created_before_the_argon2_upgrade() {
let legacy_hash = "$argon2id$v=19$m=19456,t=2,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0";
let service = PasswordService::new();
let verification = service
.verify_and_assess("legacy test password", legacy_hash)
.expect("existing PHC hashes must remain readable");
assert!(verification.verified());
assert!(!verification.needs_rehash());
assert!(
!service
.verify_password("wrong password", legacy_hash)
.unwrap()
);
}
#[test]
fn verifies_matching_password() {
let service = PasswordService::new();
let password_hash = service
.hash_password("correct horse battery staple")
.expect("test password should hash");
let verification = service
.verify_and_assess("correct horse battery staple", &password_hash)
.expect("test password hash should parse");
assert!(verification.verified());
assert!(!verification.needs_rehash());
}
#[test]
fn dummy_hash_reuses_the_configured_argon2_cost_profile() {
let service = PasswordService::new();
let dummy_hash = service
.dummy_password_hash()
.expect("dummy password hash should build");
let assessment = service
.assess_password_hash(&dummy_hash)
.expect("dummy password hash should parse");
assert!(!assessment.needs_rehash());
assert!(!service.verify_password("not-empty", &dummy_hash).unwrap());
}
#[test]
fn rejects_non_matching_password() {
let service = PasswordService::new();
let password_hash = service
.hash_password("correct horse battery staple")
.expect("test password should hash");
let verification = service
.verify_and_assess("wrong password", &password_hash)
.expect("test password hash should parse");
assert!(!verification.verified());
assert!(!verification.needs_rehash());
}
#[test]
fn rejects_invalid_hash_format() {
let service = PasswordService::new();
let result = service.verify_password("password", "not-a-password-hash");
assert!(matches!(result, Err(PasswordError::InvalidPasswordHash)));
}
#[test]
fn marks_weaker_hashes_for_rehash_after_successful_verification() {
let weak_profile = Argon2idProfile::new(8, 1, 1, 16).unwrap();
let weak_service = PasswordService::new().with_profile(weak_profile);
let password_hash = weak_service
.hash_password("correct horse battery staple")
.expect("test password should hash");
let verification = PasswordService::new()
.verify_and_assess("correct horse battery staple", &password_hash)
.expect("test password hash should parse");
assert!(verification.verified());
assert!(verification.needs_rehash());
}
#[tokio::test]
async fn cancelled_waiter_keeps_password_capacity_until_blocking_work_finishes() {
use std::sync::Arc;
use tokio::sync::{Semaphore, TryAcquireError, oneshot};
let weak_service =
PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
let stored_hash = weak_service.hash_password("test password").unwrap();
let service =
PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 32).unwrap());
let slots = Arc::new(Semaphore::new(1));
let (started_tx, started_rx) = oneshot::channel();
let (resume_tx, resume_rx) = oneshot::channel();
let (finished_tx, finished_rx) = oneshot::channel();
let worker_slots = Arc::clone(&slots);
let worker_service = service.clone();
let waiter = tokio::spawn(async move {
let permit = worker_slots.acquire_owned().await.unwrap();
tokio::task::spawn_blocking(move || {
let _permit = permit;
started_tx.send(()).unwrap();
resume_rx.blocking_recv().unwrap();
let verification = worker_service
.verify_and_assess("test password", &stored_hash)
.unwrap();
let replacement_hash = verification
.needs_rehash()
.then(|| worker_service.hash_password("test password").unwrap());
finished_tx.send((verification, replacement_hash)).unwrap();
})
.await
.unwrap();
});
started_rx.await.unwrap();
waiter.abort();
assert!(waiter.await.unwrap_err().is_cancelled());
assert!(matches!(
slots.try_acquire(),
Err(TryAcquireError::NoPermits)
));
resume_tx.send(()).unwrap();
let (verification, replacement_hash) = finished_rx.await.unwrap();
let _released_capacity = slots.acquire().await.unwrap();
assert!(verification.verified());
assert!(verification.needs_rehash());
assert!(
!service
.assess_password_hash(&replacement_hash.unwrap())
.unwrap()
.needs_rehash()
);
}
#[test]
fn rejects_oversized_passwords() {
let service = PasswordService::new()
.with_policy(PasswordPolicy::new(4).expect("policy should be valid"));
assert!(matches!(
service.hash_password("12345"),
Err(PasswordError::PasswordTooLong { max: 4 })
));
assert!(matches!(
service.verify_password("12345", "not-a-password-hash"),
Err(PasswordError::PasswordTooLong { max: 4 })
));
}
#[test]
fn rejects_invalid_password_policy() {
assert!(matches!(
PasswordPolicy::new(0),
Err(PasswordError::InvalidPasswordPolicy)
));
}
#[test]
fn rejects_invalid_argon2id_profile() {
for (memory_cost_kib, time_cost, parallelism) in [
(0, 2, 1),
(8, 0, 1),
(8, 1, 0),
(8, 1, 2),
(u32::MAX, 1, u32::MAX),
] {
assert!(matches!(
Argon2idProfile::new(memory_cost_kib, time_cost, parallelism, 32),
Err(PasswordError::InvalidPasswordHashProfile)
));
}
for output_bytes in [0, 4, 9, 65, usize::MAX] {
assert!(matches!(
Argon2idProfile::new(8, 1, 1, output_bytes),
Err(PasswordError::InvalidPasswordHashProfile)
));
}
}
#[test]
fn phc_output_boundaries_hash_and_verify_successfully() {
for output_bytes in [10, 64] {
let profile = Argon2idProfile::new(8, 1, 1, output_bytes)
.expect("PHC output boundary should be supported");
let service = PasswordService::new().with_profile(profile);
let hash = service
.hash_password("test password")
.expect("valid profile should produce a PHC hash");
let verification = service
.verify_and_assess("test password", &hash)
.expect("PHC hash should verify");
assert!(verification.verified());
assert!(!verification.needs_rehash());
assert_eq!(
service
.assess_password_hash(&hash)
.expect("PHC hash should parse")
.metadata()
.output_bytes(),
Some(output_bytes)
);
}
}
}