use argon2::{
Algorithm, Argon2, Params, PasswordHash, PasswordHasher as Argon2PasswordHasher,
PasswordVerifier as _, Version,
password_hash::{SaltString, rand_core::OsRng},
};
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, Error)]
#[non_exhaustive]
pub enum SecurityError {
#[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")]
PasswordHash,
#[error("password hash is invalid")]
InvalidPasswordHash,
#[error("password hash algorithm is unsupported")]
UnsupportedPasswordHash,
#[error("password verification failed")]
PasswordVerify,
}
impl ClassifyError for SecurityError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::PasswordTooLong { .. }
| Self::InvalidPasswordPolicy
| Self::InvalidPasswordHashProfile
| Self::InvalidPasswordHash
| Self::UnsupportedPasswordHash => ErrorKind::Validation,
Self::PasswordHash | Self::PasswordVerify => 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::PasswordHash => "password_hash_failed",
Self::InvalidPasswordHash => "invalid_password_hash",
Self::UnsupportedPasswordHash => "unsupported_password_hash",
Self::PasswordVerify => "password_verification_failed",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordPolicy {
max_password_bytes: usize,
}
impl PasswordPolicy {
pub const fn new(max_password_bytes: usize) -> Result<Self, SecurityError> {
if max_password_bytes == 0 {
return Err(SecurityError::InvalidPasswordPolicy);
}
Ok(Self { max_password_bytes })
}
#[must_use]
pub const fn max_password_bytes(&self) -> usize {
self.max_password_bytes
}
fn validate_password(self, password: &str) -> Result<(), SecurityError> {
if password.len() > self.max_password_bytes {
return Err(SecurityError::PasswordTooLong {
max: self.max_password_bytes,
});
}
Ok(())
}
}
impl Default for PasswordPolicy {
fn default() -> Self {
Self {
max_password_bytes: DEFAULT_MAX_PASSWORD_BYTES,
}
}
}
#[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, SecurityError> {
if time_cost < Params::MIN_T_COST {
return Err(SecurityError::InvalidPasswordHashProfile);
}
if parallelism < Params::MIN_P_COST || parallelism > Params::MAX_P_COST {
return Err(SecurityError::InvalidPasswordHashProfile);
}
if memory_cost_kib < Params::MIN_M_COST || memory_cost_kib < parallelism * 8 {
return Err(SecurityError::InvalidPasswordHashProfile);
}
if output_bytes < Params::MIN_OUTPUT_LEN || output_bytes > Params::MAX_OUTPUT_LEN {
return Err(SecurityError::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, SecurityError> {
Params::new(
self.memory_cost_kib,
self.time_cost,
self.parallelism,
Some(self.output_bytes),
)
.map_err(|_| SecurityError::InvalidPasswordHashProfile)
}
}
impl Default for Argon2idProfile {
fn default() -> Self {
Self::owasp_minimum()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PasswordHashProfile {
argon2id: Argon2idProfile,
}
impl PasswordHashProfile {
#[must_use]
pub const fn argon2id(argon2id: Argon2idProfile) -> Self {
Self { argon2id }
}
#[must_use]
pub const fn owasp_minimum() -> Self {
Self {
argon2id: Argon2idProfile::owasp_minimum(),
}
}
#[must_use]
pub const fn argon2id_profile(&self) -> Argon2idProfile {
self.argon2id
}
}
#[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: PasswordHashProfile,
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: PasswordHashProfile) -> Self {
self.profile = profile;
self
}
#[must_use]
pub const fn policy(&self) -> PasswordPolicy {
self.policy
}
#[must_use]
pub const fn profile(&self) -> PasswordHashProfile {
self.profile
}
pub fn hash_password(&self, password: &str) -> Result<String, SecurityError> {
self.policy.validate_password(password)?;
let salt = SaltString::generate(&mut OsRng);
self.argon2()?
.hash_password(password.as_bytes(), &salt)
.map(|hash| hash.to_string())
.map_err(|_| SecurityError::PasswordHash)
}
pub fn dummy_password_hash(&self) -> Result<String, SecurityError> {
let salt =
SaltString::encode_b64(DUMMY_PASSWORD_SALT).map_err(|_| SecurityError::PasswordHash)?;
self.argon2()?
.hash_password(b"", &salt)
.map(|hash| hash.to_string())
.map_err(|_| SecurityError::PasswordHash)
}
pub fn verify_password(
&self,
password: &str,
password_hash: &str,
) -> Result<bool, SecurityError> {
self.verify_and_assess(password, password_hash)
.map(|verification| verification.verified())
}
pub fn verify_and_assess(
&self,
password: &str,
password_hash: &str,
) -> Result<PasswordVerification, SecurityError> {
self.policy.validate_password(password)?;
let parsed =
PasswordHash::new(password_hash).map_err(|_| SecurityError::InvalidPasswordHash)?;
let assessment = self.assess_parsed_hash(&parsed);
match self.argon2()?.verify_password(password.as_bytes(), &parsed) {
Ok(()) => Ok(PasswordVerification {
assessment,
verified: true,
}),
Err(argon2::password_hash::Error::Password) => Ok(PasswordVerification {
assessment,
verified: false,
}),
Err(argon2::password_hash::Error::Algorithm) => {
Err(SecurityError::UnsupportedPasswordHash)
}
Err(_) => Err(SecurityError::PasswordVerify),
}
}
pub fn assess_password_hash(
&self,
password_hash: &str,
) -> Result<PasswordHashAssessment, SecurityError> {
let parsed =
PasswordHash::new(password_hash).map_err(|_| SecurityError::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.argon2id_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<'_>, SecurityError> {
Ok(Argon2::new(
Algorithm::Argon2id,
Version::V0x13,
self.profile.argon2id_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, PasswordHashAlgorithm, PasswordHashProfile, PasswordPolicy,
PasswordService, SecurityError,
};
#[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_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(SecurityError::InvalidPasswordHash)));
}
#[test]
fn marks_weaker_hashes_for_rehash_after_successful_verification() {
let weak_profile =
PasswordHashProfile::argon2id(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());
}
#[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(SecurityError::PasswordTooLong { max: 4 })
));
assert!(matches!(
service.verify_password("12345", "not-a-password-hash"),
Err(SecurityError::PasswordTooLong { max: 4 })
));
}
#[test]
fn rejects_invalid_password_policy() {
assert!(matches!(
PasswordPolicy::new(0),
Err(SecurityError::InvalidPasswordPolicy)
));
}
#[test]
fn rejects_invalid_argon2id_profile() {
assert!(matches!(
Argon2idProfile::new(0, 2, 1, 32),
Err(SecurityError::InvalidPasswordHashProfile)
));
assert!(matches!(
Argon2idProfile::new(8, 0, 1, 32),
Err(SecurityError::InvalidPasswordHashProfile)
));
assert!(matches!(
Argon2idProfile::new(8, 1, 0, 32),
Err(SecurityError::InvalidPasswordHashProfile)
));
assert!(matches!(
Argon2idProfile::new(8, 1, 1, 1),
Err(SecurityError::InvalidPasswordHashProfile)
));
}
}