pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
//! Runtime-neutral proof-of-control challenges.
//!
//! Confirmation is an explicit state-changing workflow. It is not passive
//! validation and does not alter [`crate::Verdict`]. Applications provide the
//! durable store and message sender; Pata owns token generation, hashing,
//! expiry, and the atomic-consumption contract.

use std::{fmt, future::Future, pin::Pin, time::SystemTime};

use secrecy::{ExposeSecret as _, SecretString};
use sha2::{Digest as _, Sha256};
use subtle::ConstantTimeEq as _;

use crate::Address;

const TOKEN_BYTES: usize = 32;

/// A boxed asynchronous confirmation operation.
pub type ConfirmationFuture<'operation, T> =
    Pin<Box<dyn Future<Output = Result<T, ConfirmationError>> + Send + 'operation>>;

/// The opaque lookup key retained by a confirmation store.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct ChallengeId([u8; 32]);

impl fmt::Debug for ChallengeId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ChallengeId([redacted])")
    }
}

impl ChallengeId {
    /// Returns the stable bytes used to index durable challenge state.
    ///
    /// The identifier does not reveal the token. Do not expose it as public
    /// telemetry.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }
}

/// Durable state written before a challenge message is sent.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PendingConfirmation {
    id: ChallengeId,
    address: Address,
    expires_at: SystemTime,
}

impl PendingConfirmation {
    /// Returns the opaque store key.
    #[must_use]
    pub const fn id(&self) -> &ChallengeId {
        &self.id
    }

    /// Returns the address whose control is being challenged.
    #[must_use]
    pub const fn address(&self) -> &Address {
        &self.address
    }

    /// Returns when the challenge expires.
    #[must_use]
    pub const fn expires_at(&self) -> SystemTime {
        self.expires_at
    }
}

/// A transport-neutral message containing a one-time token.
pub struct ChallengeMessage {
    address: Address,
    token: SecretString,
    expires_at: SystemTime,
}

impl ChallengeMessage {
    /// Returns the intended recipient.
    #[must_use]
    pub const fn address(&self) -> &Address {
        &self.address
    }

    /// Exposes the token for placement in a confirmation link or form.
    ///
    /// Treat this value as a credential. Do not log it or put it in analytics.
    #[must_use]
    pub fn token(&self) -> &str {
        self.token.expose_secret()
    }

    /// Returns when the challenge expires.
    #[must_use]
    pub const fn expires_at(&self) -> SystemTime {
        self.expires_at
    }
}

impl fmt::Debug for ChallengeMessage {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ChallengeMessage")
            .field("address", &self.address)
            .field("token", &"[redacted]")
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

/// Durable storage for single-use confirmation challenges.
pub trait ChallengeStore: Send + Sync {
    /// Inserts or supersedes a pending challenge for the address.
    fn put<'operation>(
        &'operation self,
        pending: PendingConfirmation,
    ) -> ConfirmationFuture<'operation, ()>;

    /// Atomically consumes a live challenge matching `id`.
    ///
    /// Implementations must return a matching challenge at most once and must
    /// reject expired or superseded state. Atomic consumption is what makes a
    /// successfully presented token single-use across concurrent callers.
    fn consume<'operation>(
        &'operation self,
        id: &'operation ChallengeId,
        now: SystemTime,
    ) -> ConfirmationFuture<'operation, Option<PendingConfirmation>>;
}

/// Delivery for a transport-neutral challenge message.
pub trait ChallengeSender: Send + Sync {
    /// Sends one challenge without treating provider acceptance as proof.
    fn send<'operation>(
        &'operation self,
        message: &'operation ChallengeMessage,
    ) -> ConfirmationFuture<'operation, ()>;
}

/// Proof that a one-time challenge was atomically consumed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Confirmation {
    address: Address,
    confirmed_at: SystemTime,
}

impl Confirmation {
    /// Returns the address whose control was demonstrated.
    #[must_use]
    pub const fn address(&self) -> &Address {
        &self.address
    }

    /// Returns the caller-supplied time at which the proof was accepted.
    #[must_use]
    pub const fn confirmed_at(&self) -> SystemTime {
        self.confirmed_at
    }
}

/// Coordinates storage and delivery of proof-of-control challenges.
#[derive(Clone, Copy, Debug, Default)]
pub struct ConfirmationService;

impl ConfirmationService {
    /// Creates, persists, then sends a fresh challenge.
    ///
    /// State is stored before delivery so a successfully delivered token is
    /// never unverifiable. A delivery error leaves expiring state that callers
    /// may explicitly supersede by issuing another challenge. Cancellation
    /// after storage can leave the same expiring state.
    pub async fn send<S, D>(
        &self,
        store: &S,
        sender: &D,
        address: Address,
        expires_at: SystemTime,
    ) -> Result<(), ConfirmationError>
    where
        S: ChallengeStore + ?Sized,
        D: ChallengeSender + ?Sized,
    {
        if expires_at <= SystemTime::now() {
            return Err(ConfirmationError::InvalidExpiration);
        }
        let message = issue(address, expires_at)?;
        let pending = PendingConfirmation {
            id: token_id(message.token()),
            address: message.address.clone(),
            expires_at,
        };
        store.put(pending).await?;
        sender.send(&message).await
    }

