pata 0.0.1

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

use crate::{Address, Certainty, Error, Finding, FindingCode, Outcome, Report, Result, Verdict};

/// The identity of a built-in validation policy.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum PolicyKind {
    /// Accept plausible and risky addresses while exposing their findings.
    #[default]
    Registration,
    /// Require a usable mail route while retaining descriptive warnings.
    Transactional,
    /// Surface every warning as risk.
    Strict,
    /// A caller-constructed deterministic policy.
    Custom,
}

/// Deterministic rules that reduce a report to a verdict.
#[derive(Clone, Debug)]
pub struct Policy {
    kind: PolicyKind,
    ignored_warnings: BTreeSet<FindingCode>,
    allowed_domains: BTreeSet<String>,
    denied_domains: BTreeSet<String>,
    accepts_risky: bool,
}

impl Policy {
    /// Returns the registration policy.
    #[must_use]
    pub fn registration() -> Self {
        PolicyBuilder::new(PolicyKind::Registration)
            .ignore_warning(FindingCode::ClassificationRole)
            .ignore_warning(FindingCode::ClassificationFreeMail)
            .ignore_warning(FindingCode::SyntaxNonAsciiLocalPart)
            .build()
    }

    /// Returns the transactional-delivery policy.
    #[must_use]
    pub fn transactional() -> Self {
        PolicyBuilder::new(PolicyKind::Transactional)
            .ignore_warning(FindingCode::ClassificationRole)
            .ignore_warning(FindingCode::ClassificationFreeMail)
            .ignore_warning(FindingCode::ClassificationDisposable)
            .ignore_warning(FindingCode::SyntaxNonAsciiLocalPart)
            .build()
    }

    /// Returns the strict risk policy.
    #[must_use]
    pub fn strict() -> Self {
        PolicyBuilder::new(PolicyKind::Strict).build()
    }

    /// Starts a custom deterministic policy.
    #[must_use]
    pub fn builder() -> PolicyBuilder {
        PolicyBuilder::new(PolicyKind::Custom)
    }

    /// Returns this policy's identity.
    #[must_use]
    pub const fn kind(&self) -> PolicyKind {
        self.kind
    }

    /// Applies this policy to an existing report without repeating validation.
    #[must_use]
    pub fn evaluate(&self, report: &Report) -> Verdict {
        let verdict = self.evaluate_findings(report.findings(), report.address());
        if matches!(
            verdict,
            Verdict::Invalid | Verdict::Undeliverable | Verdict::Unknown
        ) {
            return verdict;
        }
        if self.kind == PolicyKind::Transactional
            && !matches!(
                report.domain_status(),
                crate::DomainStatus::MailExchanger | crate::DomainStatus::ImplicitMailExchanger
            )
        {
            return Verdict::Unknown;
        }
        if report
            .address()
            .is_some_and(|address| self.denied_domains.contains(address.domain().ascii()))
        {
            return Verdict::Risky;
        }
        verdict
    }

    fn evaluate_findings(&self, findings: &[Finding], address: Option<&Address>) -> Verdict {
        let domain_allowed =
            address.is_some_and(|address| self.allowed_domains.contains(address.domain().ascii()));
        if findings
            .iter()
            .any(|finding| finding.code() == FindingCode::SyntaxInvalid)
        {
            return Verdict::Invalid;
        }
        if findings.iter().any(|finding| {
            finding.outcome() == Outcome::Fail
                && matches!(
                    finding.code(),
                    FindingCode::DomainNxDomain
                        | FindingCode::DomainNullMx
                        | FindingCode::DomainNoMailRoute
                        | FindingCode::SmtpRecipientRejected
                        | FindingCode::SmtpMailboxDisabled
                )
        }) {
            return Verdict::Undeliverable;
        }
        if findings
            .iter()
            .any(|finding| finding.outcome() == Outcome::Unknown)
        {
            return Verdict::Unknown;
        }
        if findings.iter().any(|finding| {
            finding.outcome() == Outcome::Warning
                && finding.code() != FindingCode::PolicyDenied
                && !self.ignored_warnings.contains(&finding.code())
                && !(domain_allowed && is_domain_classification(finding.code()))
        }) {
            return Verdict::Risky;
        }
        Verdict::Plausible
    }

