pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
//! Runtime-neutral DNS mail-routing capabilities.

use std::{collections::BTreeSet, fmt, future::Future, net::IpAddr, pin::Pin, time::Duration};

pub(crate) const MAX_EXCHANGES: usize = 32;
const MAX_ADDRESSES_PER_EXCHANGE: usize = 16;
#[cfg(feature = "posture")]
const MAX_TEXT_RECORDS: usize = 32;
#[cfg(feature = "posture")]
const MAX_TEXT_RECORD_BYTES: usize = 4 * 1024;
#[cfg(feature = "posture")]
const MAX_TEXT_RESPONSE_BYTES: usize = 16 * 1024;

/// A boxed DNS lookup future.
pub type Resolve<'a> = Pin<Box<dyn Future<Output = Result<Resolution, ResolveError>> + Send + 'a>>;

/// A boxed TXT lookup future used by optional domain-posture inspection.
#[cfg(feature = "posture")]
pub type ResolveText<'a> =
    Pin<Box<dyn Future<Output = Result<TextRecords, ResolveError>> + Send + 'a>>;

/// Resolves the DNS records needed to route mail for one domain.
pub trait Resolver: Send + Sync {
    /// Resolves MX records and any required implicit-MX addresses.
    fn resolve(&self, domain: &str) -> Resolve<'_>;

    /// Resolves TXT records for optional domain-posture inspection.
    #[cfg(feature = "posture")]
    fn resolve_text(&self, _domain: &str) -> ResolveText<'_> {
        Box::pin(async {
            Err(ResolveError::new(
                ResolveErrorKind::Unavailable,
                "TXT lookup capability is unavailable",
            ))
        })
    }
}

/// Owned TXT records returned to the posture layer.
#[cfg(feature = "posture")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TextRecords {
    values: Vec<String>,
    valid_for: Option<Duration>,
}

#[cfg(feature = "posture")]
impl TextRecords {
    /// Creates bounded, deterministically ordered TXT records.
    ///
    /// The response can contain at most 32 records, 4 KiB per record, and
    /// 16 KiB in total.
    pub fn new(mut values: Vec<String>, valid_for: Option<Duration>) -> Result<Self, ResolveError> {
        let total_bytes = values.iter().try_fold(0_usize, |total, value| {
            total.checked_add(value.len()).ok_or(())
        });
        let exceeds_total = match total_bytes {
            Ok(total) => total > MAX_TEXT_RESPONSE_BYTES,
            Err(()) => true,
        };
        if values.len() > MAX_TEXT_RECORDS
            || values
                .iter()
                .any(|value| value.len() > MAX_TEXT_RECORD_BYTES)
            || exceeds_total
        {
            return Err(ResolveError::new(
                ResolveErrorKind::Protocol,
                "TXT response exceeded its resource limit",
            ));
        }
        values.sort();
        Ok(Self { values, valid_for })
    }

    /// Returns deterministically ordered record strings.
    #[must_use]
    pub fn values(&self) -> &[String] {
        &self.values
    }

    /// Returns the resolver-supplied cache lifetime when available.
    #[must_use]
    pub const fn valid_for(&self) -> Option<Duration> {
        self.valid_for
    }
}

/// A resolved SMTP destination advertised by an MX record.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct MailExchange {
    preference: u16,
    host: String,
    addresses: Vec<IpAddr>,
}

impl MailExchange {
    /// Creates one normalized mail exchange.
    ///
    /// The exchange retains at most 16 unique addresses.
    pub fn new(
        preference: u16,
        host: impl AsRef<str>,
        mut addresses: Vec<IpAddr>,
    ) -> Result<Self, ResolveError> {
        let host = host.as_ref();
        let host = host.strip_suffix('.').unwrap_or(host);
        let host = idna::domain_to_ascii_strict(host)
            .map_err(|_| {
                ResolveError::new(ResolveErrorKind::InvalidName, "invalid mail exchanger name")
            })?
            .to_ascii_lowercase();
        if host.is_empty()
            || host.len() > 253
            || host
                .split('.')
                .any(|label| label.is_empty() || label.len() > 63)
        {
            return Err(ResolveError::new(
                ResolveErrorKind::InvalidName,
                "invalid mail exchanger name",
            ));
        }
        addresses.sort_unstable();
        addresses.dedup();
        addresses.truncate(MAX_ADDRESSES_PER_EXCHANGE);
        Ok(Self {
            preference,
            host,
            addresses,
        })
    }

    /// Returns the MX preference; lower values are tried first.
    #[must_use]
    pub const fn preference(&self) -> u16 {
        self.preference
    }

    /// Returns the normalized exchange hostname.
    #[must_use]
    pub fn host(&self) -> &str {
        &self.host
    }

    /// Returns the resolved destination addresses.
    #[must_use]
    pub fn addresses(&self) -> &[IpAddr] {
        &self.addresses
    }
}

/// The authoritative DNS conclusion for a domain.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ResolutionKind {
    /// Explicit MX records advertise one or more exchanges.
    Mx,
    /// No MX exists, but address records permit RFC 5321 implicit MX.
    ImplicitMx,
    /// The domain explicitly publishes a single Null MX.
    NullMx,
    /// The queried name does not exist.
    NxDomain,
    /// The name exists but has no MX or address route.
    NoMailRoute,
}

/// An owned DNS mail-routing result.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Resolution {
    kind: ResolutionKind,
    exchanges: Vec<MailExchange>,
    valid_for: Option<Duration>,
}