    /// Atomically verifies and consumes a presented token.
    ///
    /// Cancellation during the store operation can consume a token without
    /// returning its confirmation. This preserves single use but requires the
    /// application to treat an interrupted confirmation as unresolved.
    pub async fn confirm<S>(
        &self,
        store: &S,
        token: &str,
        now: SystemTime,
    ) -> Result<Option<Confirmation>, ConfirmationError>
    where
        S: ChallengeStore + ?Sized,
    {
        if !valid_token(token) {
            return Ok(None);
        }
        let expected = token_id(token);
        let Some(pending) = store.consume(&expected, now).await? else {
            return Ok(None);
        };
        if now >= pending.expires_at || !bool::from(expected.0.ct_eq(&pending.id.0)) {
            return Ok(None);
        }
        Ok(Some(Confirmation {
            address: pending.address,
            confirmed_at: now,
        }))
    }
}

/// A failure in challenge creation, storage, or delivery.
#[derive(Clone, Copy, Debug, thiserror::Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum ConfirmationError {
    /// The challenge would already be expired when issued.
    #[error("confirmation expiration must be in the future")]
    InvalidExpiration,
    /// Secure operating-system randomness was unavailable.
    #[error("secure challenge randomness is unavailable")]
    Entropy,
    /// Durable challenge state could not be written or consumed.
    #[error("confirmation state operation failed")]
    Storage,
    /// The challenge message could not be submitted for delivery.
    #[error("confirmation message delivery failed")]
    Delivery,
}

fn issue(address: Address, expires_at: SystemTime) -> Result<ChallengeMessage, ConfirmationError> {
    let mut random = [0_u8; TOKEN_BYTES];
    getrandom::fill(&mut random).map_err(|_| ConfirmationError::Entropy)?;
    Ok(ChallengeMessage {
        address,
        token: SecretString::from(hex(&random)),
        expires_at,
    })
}

fn token_id(token: &str) -> ChallengeId {
    ChallengeId(Sha256::digest(token.as_bytes()).into())
}

fn valid_token(token: &str) -> bool {
    token.len() == TOKEN_BYTES * 2
        && token
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
        output.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
    }
    output
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use futures_executor::block_on;

    use super::*;

    #[derive(Default)]
    struct MemoryStore(Mutex<Option<PendingConfirmation>>);

    impl ChallengeStore for MemoryStore {
        fn put<'a>(&'a self, pending: PendingConfirmation) -> ConfirmationFuture<'a, ()> {
            Box::pin(async move {
                *self.0.lock().unwrap() = Some(pending);
                Ok(())
            })
        }

        fn consume<'a>(
            &'a self,
            id: &'a ChallengeId,
            now: SystemTime,
        ) -> ConfirmationFuture<'a, Option<PendingConfirmation>> {
            Box::pin(async move {
                let mut state = self.0.lock().unwrap();
                let matches = state
                    .as_ref()
                    .is_some_and(|pending| pending.id == *id && pending.expires_at > now);
                Ok(matches.then(|| state.take().unwrap()))
            })
        }
    }

    #[derive(Default)]
    struct MemorySender(Mutex<Option<String>>);

    impl ChallengeSender for MemorySender {
        fn send<'a>(&'a self, message: &'a ChallengeMessage) -> ConfirmationFuture<'a, ()> {
            Box::pin(async move {
                *self.0.lock().unwrap() = Some(message.token().to_owned());
                Ok(())
            })
        }
    }

    #[test]
    fn token_is_single_use_and_debug_redacted() {
        block_on(async {
            let store = MemoryStore::default();
            let sender = MemorySender::default();
            let now = SystemTime::now();
            let expires = now + std::time::Duration::from_secs(300);
            ConfirmationService
                .send(
                    &store,
                    &sender,
                    Address::parse("maya@example.com").unwrap(),
                    expires,
                )
                .await
                .unwrap();

            let token = sender.0.lock().unwrap().clone().unwrap();
            assert!(!format!("{:?}", store.0.lock().unwrap()).contains(&token));
            let confirmation = ConfirmationService
                .confirm(&store, &token, now)
                .await
                .unwrap();
            assert!(confirmation.is_some());
            assert!(
                ConfirmationService
                    .confirm(&store, &token, now)
                    .await
                    .unwrap()
                    .is_none()
            );
        });
    }

    #[test]
    fn malformed_token_does_not_consume_state() {
        block_on(async {
            let store = MemoryStore::default();
            assert!(
                ConfirmationService
                    .confirm(&store, "not-a-token", SystemTime::now())
                    .await
                    .unwrap()
                    .is_none()
            );
        });
    }

    #[test]
    fn expired_challenge_is_rejected_before_storage_or_delivery() {
        let store = MemoryStore::default();
        let sender = MemorySender::default();
        let result = block_on(ConfirmationService.send(
            &store,
            &sender,
            Address::parse("maya@example.com").unwrap(),
            SystemTime::UNIX_EPOCH,
        ));

        assert_eq!(result, Err(ConfirmationError::InvalidExpiration));
        assert!(store.0.lock().unwrap().is_none());
        assert!(sender.0.lock().unwrap().is_none());
    }
}