    /// Returns whether this policy accepts a report for normal use.
    #[must_use]
    pub fn accepts(&self, report: &Report) -> bool {
        if report
            .address()
            .is_some_and(|address| self.denied_domains.contains(address.domain().ascii()))
        {
            return false;
        }
        match self.evaluate(report) {
            Verdict::Plausible => true,
            Verdict::Risky => self.accepts_risky,
            Verdict::Invalid | Verdict::Undeliverable | Verdict::Unknown => false,
        }
    }

    pub(crate) fn overlay(&self, address: &Address) -> Option<Finding> {
        let domain = address.domain().ascii();
        if self.allowed_domains.contains(domain) {
            Some(Finding::new(
                FindingCode::PolicyAllowed,
                Outcome::Pass,
                Certainty::Conclusive,
                "a caller-owned allow rule matched the domain",
            ))
        } else if self.denied_domains.contains(domain) {
            Some(Finding::new(
                FindingCode::PolicyDenied,
                Outcome::Warning,
                Certainty::Conclusive,
                "a caller-owned deny rule matched the domain",
            ))
        } else {
            None
        }
    }
}

const fn is_domain_classification(code: FindingCode) -> bool {
    matches!(
        code,
        FindingCode::ClassificationDisposable
            | FindingCode::ClassificationFreeMail
            | FindingCode::ClassificationTypo
    )
}

impl Default for Policy {
    fn default() -> Self {
        Self::registration()
    }
}

/// Builds a custom deterministic validation policy.
#[derive(Clone, Debug)]
pub struct PolicyBuilder {
    kind: PolicyKind,
    ignored_warnings: BTreeSet<FindingCode>,
    allowed_domains: BTreeSet<String>,
    denied_domains: BTreeSet<String>,
    accepts_risky: bool,
}

impl PolicyBuilder {
    fn new(kind: PolicyKind) -> Self {
        Self {
            kind,
            ignored_warnings: BTreeSet::new(),
            allowed_domains: BTreeSet::new(),
            denied_domains: BTreeSet::new(),
            accepts_risky: kind != PolicyKind::Strict,
        }
    }

    /// Prevents one warning from changing a plausible verdict to risky.
    #[must_use]
    pub fn ignore_warning(mut self, code: FindingCode) -> Self {
        self.ignored_warnings.insert(code);
        self
    }

    /// Makes [`Policy::accepts`] reject reports with a risky verdict.
    #[must_use]
    pub const fn reject_risky(mut self) -> Self {
        self.accepts_risky = false;
        self
    }

    /// Adds an exact caller-owned domain allow rule.
    pub fn allow_domain(mut self, domain: impl AsRef<str>) -> Result<Self> {
        let domain = normalize_domain(domain.as_ref())?;
        self.allowed_domains.insert(domain.clone());
        self.denied_domains.remove(&domain);
        Ok(self)
    }

    /// Adds an exact caller-owned domain deny rule.
    pub fn deny_domain(mut self, domain: impl AsRef<str>) -> Result<Self> {
        let domain = normalize_domain(domain.as_ref())?;
        self.denied_domains.insert(domain.clone());
        self.allowed_domains.remove(&domain);
        Ok(self)
    }

    /// Finishes the policy.
    #[must_use]
    pub fn build(self) -> Policy {
        Policy {
            kind: self.kind,
            ignored_warnings: self.ignored_warnings,
            allowed_domains: self.allowed_domains,
            denied_domains: self.denied_domains,
            accepts_risky: self.accepts_risky,
        }
    }
}

fn normalize_domain(domain: &str) -> Result<String> {
    if domain.len() > Address::MAX_INPUT_BYTES {
        return Err(Error::Configuration("policy domain must be a DNS name"));
    }
    let ascii = idna::domain_to_ascii_strict(domain)
        .map_err(|_| Error::Configuration("policy domain must be a DNS name"))?;
    if ascii.is_empty()
        || ascii.len() > 253
        || ascii.contains('@')
        || ascii
            .split('.')
            .any(|label| label.is_empty() || label.len() > 63)
    {
        return Err(Error::Configuration("policy domain must be a DNS name"));
    }
    Ok(ascii.to_ascii_lowercase())
}

