use std::{fmt, sync::Arc};
use thiserror::Error;
use crate::result::{ClassifyError, ErrorCode, ErrorKind};
#[cfg(feature = "password-common")]
mod common_passwords;
#[derive(Clone, PartialEq, Eq)]
pub struct PasswordPolicy {
min_length: usize,
check_repeated_characters: bool,
blocklist: Arc<[String]>,
#[cfg(feature = "password-common")]
common_passwords: bool,
}
impl PasswordPolicy {
pub fn new(min_length: usize) -> Result<Self, PasswordPolicyError> {
if min_length == 0 {
return Err(PasswordPolicyError::InvalidMinimumLength);
}
Ok(Self {
min_length,
check_repeated_characters: false,
blocklist: Arc::from([]),
#[cfg(feature = "password-common")]
common_passwords: false,
})
}
#[must_use]
pub const fn min_length(&self) -> usize {
self.min_length
}
#[must_use]
pub fn with_repeated_character_check(mut self, enabled: bool) -> Self {
self.check_repeated_characters = enabled;
self
}
#[must_use]
pub const fn repeated_character_check_enabled(&self) -> bool {
self.check_repeated_characters
}
#[must_use]
pub fn with_blocklist(mut self, passwords: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
let mut blocklist: Vec<_> = passwords
.into_iter()
.map(|password| password.as_ref().to_ascii_lowercase())
.collect();
blocklist.sort_unstable();
blocklist.dedup();
self.blocklist = blocklist.into();
self
}
#[cfg(feature = "password-common")]
#[cfg_attr(docsrs, doc(cfg(feature = "password-common")))]
#[must_use]
pub fn with_common_passwords(mut self, enabled: bool) -> Self {
self.common_passwords = enabled;
self
}
#[cfg(feature = "password-common")]
#[cfg_attr(docsrs, doc(cfg(feature = "password-common")))]
#[must_use]
pub const fn common_passwords_enabled(&self) -> bool {
self.common_passwords
}
pub fn validate(&self, password: &str) -> Result<(), PasswordPolicyError> {
if password.chars().take(self.min_length).count() < self.min_length {
return Err(PasswordPolicyError::TooShort {
min: self.min_length,
});
}
if self.check_repeated_characters {
let mut characters = password.chars();
if let Some(first) = characters.next()
&& characters.next() == Some(first)
&& characters.all(|character| character == first)
{
return Err(PasswordPolicyError::RepeatedCharacter);
}
}
if contains_password(&self.blocklist, password) {
return Err(PasswordPolicyError::BlockedPassword);
}
#[cfg(feature = "password-common")]
if self.common_passwords && contains_password(common_passwords::COMMON_PASSWORDS, password)
{
return Err(PasswordPolicyError::CommonPassword);
}
Ok(())
}
}
impl fmt::Debug for PasswordPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("PasswordPolicy");
debug
.field("min_length", &self.min_length)
.field("check_repeated_characters", &self.check_repeated_characters)
.field("blocklist_len", &self.blocklist.len());
#[cfg(feature = "password-common")]
debug.field("common_passwords", &self.common_passwords);
debug.finish()
}
}
fn contains_password(blocklist: &[impl AsRef<str>], password: &str) -> bool {
blocklist
.binary_search_by(|entry| {
entry
.as_ref()
.bytes()
.cmp(password.bytes().map(|byte| byte.to_ascii_lowercase()))
})
.is_ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PasswordPolicyError {
#[error("password minimum length must be greater than zero")]
InvalidMinimumLength,
#[error("password must contain at least {min} characters")]
TooShort {
min: usize,
},
#[error("password must not consist of a single repeated character")]
RepeatedCharacter,
#[error("password is blocked by the application")]
BlockedPassword,
#[error("password is too common")]
CommonPassword,
}
impl ClassifyError for PasswordPolicyError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal(match self {
Self::InvalidMinimumLength => "invalid_password_minimum_length",
Self::TooShort { .. } => "password_too_short",
Self::RepeatedCharacter => "password_repeated_character",
Self::BlockedPassword => "password_blocked",
Self::CommonPassword => "password_too_common",
})
}
}
#[cfg(test)]
mod tests;