footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
//! Explicit admission checks for prospective passwords.

use std::{fmt, sync::Arc};

use thiserror::Error;

use crate::result::{ClassifyError, ErrorCode, ErrorKind};

#[cfg(feature = "password-common")]
mod common_passwords;

/// Rules for accepting a password when it is set, changed, or reset.
///
/// Call [`Self::validate`] explicitly before hashing a new password. Do not run
/// admission checks during login or automatic rehashing: changing these rules
/// or updating the bundled list must not invalidate existing credentials.
/// `PasswordService` does not apply these rules.
///
/// Length is measured in Unicode scalar values (`str::chars`), not UTF-8 bytes
/// or grapheme clusters. Blocklists compare the **entire** password, ignoring
/// only ASCII case. Whitespace and non-ASCII characters remain significant;
/// there is no trimming, Unicode normalization, or substring matching. An
/// optional repeated-character check compares Unicode scalar values exactly,
/// including case, and is disabled by default. Validation never changes the
/// password passed to hashing.
/// Applications that normalize Unicode must apply the same normalization before
/// admission, hashing, and login verification.
///
/// The caller chooses the minimum length for its authentication context. For
/// example, NIST SP 800-63B-4 requires 15 characters for single-factor passwords
/// and at least eight when passwords are only used as part of MFA. Passing a
/// policy does not establish password strength or replace login rate limiting.
/// See the [password verifier requirements](https://pages.nist.gov/800-63-4/sp800-63b/authenticators/#passwordver).
///
/// This type performs no I/O. Custom entries are copied, ASCII-folded, sorted,
/// and deduplicated once when configured; cloning shares that immutable list.
/// Validation uses binary search without allocating a copy of the password.
/// The optional built-in list is shared static data and is **disabled by
/// default**, including when `password-common` is enabled by another dependency.
/// Neither `password-policy` nor `password-common` enables password hashing.
///
/// ```rust
/// use footing::auth::{PasswordPolicy, PasswordPolicyError};
///
/// let policy = PasswordPolicy::new(15)?
///     .with_blocklist(["our-service-name", "organization-name"]);
/// assert_eq!(policy.validate("OUR-SERVICE-NAME"), Err(PasswordPolicyError::BlockedPassword));
/// policy.validate("a unique passphrase containing ordinary words")?;
/// # Ok::<(), PasswordPolicyError>(())
/// ```
///
/// Validating before storage (requires both `password-policy` and `password`):
///
/// ```rust
/// # #[cfg(feature = "password")]
/// # {
/// use footing::auth::{PasswordLimits, PasswordPolicy, PasswordService};
///
/// let policy = PasswordPolicy::new(15)?;
/// let service = PasswordService::new().with_limits(PasswordLimits::new(1024)?);
/// let password = "a distinct phrase for this account";
/// policy.validate(password)?;
/// let stored_hash = service.hash_password(password)?;
/// // On login, only verify the stored credential.
/// assert!(service.verify_password(password, &stored_hash)?);
/// # }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[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 {
    /// Creates a policy that only checks the explicit minimum length.
    ///
    /// Returns [`PasswordPolicyError::InvalidMinimumLength`] for zero. There is
    /// no implicit minimum or maximum length. Bound request sizes at the
    /// application boundary; password storage has its own byte/resource limits.
    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,
        })
    }

    /// Returns the minimum number of Unicode scalar values.
    #[must_use]
    pub const fn min_length(&self) -> usize {
        self.min_length
    }

    /// Enables or disables rejection of a single repeated character; disabled by default.
    ///
    /// Rejects a password only when it contains at least two Unicode scalar
    /// values and all of them are identical. Equality is case-sensitive: `aa`
    /// and `éé` are rejected, while `Aa` and `abab` are not. A repeated sequence
    /// of `e` plus a combining accent is also not a single repeated scalar.
    /// No case folding, trimming, or Unicode normalization is performed.
    ///
    /// This check is independent of both blocklists and requires only
    /// `password-policy`. It scans the input without allocating or retaining a
    /// password copy. It is an optional application restriction, not a NIST
    /// requirement or a general password-strength assessment. Like other
    /// admission rules, apply it only when setting, changing, or resetting a
    /// password, never during login or automatic rehashing.
    ///
    /// ```rust
    /// use footing::auth::{PasswordPolicy, PasswordPolicyError};
    ///
    /// let policy = PasswordPolicy::new(15)?.with_repeated_character_check(true);
    /// assert_eq!(
    ///     policy.validate("aaaaaaaaaaaaaaa"),
    ///     Err(PasswordPolicyError::RepeatedCharacter),
    /// );
    /// policy.validate("a distinct phrase with repeated letters")?;
    /// # Ok::<(), PasswordPolicyError>(())
    /// ```
    #[must_use]
    pub fn with_repeated_character_check(mut self, enabled: bool) -> Self {
        self.check_repeated_characters = enabled;
        self
    }

    /// Whether rejection of a single repeated character is enabled.
    #[must_use]
    pub const fn repeated_character_check_enabled(&self) -> bool {
        self.check_repeated_characters
    }

    /// Replaces the custom blocklist, independently of the built-in list.
    ///
    /// Entries are complete passwords, compared with ASCII case ignored.
    /// Surrounding whitespace is preserved. Duplicate entries after ASCII case
    /// folding are stored once. An empty iterator clears the custom list.
    /// The application owns loading and refreshing these values; this method
    /// copies them and never reads files or performs network requests.
    #[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
    }

    /// Enables or disables the bundled common-password list; disabled by default.
    ///
    /// Requires `password-common`. Turning this off does not clear or disable
    /// the custom blocklist. The fixed offline snapshot covers common passwords,
    /// not every compromised password or every language. Dataset updates may
    /// change admission decisions but never change stored-password verification.
    ///
    /// The bundled list contains 19,640 entries from
    /// [Django's pinned snapshot](https://github.com/django/django/blob/727731d76d9dfd5304d536478d862778f6dd6d9b/django/contrib/auth/common-passwords.txt.gz),
    /// originally compiled by [Royce Williams](https://gist.github.com/roycewilliams/226886fd01572964e1431ac8afc999ce).
    /// It is sorted, deduplicated and
    /// ASCII-folded ahead of time, stored as shared static strings, and requires
    /// no initialization or decompression. Source comments retain the pinned
    /// version, checksums, regeneration steps, and the
    /// [Django license](https://github.com/django/django/blob/727731d76d9dfd5304d536478d862778f6dd6d9b/LICENSE).
    ///
    /// ```rust
    /// use footing::auth::{PasswordPolicy, PasswordPolicyError};
    ///
    /// let policy = PasswordPolicy::new(8)?
    ///     .with_blocklist(["our-service"])
    ///     .with_common_passwords(true);
    /// assert_eq!(policy.validate("PaSsWoRd"), Err(PasswordPolicyError::CommonPassword));
    /// policy.validate("a unique password-containing passphrase")?;
    /// # Ok::<(), PasswordPolicyError>(())
    /// ```
    #[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
    }

    /// Whether the built-in list is enabled on this policy.
    #[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
    }

    /// Checks a prospective password without changing or retaining it.
    ///
    /// Returns the first rejection in this order: minimum length, repeated
    /// character check, custom blocklist, built-in common-password list. Optional
    /// checks run only when enabled. Errors contain no password or matching
    /// entry; applications can map the variants to localized messages.
    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()
}

/// Configuration and admission failures without password contents.
///
/// Errors expose only the reason and, for length failures, the configured
/// minimum. Neither [`std::fmt::Debug`] nor [`std::fmt::Display`] reveals the
/// candidate or the matching blocklist entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PasswordPolicyError {
    /// A minimum length of zero was requested.
    #[error("password minimum length must be greater than zero")]
    InvalidMinimumLength,
    /// The password contains fewer Unicode scalar values than required.
    #[error("password must contain at least {min} characters")]
    TooShort {
        /// The configured minimum number of Unicode scalar values.
        min: usize,
    },
    /// The password consists of at least two identical Unicode scalar values.
    #[error("password must not consist of a single repeated character")]
    RepeatedCharacter,
    /// The entire password matches an entry in the custom blocklist.
    #[error("password is blocked by the application")]
    BlockedPassword,
    /// The entire password matches an entry in the built-in common-password list.
    #[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;