#[cfg(test)]
mod tests {
    use crate::{Certainty, Finding, FindingCode, Outcome};

    use super::*;

    fn finding(code: FindingCode, outcome: Outcome) -> Finding {
        Finding::new(code, outcome, Certainty::Indicative, "test")
    }

    fn report(findings: Vec<Finding>) -> Report {
        Report::parsed(
            "reader@example.com".to_owned(),
            Address::parse("reader@example.com").unwrap(),
            findings,
            crate::Classification::default(),
            crate::Mode::Local,
            PolicyKind::Registration,
            std::time::Duration::ZERO,
        )
    }

    #[test]
    fn decisive_failure_precedes_unknown() {
        let report = report(vec![
            finding(FindingCode::DomainNxDomain, Outcome::Fail),
            finding(FindingCode::SmtpTemporaryFailure, Outcome::Unknown),
        ]);

        assert_eq!(Policy::default().evaluate(&report), Verdict::Undeliverable);
    }

    #[test]
    fn registration_ignores_descriptive_role_warning() {
        let report = report(vec![
            finding(FindingCode::SyntaxValid, Outcome::Pass),
            finding(FindingCode::ClassificationRole, Outcome::Warning),
        ]);

        assert_eq!(Policy::registration().evaluate(&report), Verdict::Plausible);
        assert_eq!(Policy::strict().evaluate(&report), Verdict::Risky);
    }

    #[test]
    fn caller_domain_rules_are_normalized_and_auditable() {
        let policy = Policy::builder()
            .deny_domain("BÜCHER.example")
            .unwrap()
            .build();
        let address = Address::parse("reader@bücher.example").unwrap();
        let finding = policy.overlay(&address).unwrap();

        assert_eq!(finding.code(), FindingCode::PolicyDenied);
    }

    #[test]
    fn custom_policy_can_reject_risky_reports() {
        let policy = Policy::builder().reject_risky().build();
        let report = Report::parsed(
            "reader@example.com".to_owned(),
            Address::parse("reader@example.com").unwrap(),
            vec![finding(
                FindingCode::ClassificationDisposable,
                Outcome::Warning,
            )],
            crate::Classification::default(),
            crate::Mode::Local,
            PolicyKind::Registration,
            std::time::Duration::ZERO,
        );

        assert!(!policy.accepts(&report));
    }

    #[test]
    fn transactional_policy_requires_a_mail_route() {
        let report = report(vec![finding(FindingCode::SyntaxValid, Outcome::Pass)]);

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

    #[test]
    fn reevaluation_uses_the_active_domain_rules() {
        let report = report(vec![
            finding(FindingCode::SyntaxValid, Outcome::Pass),
            finding(FindingCode::PolicyDenied, Outcome::Warning),
            finding(FindingCode::ClassificationFreeMail, Outcome::Warning),
        ]);
        let allowed = Policy::builder()
            .allow_domain("example.com")
            .unwrap()
            .build();
        let denied = Policy::builder()
            .deny_domain("example.com")
            .unwrap()
            .build();

        assert_eq!(allowed.evaluate(&report), Verdict::Plausible);
        assert_eq!(denied.evaluate(&report), Verdict::Risky);
        assert!(!denied.accepts(&report));
    }

    #[cfg(feature = "dns")]
    #[test]
    fn transactional_policy_accepts_a_usable_mail_route() {
        let mut report = Report::parsed(
            "reader@example.com".to_owned(),
            Address::parse("reader@example.com").unwrap(),
            vec![finding(FindingCode::SyntaxValid, Outcome::Pass)],
            crate::Classification::default(),
            crate::Mode::Domain,
            PolicyKind::Transactional,
            std::time::Duration::ZERO,
        );
        report.append_domain(
            crate::DomainStatus::MailExchanger,
            finding(FindingCode::DomainMx, Outcome::Pass),
        );

        assert!(Policy::transactional().accepts(&report));
    }
}