footing 0.5.1

Feature-gated foundations for Rust backend services
Documentation
//! Bounded Tokio execution of synchronous password operations.

use std::{
    fmt,
    sync::{Arc, OnceLock},
    time::{Duration, Instant},
};

use thiserror::Error;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

use super::{PasswordError, PasswordService, PasswordVerification};
use crate::{
    result::{ClassifyError, ErrorCode, ErrorKind},
    secret::{ExposeSecret, SecretString},
};

/// Limits shared by every clone of a [`TokioPasswordService`].
///
/// Running work includes tasks submitted to Tokio's blocking pool but not yet
/// started. Choose concurrency for the CPU and memory costs of both the current
/// profile and accepted historical hashes. These limits bound task counts, not
/// Argon2 parameters; use [`super::PasswordVerificationLimits`] for those.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordWorkLimits {
    concurrency: usize,
    max_waiters: usize,
    wait_timeout: Duration,
}

impl PasswordWorkLimits {
    /// Allows up to `concurrency` submitted operations and rejects excess work
    /// immediately. The count must be in `1..=Semaphore::MAX_PERMITS`.
    pub const fn new(concurrency: usize) -> Result<Self, TokioPasswordError> {
        if concurrency == 0 || concurrency > Semaphore::MAX_PERMITS {
            return Err(TokioPasswordError::InvalidConcurrency);
        }
        Ok(Self {
            concurrency,
            max_waiters: 0,
            wait_timeout: Duration::ZERO,
        })
    }

    /// Enables a bounded FIFO wait queue. Both arguments must be nonzero;
    /// `max_waiters` must not exceed `Semaphore::MAX_PERMITS`, and the timeout
    /// must fit in a monotonic deadline. The timeout covers admission only.
    pub fn with_queue(
        mut self,
        max_waiters: usize,
        wait_timeout: Duration,
    ) -> Result<Self, TokioPasswordError> {
        if max_waiters == 0
            || max_waiters > Semaphore::MAX_PERMITS
            || wait_timeout.is_zero()
            || Instant::now().checked_add(wait_timeout).is_none()
        {
            return Err(TokioPasswordError::InvalidQueue);
        }
        self.max_waiters = max_waiters;
        self.wait_timeout = wait_timeout;
        Ok(self)
    }

    /// Maximum number of submitted or running blocking tasks.
    #[must_use]
    pub const fn concurrency(&self) -> usize {
        self.concurrency
    }

    /// Maximum queued callers; zero means immediate rejection when busy.
    #[must_use]
    pub const fn max_waiters(&self) -> usize {
        self.max_waiters
    }

    /// Maximum admission wait; zero when queuing is disabled.
    #[must_use]
    pub const fn wait_timeout(&self) -> Duration {
        self.wait_timeout
    }
}

/// Tokio adapter with one shared, bounded budget for all password operations.
///
/// Construct once at startup and clone it into handlers. Each task acquires a
/// permit **before** `spawn_blocking` and owns that permit until computation
/// finishes, even if its caller is cancelled. Verification and rehashing run
/// together under one permit. Cancelling a queued caller removes it from the
/// queue without starting work. Cancelling dispatched work does not stop Argon2.
///
/// Password admission rules are independent of this adapter. Validate new
/// passwords before calling it when setting, changing, or resetting credentials;
/// verification and rehashing continue to accept existing passwords regardless
/// of changes to those rules.
///
/// Passwords and generated hashes use [`SecretString`] to redact formatting and
/// zeroize owned strings on drop. Persist replacement hashes in application code,
/// using a conditional update against the hash that was verified to avoid
/// overwriting a concurrent password change. Do not hold a database transaction
/// while waiting or hashing.
///
/// ```rust
/// use std::time::Duration;
/// use footing::auth::{PasswordService, PasswordWorkLimits, TokioPasswordService};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let limits = PasswordWorkLimits::new(2)?
///     .with_queue(8, Duration::from_millis(100))?;
/// let passwords = TokioPasswordService::new(PasswordService::new(), limits);
/// let hash = passwords.hash_password("correct horse battery staple".into()).await?;
/// let result = passwords.clone()
///     .verify_and_rehash("correct horse battery staple".into(), hash).await?;
/// assert!(result.verification().verified());
/// # Ok(())
/// # }
/// ```
///
/// Async methods require a Tokio runtime. Queuing additionally requires its time
/// driver. The synchronous `password` feature remains independent of Tokio.
#[derive(Clone)]
pub struct TokioPasswordService {
    inner: Arc<Inner>,
}

