pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
use std::{io, time::Duration};

use futures_lite::io::AsyncReadExt as _;
use smtp_proto::{Error as ParseError, Response, response::parser::ResponseReceiver};

use super::Observation;
use crate::{
    Certainty, Finding, FindingCode, MailboxStatus, Outcome,
    runtime::{Io, Timer, timeout},
};

const MAX_RESPONSE_BYTES: usize = 8 * 1024;

pub(super) async fn read(
    stream: &mut dyn Io,
    timer: &dyn Timer,
    duration: Duration,
) -> io::Result<Response<String>> {
    timeout(timer, duration, async {
        let mut receiver = ResponseReceiver::default();
        let mut buffer = [0_u8; 512];
        let mut total = 0_usize;
        while total < MAX_RESPONSE_BYTES {
            let remaining = MAX_RESPONSE_BYTES - total;
            let capacity = remaining.min(buffer.len());
            let length = stream.read(&mut buffer[..capacity]).await?;
            if length == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "SMTP server closed an incomplete response",
                ));
            }
            total += length;
            match receiver.parse(&mut buffer[..length].iter()) {
                Ok(response) => return Ok(response),
                Err(ParseError::NeedsMoreData { .. }) => {}
                Err(_) => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "invalid SMTP response",
                    ));
                }
            }
        }
        Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "SMTP response exceeded the configured bound",
        ))
    })
    .await?
}

pub(super) fn classify(response: Response<String>) -> Observation {
    match (response.code, response.esc) {
        (200..=299, _) => Observation {
            status: MailboxStatus::Accepted,
            findings: vec![Finding::new(
                FindingCode::SmtpAccepted,
                Outcome::Pass,
                Certainty::Strong,
                "the server accepted the recipient at observation time",
            )],
        },
        (500..=599, [5, 2, 1]) => Observation {
            status: MailboxStatus::Disabled,
            findings: vec![Finding::new(
                FindingCode::SmtpMailboxDisabled,
                Outcome::Fail,
                Certainty::Strong,
                "the server reported a disabled mailbox",
            )],
        },
        (400..=499, [4, 2, 2]) | (500..=599, [5, 2, 2]) => Observation {
            status: MailboxStatus::Full,
            findings: vec![Finding::new(
                FindingCode::SmtpMailboxFull,
                Outcome::Warning,
                Certainty::Strong,
                "the server reported a full mailbox",
            )],
        },
        (500..=599, [5, 1, 1]) => Observation {
            status: MailboxStatus::Rejected,
            findings: vec![Finding::new(
                FindingCode::SmtpRecipientRejected,
                Outcome::Fail,
                Certainty::Strong,
                "the server permanently rejected the recipient",
            )],
        },
        (500..=599, [5, 7, _]) => unknown(
            FindingCode::SmtpPolicyBlocked,
            "the server blocked recipient observation by policy",
        ),
        (500..=599, _) => unknown(
            FindingCode::SmtpProbeRejected,
            "the server rejected the transaction, but not the recipient",
        ),
        (400..=499, _) if contains(&response.message, "grey") => unknown(
            FindingCode::SmtpGreylisted,
            "the server applied temporary greylisting",
        ),
        (400..=499, _) if contains(&response.message, "rate") => unknown(
            FindingCode::SmtpRateLimited,
            "the server rate-limited the SMTP probe",
        ),
        _ => unknown(
            FindingCode::SmtpTemporaryFailure,
            "the SMTP response did not identify the recipient as accepted or rejected",
        ),
    }
}

pub(super) fn transaction_failure(response: Response<String>) -> Observation {
    if response.code / 100 == 4 && contains(&response.message, "grey") {
        unknown(
            FindingCode::SmtpGreylisted,
            "the server applied temporary greylisting",
        )
    } else if response.code / 100 == 4 && contains(&response.message, "rate") {
        unknown(
            FindingCode::SmtpRateLimited,
            "the server rate-limited the SMTP probe",
        )
    } else if response.code / 100 == 5 {
        unknown(
            FindingCode::SmtpPolicyBlocked,
            "the server declined the SMTP probe before recipient observation",
        )
    } else {
        unknown(
            FindingCode::SmtpTemporaryFailure,
            "the SMTP transaction could not reach recipient observation",
        )
    }
}

