pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
use std::time::Instant;

use crate::{Address, Limits, Mode, Policy, Report, Timeouts};

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

mod batch;
mod builder;
mod local;
mod network;

pub use builder::ValidatorBuilder;

/// A no-I/O description of the work a validator would perform.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Plan {
    mode: Mode,
    parses: bool,
    queries_domain: bool,
    may_disclose_address: bool,
    inspects_posture: bool,
    network_time_limit: Option<std::time::Duration>,
}

impl Plan {
    /// Returns the requested mode.
    #[must_use]
    pub const fn mode(&self) -> Mode {
        self.mode
    }

    /// Returns whether the input parsed successfully.
    #[must_use]
    pub const fn parses(&self) -> bool {
        self.parses
    }

    /// Returns whether execution would query the address domain.
    #[must_use]
    pub const fn queries_domain(&self) -> bool {
        self.queries_domain
    }

    /// Returns whether execution may disclose the complete address.
    #[must_use]
    pub const fn may_disclose_address(&self) -> bool {
        self.may_disclose_address
    }

    /// Returns whether optional domain-security records would be inspected.
    #[must_use]
    pub const fn inspects_posture(&self) -> bool {
        self.inspects_posture
    }

    /// Returns the total network time limit when the plan performs I/O.
    #[must_use]
    pub const fn network_time_limit(&self) -> Option<std::time::Duration> {
        self.network_time_limit
    }
}

/// An immutable, reusable address validator.
#[derive(Clone, Debug)]
pub struct Validator {
    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 Validator {
    /// Starts a checked validator configuration.
    #[must_use]
    pub fn builder() -> ValidatorBuilder {
        ValidatorBuilder::default()
    }

    /// Creates a validator that performs no network I/O.
    #[must_use]
    pub fn local() -> Self {
        ValidatorBuilder::default()
            .build()
            .expect("the default local validator is valid")
    }

    /// Describes the configured validation without performing network I/O.
    #[must_use]
    pub fn plan(&self, input: impl AsRef<str>) -> Plan {
        let address = (input.as_ref().len() <= self.limits.input_bytes())
            .then(|| Address::parse(input.as_ref()).ok())
            .flatten();
        let parses = address.is_some();
        let queries_domain = address
            .as_ref()
            .is_some_and(|address| self.mode != Mode::Local && !address.domain().is_literal());
        Plan {
            mode: self.mode,
            parses,
            queries_domain,
            may_disclose_address: queries_domain && self.mode == Mode::Mailbox,
            inspects_posture: {
                #[cfg(feature = "posture")]
                {
                    queries_domain && self.posture
                }
                #[cfg(not(feature = "posture"))]
                {
                    false
                }
            },
            network_time_limit: queries_domain.then_some(self.timeouts.total()),
        }
    }

    /// Validates untrusted input and returns a complete report.
    pub async fn validate(&self, input: impl Into<String>) -> Report {
        let started = Instant::now();
        let input = input.into();
        let parsed = if input.len() > self.limits.input_bytes() {
            Err(crate::ParseErrorKind::TooLong)
        } else {
            Address::parse(&input).map_err(|error| error.kind())
        };

        let mut report = match parsed {
            Ok(address) => self.local_report(input, address, started.elapsed()),
            Err(kind) => Report::invalid(
                input,
                kind,
                self.mode,
                self.policy.kind(),
                started.elapsed(),
            ),
        };
        self.check_network(&mut report).await;
        report.set_verdict(self.policy.evaluate(&report));
        report.set_elapsed(started.elapsed());
        #[cfg(feature = "tracing")]
        tracing::debug!(
            mode = ?self.mode,
            verdict = ?report.verdict(),
            findings = report.findings().len(),
            "email validation completed"
        );
        report
    }

    /// Inspects an address that has already passed Pata's parser.
    pub async fn inspect(&self, address: Address) -> Report {
        let started = Instant::now();
        let input = address.to_string();
        let mut report = self.local_report(input, address, started.elapsed());
        self.check_network(&mut report).await;
        report.set_verdict(self.policy.evaluate(&report));
        report.set_elapsed(started.elapsed());
        #[cfg(feature = "tracing")]
        tracing::debug!(
            mode = ?self.mode,
            verdict = ?report.verdict(),
            findings = report.findings().len(),
            "email validation completed"
        );
        report
    }
}

#[cfg(test)]
mod tests {
    use futures_executor::block_on;

    use super::*;
    use crate::Verdict;

