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},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordWorkLimits {
concurrency: usize,
max_waiters: usize,
wait_timeout: Duration,
}
impl PasswordWorkLimits {
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,
})
}
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)
}
#[must_use]
pub const fn concurrency(&self) -> usize {
self.concurrency
}
#[must_use]
pub const fn max_waiters(&self) -> usize {
self.max_waiters
}
#[must_use]
pub const fn wait_timeout(&self) -> Duration {
self.wait_timeout
}
}
#[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 {
#[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(),
}),
}
}
#[must_use]
pub fn limits(&self) -> PasswordWorkLimits {
self.inner.limits
}
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
}
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())
}
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
}
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
}
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);
}
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
.policy()
.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)
}
}
#[derive(Debug)]
pub struct PasswordRehash {
verification: PasswordVerification,
replacement_hash: Option<SecretString>,
}
impl PasswordRehash {
#[must_use]
pub const fn verification(&self) -> PasswordVerification {
self.verification
}
#[must_use]
pub const fn replacement_hash(&self) -> Option<&SecretString> {
self.replacement_hash.as_ref()
}
#[must_use]
pub fn into_parts(self) -> (PasswordVerification, Option<SecretString>) {
(self.verification, self.replacement_hash)
}
}
#[derive(Error)]
#[non_exhaustive]
pub enum TokioPasswordError {
#[error("password concurrency is outside the supported range")]
InvalidConcurrency,
#[error("password wait queue limits are invalid")]
InvalidQueue,
#[error("password service is busy")]
Busy,
#[error("password admission timed out")]
WaitTimeout,
#[error("password operation requires a Tokio runtime")]
NoRuntime,
#[error("password worker failed")]
Task(#[source] tokio::task::JoinError),
#[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;