impl Resolution {
    /// Creates a normalized routing result.
    ///
    /// The result drops exchanges without resolved addresses and retains at
    /// most 32 unique routes.
    #[must_use]
    pub fn new(
        mut kind: ResolutionKind,
        exchanges: Vec<MailExchange>,
        valid_for: Option<Duration>,
    ) -> Self {
        let exchanges = if matches!(
            kind,
            ResolutionKind::NullMx | ResolutionKind::NxDomain | ResolutionKind::NoMailRoute
        ) {
            Vec::new()
        } else {
            let mut routes = BTreeSet::new();
            for exchange in exchanges {
                if exchange.addresses().is_empty() {
                    continue;
                }
                routes.insert(exchange);
                if routes.len() > MAX_EXCHANGES {
                    let _ = routes.pop_last();
                }
            }
            if routes.is_empty() {
                kind = ResolutionKind::NoMailRoute;
            }
            routes.into_iter().collect()
        };
        Self {
            kind,
            exchanges,
            valid_for,
        }
    }

    /// Returns the semantic routing conclusion.
    #[must_use]
    pub const fn kind(&self) -> ResolutionKind {
        self.kind
    }

    /// Returns ordered SMTP destinations.
    #[must_use]
    pub fn exchanges(&self) -> &[MailExchange] {
        &self.exchanges
    }

    /// Returns the resolver-provided cache lifetime when available.
    #[must_use]
    pub const fn valid_for(&self) -> Option<Duration> {
        self.valid_for
    }
}

/// A DNS failure that does not itself establish domain non-existence.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolveError {
    kind: ResolveErrorKind,
    message: String,
}

impl ResolveError {
    /// Creates a resolver error from a message that is safe to disclose.
    ///
    /// The message must not contain an email address, credential, or other
    /// sensitive input.
    #[must_use]
    pub fn new(kind: ResolveErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }

    /// Returns the stable failure category.
    #[must_use]
    pub const fn kind(&self) -> ResolveErrorKind {
        self.kind
    }
}

impl fmt::Display for ResolveError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ResolveError {}

/// Stable categories for inconclusive DNS failures.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ResolveErrorKind {
    /// The operation exceeded its deadline.
    Timeout,
    /// No configured name server could answer.
    Unavailable,
    /// A response was malformed or internally inconsistent.
    Protocol,
    /// The supplied name could not be queried.
    InvalidName,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exchanges_are_normalized_and_deterministic() {
        let exchange = MailExchange::new(
            10,
            "MX.EXAMPLE.COM.",
            vec!["192.0.2.2".parse().unwrap(), "192.0.2.1".parse().unwrap()],
        )
        .unwrap();

        assert_eq!(exchange.host(), "mx.example.com");
        assert_eq!(exchange.addresses()[0].to_string(), "192.0.2.1");
    }

    #[test]
    fn exchange_names_accept_only_one_dns_root_label() {
        assert!(MailExchange::new(10, "mx.example.com.", Vec::new()).is_ok());
        assert!(MailExchange::new(10, "mx.example.com..", Vec::new()).is_err());
    }

    #[test]
    fn resolver_results_are_bounded_before_use() {
        let addresses = (1..=32).map(|last| IpAddr::from([1, 1, 1, last])).collect();
        let exchange = MailExchange::new(10, "mx.example.com", addresses).unwrap();
        assert_eq!(exchange.addresses().len(), MAX_ADDRESSES_PER_EXCHANGE);

        let exchanges = (0..64)
            .map(|index| {
                MailExchange::new(
                    index,
                    format!("mx-{index}.example.com"),
                    vec![IpAddr::from([1, 1, 1, 1])],
                )
            })
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        let resolution = Resolution::new(ResolutionKind::Mx, exchanges, None);
        assert_eq!(resolution.exchanges().len(), MAX_EXCHANGES);
    }

    #[test]
    fn negative_conclusions_cannot_carry_smtp_routes() {
        let exchange = MailExchange::new(10, "mx.example.com", Vec::new()).unwrap();
        let resolution = Resolution::new(ResolutionKind::NullMx, vec![exchange], None);

        assert!(resolution.exchanges().is_empty());
    }

    #[test]
    fn empty_positive_routes_become_no_mail_route() {
        let exchange = MailExchange::new(10, "mx.example.com", Vec::new()).unwrap();
        let resolution = Resolution::new(ResolutionKind::Mx, vec![exchange], None);

        assert_eq!(resolution.kind(), ResolutionKind::NoMailRoute);
        assert!(resolution.exchanges().is_empty());
    }

    #[test]
    fn usable_routes_are_selected_before_the_exchange_limit() {
        let mut exchanges = (0..MAX_EXCHANGES)
            .map(|index| {
                MailExchange::new(index as u16, format!("mx-{index}.example.com"), Vec::new())
            })
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        exchanges.push(
            MailExchange::new(
                100,
                "mx-usable.example.com",
                vec![IpAddr::from([1, 1, 1, 1])],
            )
            .unwrap(),
        );

        let resolution = Resolution::new(ResolutionKind::Mx, exchanges, None);

        assert_eq!(resolution.kind(), ResolutionKind::Mx);
        assert_eq!(resolution.exchanges().len(), 1);
        assert_eq!(resolution.exchanges()[0].host(), "mx-usable.example.com");
    }

    #[cfg(feature = "posture")]
    #[test]
    fn text_records_reject_oversized_responses() {
        let error =
            TextRecords::new(vec!["x".repeat(MAX_TEXT_RECORD_BYTES + 1)], None).unwrap_err();

        assert_eq!(error.kind(), ResolveErrorKind::Protocol);
    }
}