    #[test]
    fn malformed_input_is_a_report_not_an_error() {
        let report = block_on(Validator::local().validate("not an address"));

        assert_eq!(report.verdict(), Verdict::Invalid);
        assert!(report.address().is_none());
        assert_eq!(report.findings()[0].code(), FindingCode::SyntaxInvalid);
    }

    #[test]
    fn builder_rejects_input_beyond_the_parser_bound() {
        let result = Validator::builder()
            .limits(Limits::default().with_input_bytes(Address::MAX_INPUT_BYTES + 1))
            .build();

        assert!(result.is_err());
    }

    #[test]
    fn builder_rejects_unbounded_batch_concurrency() {
        let result = Validator::builder()
            .limits(
                Limits::default()
                    .with_concurrent_validations(Limits::MAX_CONCURRENT_VALIDATIONS + 1),
            )
            .build();

        assert!(result.is_err());
    }

    #[cfg(feature = "classification")]
    #[test]
    fn registration_keeps_descriptive_classification_plausible() {
        let report = block_on(Validator::local().validate("support@gmail.com"));

        assert_eq!(report.verdict(), Verdict::Plausible);
        assert!(report.classification().is_role());
        assert!(report.classification().is_free_mail());
    }

    #[cfg(feature = "classification")]
    #[test]
    fn strict_policy_surfaces_classification_as_risk() {
        let validator = Validator::builder()
            .policy(Policy::strict())
            .build()
            .unwrap();
        let report = block_on(validator.validate("person@mailinator.com"));

        assert_eq!(report.verdict(), Verdict::Risky);
        assert!(report.classification().is_disposable());
    }

    #[cfg(feature = "classification")]
    #[test]
    fn domain_allow_rule_preserves_classification_findings() {
        let policy = Policy::builder().allow_domain("gmail.com").unwrap().build();
        let validator = Validator::builder().policy(policy).build().unwrap();
        let report = block_on(validator.validate("support@gmail.com"));

        assert!(
            report
                .findings()
                .iter()
                .any(|finding| { finding.code() == FindingCode::ClassificationRole })
        );
        assert!(
            report
                .findings()
                .iter()
                .any(|finding| { finding.code() == FindingCode::ClassificationFreeMail })
        );
        assert_eq!(report.verdict(), Verdict::Risky);

        let report = block_on(validator.validate("person@gmail.com"));
        assert_eq!(report.verdict(), Verdict::Plausible);
        assert!(
            report
                .findings()
                .iter()
                .any(|finding| finding.code() == FindingCode::ClassificationFreeMail)
        );
    }

    #[cfg(feature = "classification")]
    #[test]
    fn provider_typo_suggestion_never_rewrites_the_address() {
        let report = block_on(Validator::local().validate("maya@gamil.com"));

        assert_eq!(report.address().unwrap().domain().ascii(), "gamil.com");
        assert_eq!(
            report.classification().suggested_domain(),
            Some("gmail.com")
        );
        assert_eq!(report.verdict(), Verdict::Risky);
    }

    #[test]
    fn plan_discloses_network_boundary_without_running_it() {
        let plan = Validator::local().plan("maya@example.com");

        assert!(plan.parses());
        assert!(!plan.queries_domain());
        assert!(!plan.may_disclose_address());
        assert_eq!(plan.network_time_limit(), None);
    }

    #[test]
    fn report_debug_redacts_original_input() {
        let report = block_on(Validator::local().validate("secret@example.com"));
        let debug = format!("{report:?}");

        assert!(!debug.contains("secret"));
        assert!(debug.contains("example.com"));
    }

    #[test]
    fn non_normalized_local_part_is_valid_but_risky() {
        let report = block_on(Validator::local().validate("e\u{301}@example.com"));

        assert_eq!(report.verdict(), Verdict::Risky);
        assert!(
            report
                .findings()
                .iter()
                .any(|finding| { finding.code() == FindingCode::UnicodeLocalPartNotNormalized })
        );
    }

    #[test]
    fn normalized_international_local_part_is_plausible_by_default() {
        let report = block_on(Validator::local().validate("माया@example.com"));

        assert_eq!(report.verdict(), Verdict::Plausible);
        assert!(
            report
                .findings()
                .iter()
                .any(|finding| finding.code() == FindingCode::SyntaxNonAsciiLocalPart)
        );
    }

    #[test]
    fn transactional_policy_reports_a_missing_route_as_unknown() {
        let validator = Validator::builder()
            .policy(Policy::transactional())
            .build()
            .unwrap();
        let report = block_on(validator.validate("maya@example.com"));

        assert_eq!(report.verdict(), Verdict::Unknown);
        assert!(!Policy::transactional().accepts(&report));
    }
}