struct Inner {
    service: PasswordService,
    limits: PasswordWorkLimits,
    running: Arc<Semaphore>,
    waiting: Semaphore,
    dummy_hash: OnceLock<Result<SecretString, PasswordError>>,
}

impl fmt::Debug for TokioPasswordService {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TokioPasswordService")
            .field("service", &self.inner.service)
            .field("limits", &self.inner.limits)
            .finish_non_exhaustive()
    }
}

impl TokioPasswordService {
    /// Creates one execution budget. Clones share it and the cached dummy hash.
    #[must_use]
    pub fn new(service: PasswordService, limits: PasswordWorkLimits) -> Self {
        Self {
            inner: Arc::new(Inner {
                service,
                limits,
                running: Arc::new(Semaphore::new(limits.concurrency)),
                waiting: Semaphore::new(limits.max_waiters),
                dummy_hash: OnceLock::new(),
            }),
        }
    }

    /// Returns the immutable admission limits shared by this service's clones.
    #[must_use]
    pub fn limits(&self) -> PasswordWorkLimits {
        self.inner.limits
    }

    /// Generates a PHC-formatted hash on the blocking pool.
    pub async fn hash_password(
        &self,
        password: SecretString,
    ) -> Result<SecretString, TokioPasswordError> {
        self.run(password, |inner, password| {
            inner.service.hash_password(password).map(SecretString::new)
        })
        .await
    }

    /// Verifies without generating a replacement hash.
    pub async fn verify_password(
        &self,
        password: SecretString,
        password_hash: SecretString,
    ) -> Result<bool, TokioPasswordError> {
        self.verify_and_assess(password, password_hash)
            .await
            .map(|verification| verification.verified())
    }

    /// Verifies and reports whether the stored hash needs upgrading.
    pub async fn verify_and_assess(
        &self,
        password: SecretString,
        password_hash: SecretString,
    ) -> Result<PasswordVerification, TokioPasswordError> {
        self.run(password, move |inner, password| {
            inner
                .service
                .verify_and_assess(password, password_hash.expose_secret())
        })
        .await
    }

    /// Verifies and, only on a successful verification that needs upgrading,
    /// computes a replacement hash under the same permit.
    pub async fn verify_and_rehash(
        &self,
        password: SecretString,
        password_hash: SecretString,
    ) -> Result<PasswordRehash, TokioPasswordError> {
        self.run(password, move |inner, password| {
            let verification = inner
                .service
                .verify_and_assess(password, password_hash.expose_secret())?;
            let replacement_hash = if verification.needs_rehash() {
                Some(SecretString::new(inner.service.hash_password(password)?))
            } else {
                None
            };
            Ok(PasswordRehash {
                verification,
                replacement_hash,
            })
        })
        .await
    }

    /// Performs verification work for an unknown account using a cached dummy
    /// hash. `Ok(())` means the work completed, **not** successful authentication.
    ///
    /// The first call also generates the dummy hash, under the same permit.
    /// Subsequent calls, including through clones, reuse it. Its cost matches the
    /// configured generation profile, not every historical hash's cost.
    /// Call once during startup to pay initialization cost before serving requests.
    pub async fn verify_dummy_password(
        &self,
        password: SecretString,
    ) -> Result<(), TokioPasswordError> {
        self.run(password, |inner, password| {
            let hash = inner
                .dummy_hash
                .get_or_init(|| inner.service.dummy_password_hash().map(SecretString::new))
                .as_ref()
                .map_err(Clone::clone)?;
            inner
                .service
                .verify_password(password, hash.expose_secret())?;
            Ok(())
        })
        .await
    }

