pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
use super::Validator;
use crate::{Error, Limits, Mode, Policy, Result, Timeouts};

#[cfg(feature = "dns")]
use crate::Network;
#[cfg(feature = "smtp")]
use crate::SmtpPolicy;

/// Builds a checked validator.
#[derive(Clone, Debug, Default)]
pub struct ValidatorBuilder {
    mode: Mode,
    policy: Policy,
    limits: Limits,
    timeouts: Timeouts,
    #[cfg(feature = "smtp")]
    smtp_policy: SmtpPolicy,
    #[cfg(feature = "smtp")]
    probe_identity: Option<String>,
    #[cfg(feature = "posture")]
    posture: bool,
    #[cfg(feature = "dns")]
    network: Option<Network>,
}

impl ValidatorBuilder {
    /// Selects the validation mode.
    #[must_use]
    pub fn mode(mut self, mode: Mode) -> Self {
        self.mode = mode;
        self
    }

    /// Selects the deterministic verdict policy.
    #[must_use]
    pub fn policy(mut self, policy: Policy) -> Self {
        self.policy = policy;
        self
    }

    /// Replaces resource bounds.
    #[must_use]
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Replaces time bounds.
    #[must_use]
    pub fn timeouts(mut self, timeouts: Timeouts) -> Self {
        self.timeouts = timeouts;
        self
    }

    /// Supplies runtime-neutral network capabilities.
    #[cfg(feature = "dns")]
    #[must_use]
    pub fn network(mut self, network: Network) -> Self {
        self.network = Some(network);
        self
    }

    /// Selects SMTP probing behavior.
    #[cfg(feature = "smtp")]
    #[must_use]
    pub fn smtp_policy(mut self, policy: SmtpPolicy) -> Self {
        self.smtp_policy = policy;
        self
    }

    /// Sets the multi-label DNS identity sent in `EHLO` and `HELO`.
    #[cfg(feature = "smtp")]
    pub fn probe_identity(mut self, identity: impl Into<String>) -> Result<Self> {
        let identity = identity.into();
        if identity.len() > crate::Address::MAX_INPUT_BYTES {
            return Err(Error::Configuration(
                "probe identity must be a DNS hostname",
            ));
        }
        let ascii = idna::domain_to_ascii_strict(&identity)
            .map_err(|_| Error::Configuration("probe identity must be a DNS hostname"))?;
        if ascii.is_empty()
            || ascii.len() > 253
            || !ascii.contains('.')
            || ascii.contains('@')
            || ascii.parse::<std::net::IpAddr>().is_ok()
            || ascii
                .split('.')
                .any(|label| label.is_empty() || label.len() > 63)
        {
            return Err(Error::Configuration(
                "probe identity must be a DNS hostname",
            ));
        }
        self.probe_identity = Some(ascii.to_ascii_lowercase());
        Ok(self)
    }

    /// Enables SPF, DMARC, MTA-STS, and TLS-RPT publication inspection.
    #[cfg(feature = "posture")]
    #[must_use]
    pub fn posture(mut self, enabled: bool) -> Self {
        self.posture = enabled;
        self
    }

    /// Finishes the validator configuration.
    pub fn build(self) -> Result<Validator> {
        self.validate()?;
        Ok(Validator {
            mode: self.mode,
            policy: self.policy,
            limits: self.limits,
            timeouts: self.timeouts,
            #[cfg(feature = "smtp")]
            smtp_policy: self.smtp_policy,
            #[cfg(feature = "smtp")]
            probe_identity: self.probe_identity,
            #[cfg(feature = "posture")]
            posture: self.posture,
            #[cfg(feature = "dns")]
            network: self.network,
        })
    }

    fn validate(&self) -> Result<()> {
        if self.limits.input_bytes() == 0 {
            return Err(Error::Configuration("input byte limit must be positive"));
        }
        if self.limits.input_bytes() > crate::Address::MAX_INPUT_BYTES {
            return Err(Error::Configuration(
                "input byte limit exceeds the parser safety bound",
            ));
        }
        if self.limits.concurrent_validations() == 0 {
            return Err(Error::Configuration(
                "concurrent validation limit must be positive",
            ));
        }
        if self.limits.concurrent_validations() > Limits::MAX_CONCURRENT_VALIDATIONS {
            return Err(Error::Configuration(
                "concurrent validation limit exceeds the supported maximum",
            ));
        }
        if self.timeouts.dns().is_zero()
            || self.timeouts.connect().is_zero()
            || self.timeouts.command().is_zero()
            || self.timeouts.total().is_zero()
        {
            return Err(Error::Configuration("timeouts must be positive"));
        }
        if self.timeouts.total() < self.timeouts.dns()
            || self.timeouts.total() < self.timeouts.connect()
            || self.timeouts.total() < self.timeouts.command()
        {
            return Err(Error::Configuration(
                "total timeout must cover each individual operation timeout",
            ));
        }
        let now = std::time::Instant::now();
        if [
            self.timeouts.dns(),
            self.timeouts.connect(),
            self.timeouts.command(),
            self.timeouts.total(),
        ]
        .into_iter()
        .any(|duration| now.checked_add(duration).is_none())
        {
            return Err(Error::Configuration(
                "timeouts exceed the monotonic clock range",
            ));
        }
        #[cfg(feature = "dns")]
        if self.mode != Mode::Local && self.network.is_none() {
            return Err(Error::Configuration(
                "the selected mode requires a configured network",
            ));
        }
        #[cfg(not(feature = "dns"))]
        if self.mode != Mode::Local {
            return Err(Error::Configuration(
                "the selected mode requires the dns feature",
            ));
        }
        #[cfg(not(feature = "smtp"))]
        if self.mode == Mode::Mailbox {
            return Err(Error::Configuration(
                "mailbox validation requires the smtp feature",
            ));
        }
        #[cfg(feature = "smtp")]
        if self.mode == Mode::Mailbox {
            let Some(network) = self.network.as_ref() else {
                return Err(Error::Configuration(
                    "mailbox validation requires a configured network",
                ));
            };
            if network.smtp().is_none() {
                return Err(Error::Configuration(
                    "mailbox validation requires connector and timer capabilities",
                ));
            }
            if self.smtp_policy.tls() == crate::TlsPolicy::Required && !network.has_tls() {
                return Err(Error::Configuration(
                    "required STARTTLS needs an authenticated TLS capability",
                ));
            }
            if self.probe_identity.is_none() {
                return Err(Error::Configuration(
                    "mailbox validation requires a probe identity",
                ));
            }
        }
        Ok(())
    }
}

#[cfg(all(test, feature = "smtp"))]
mod tests {
    use super::*;

    #[test]
    fn probe_identity_requires_a_multi_label_dns_form() {
        assert!(
            ValidatorBuilder::default()
                .probe_identity("validator.example")
                .is_ok()
        );
        assert!(
            ValidatorBuilder::default()
                .probe_identity("localhost")
                .is_err()
        );
        assert!(
            ValidatorBuilder::default()
                .probe_identity("127.0.0.1")
                .is_err()
        );
    }
}