pub(super) fn advertises(message: &str, extension: &str) -> bool {
    message.lines().any(|line| {
        line.split_ascii_whitespace()
            .next()
            .is_some_and(|word| word.eq_ignore_ascii_case(extension))
    })
}

pub(super) fn unknown(code: FindingCode, summary: &'static str) -> Observation {
    Observation {
        status: MailboxStatus::Unknown,
        findings: vec![Finding::new(
            code,
            Outcome::Unknown,
            Certainty::Strong,
            summary,
        )],
    }
}

fn contains(message: &str, needle: &str) -> bool {
    message.to_ascii_lowercase().contains(needle)
}

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

    #[test]
    fn enhanced_mailbox_codes_are_interpreted_semantically() {
        let disabled = classify(Response {
            code: 550,
            esc: [5, 2, 1],
            message: "mailbox disabled".to_owned(),
        });
        let full = classify(Response {
            code: 452,
            esc: [4, 2, 2],
            message: "mailbox full".to_owned(),
        });
        assert_eq!(disabled.status, MailboxStatus::Disabled);
        assert_eq!(full.status, MailboxStatus::Full);
    }

    #[test]
    fn contradictory_enhanced_codes_do_not_override_the_reply_class() {
        let temporary = classify(Response {
            code: 452,
            esc: [5, 2, 1],
            message: "temporary failure".to_owned(),
        });
        assert_eq!(temporary.status, MailboxStatus::Unknown);
        assert_eq!(
            temporary.findings[0].code(),
            FindingCode::SmtpTemporaryFailure
        );
    }

    #[test]
    fn recipient_policy_failure_keeps_the_mailbox_unknown() {
        let blocked = classify(Response {
            code: 550,
            esc: [5, 7, 1],
            message: "sender policy rejected".to_owned(),
        });

        assert_eq!(blocked.status, MailboxStatus::Unknown);
        assert_eq!(blocked.findings[0].code(), FindingCode::SmtpPolicyBlocked);
    }

    #[test]
    fn sender_address_failure_keeps_the_recipient_unknown() {
        let rejected = classify(Response {
            code: 550,
            esc: [5, 1, 7],
            message: "sender address rejected".to_owned(),
        });

        assert_eq!(rejected.status, MailboxStatus::Unknown);
        assert_eq!(rejected.findings[0].code(), FindingCode::SmtpProbeRejected);
    }

    #[test]
    fn non_recipient_permanent_failure_keeps_the_mailbox_unknown() {
        let rejected = classify(Response {
            code: 550,
            esc: [5, 3, 0],
            message: "mail system failure".to_owned(),
        });

        assert_eq!(rejected.status, MailboxStatus::Unknown);
        assert_eq!(rejected.findings[0].code(), FindingCode::SmtpProbeRejected);
    }

    #[test]
    fn unenhanced_permanent_failure_keeps_the_mailbox_unknown() {
        let rejected = classify(Response {
            code: 550,
            esc: [0, 0, 0],
            message: "mailbox unavailable".to_owned(),
        });

        assert_eq!(rejected.status, MailboxStatus::Unknown);
        assert_eq!(rejected.findings[0].code(), FindingCode::SmtpProbeRejected);
    }

    #[test]
    fn greylisting_and_rate_limits_remain_transient() {
        let greylisted = classify(Response {
            code: 451,
            esc: [4, 7, 1],
            message: "greylisted, try later".to_owned(),
        });
        let limited = classify(Response {
            code: 421,
            esc: [4, 7, 0],
            message: "rate limit exceeded".to_owned(),
        });
        assert_eq!(greylisted.findings[0].code(), FindingCode::SmtpGreylisted);
        assert_eq!(limited.findings[0].code(), FindingCode::SmtpRateLimited);
        assert_eq!(greylisted.status, MailboxStatus::Unknown);
    }

    #[test]
    fn extension_matching_requires_a_capability_token() {
        assert!(advertises("mx.example\nSTARTTLS\nSIZE 1024", "STARTTLS"));
        assert!(advertises("SMTPUTF8", "smtputf8"));
        assert!(!advertises("mx-starttls.example", "STARTTLS"));
        assert!(!advertises("XSTARTTLS", "STARTTLS"));
    }
}