    async fn acquire(&self) -> Result<OwnedSemaphorePermit, TokioPasswordError> {
        if let Ok(permit) = self.inner.running.clone().try_acquire_owned() {
            return Ok(permit);
        }
        // This guard bounds waiting futures as well as running tasks. Cancellation
        // or a deadline releases the queue slot before any work is dispatched.
        let _waiting = self
            .inner
            .waiting
            .try_acquire()
            .map_err(|_| TokioPasswordError::Busy)?;
        tokio::time::timeout(
            self.inner.limits.wait_timeout,
            self.inner.running.clone().acquire_owned(),
        )
        .await
        .map_err(|_| TokioPasswordError::WaitTimeout)?
        .map_err(|_| TokioPasswordError::Busy)
    }

    async fn run<T: Send + 'static>(
        &self,
        password: SecretString,
        operation: impl FnOnce(&Inner, &str) -> Result<T, PasswordError> + Send + 'static,
    ) -> Result<T, TokioPasswordError> {
        self.inner
            .service
            .limits()
            .validate_password(password.expose_secret())?;
        let runtime =
            tokio::runtime::Handle::try_current().map_err(|_| TokioPasswordError::NoRuntime)?;
        let permit = self.acquire().await?;
        let inner = self.inner.clone();
        runtime
            .spawn_blocking(move || {
                let _permit = permit;
                operation(&inner, password.expose_secret())
            })
            .await
            .map_err(TokioPasswordError::Task)?
            .map_err(TokioPasswordError::Password)
    }
}

/// Verification outcome and an optional replacement hash for the application to
/// persist. A failed verification never contains a replacement hash.
#[derive(Debug)]
pub struct PasswordRehash {
    verification: PasswordVerification,
    replacement_hash: Option<SecretString>,
}

impl PasswordRehash {
    /// Returns the verification and assessment of the original stored hash.
    #[must_use]
    pub const fn verification(&self) -> PasswordVerification {
        self.verification
    }

    /// Returns the replacement hash, with redacted formatting.
    #[must_use]
    pub const fn replacement_hash(&self) -> Option<&SecretString> {
        self.replacement_hash.as_ref()
    }

    /// Transfers the result and replacement hash to application code.
    #[must_use]
    pub fn into_parts(self) -> (PasswordVerification, Option<SecretString>) {
        (self.verification, self.replacement_hash)
    }
}

/// Admission, scheduling, or password failures. Default formatting does not
/// include a blocking task's panic payload; its source is available explicitly.
#[derive(Error)]
#[non_exhaustive]
pub enum TokioPasswordError {
    /// Concurrency is zero or exceeds Tokio's supported semaphore size.
    #[error("password concurrency is outside the supported range")]
    InvalidConcurrency,
    /// Queue size or timeout is zero or outside the supported range.
    #[error("password wait queue limits are invalid")]
    InvalidQueue,
    /// All running and waiting slots are occupied.
    #[error("password service is busy")]
    Busy,
    /// No running permit became available before the admission deadline.
    #[error("password admission timed out")]
    WaitTimeout,
    /// The operation was polled outside a Tokio runtime.
    #[error("password operation requires a Tokio runtime")]
    NoRuntime,
    /// The blocking task panicked or was cancelled by runtime shutdown.
    #[error("password worker failed")]
    Task(#[source] tokio::task::JoinError),
    /// Password limits, hash format, or cryptographic operation failure.
    #[error(transparent)]
    Password(#[from] PasswordError),
}

impl fmt::Debug for TokioPasswordError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TokioPasswordError")
            .field("code", &self.error_code())
            .finish_non_exhaustive()
    }
}

impl ClassifyError for TokioPasswordError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidConcurrency | Self::InvalidQueue => ErrorKind::Validation,
            Self::Busy => ErrorKind::Unavailable,
            Self::WaitTimeout => ErrorKind::Timeout,
            Self::NoRuntime | Self::Task(_) => ErrorKind::Internal,
            Self::Password(error) => error.error_kind(),
        }
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::InvalidConcurrency => "password_invalid_concurrency",
            Self::InvalidQueue => "password_invalid_queue",
            Self::Busy => "password_service_busy",
            Self::WaitTimeout => "password_admission_timed_out",
            Self::NoRuntime => "password_tokio_runtime_required",
            Self::Task(_) => "password_worker_failed",
            Self::Password(error) => return error.error_code(),
        })
    }
}

#[cfg(test)]
mod tests;