zero-bounce 4.0.0

Wrapper library over the ZeroBounce API v2
Documentation
use std::io::Error as IOError;
use std::io::Read;

pub mod bulk_get_file;
pub mod http_error;
// Test fixtures. Not part of the public API; the integration tests include the
// same file (tests/mod.rs).
#[cfg(test)]
#[allow(dead_code)]
pub(crate) mod mock_constants;
pub mod structures;

pub use bulk_get_file::{format_get_file_error_message, get_file_json_indicates_error};

/// A key with surrounding whitespace or control characters would be quoted,
/// unredacted, in the HTTP library's own error, so it is never sent.
pub(crate) fn check_key_text(api_key: &str) -> ZBResult<()> {
    if api_key != api_key.trim() || api_key.chars().any(|c| c.is_control()) {
        return Err(ZBError::explicit(
            "api_key has surrounding whitespace or control characters",
        ));
    }
    Ok(())
}

/// What Debug output shows in place of an API key.
pub(crate) fn redacted_key(api_key: &str) -> &'static str {
    if api_key.is_empty() {
        ""
    } else {
        "***"
    }
}

pub const CONTENT_TYPE_JSON: &str = "application/json";
pub const CONTENT_TYPE_STREAM: &str = "application/octet-stream";
/// Cap JSON API responses so error pages cannot exhaust memory (RS-05).
pub const MAX_JSON_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
/// Cap bulk getfile downloads (still large enough for typical CSV exports).
pub const MAX_GETFILE_BYTES: usize = 256 * 1024 * 1024;

/// Stop reading after one byte past the cap, so an oversized response cannot
/// consume unbounded memory before the caller checks its length.
pub(crate) fn read_limited(
    mut reader: impl Read,
    max_bytes: usize,
    message: &str,
) -> ZBResult<Vec<u8>> {
    let mut body = Vec::new();
    reader.by_ref().take(max_bytes as u64 + 1).read_to_end(&mut body)?;
    if body.len() > max_bytes {
        return Err(ZBError::explicit(message));
    }
    Ok(body)
}

#[cfg(test)]
mod response_limit_tests {
    use super::read_limited;
    use std::io::{self, Read};

    struct CountingReader {
        remaining: usize,
        read: usize,
    }

    impl Read for CountingReader {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let n = buf.len().min(self.remaining);
            buf[..n].fill(b'x');
            self.remaining -= n;
            self.read += n;
            Ok(n)
        }
    }

    #[test]
    fn stops_at_one_byte_past_limit() {
        let mut source = CountingReader {
            remaining: 10_000,
            read: 0,
        };
        let error = read_limited(&mut source, 32, "too large").unwrap_err();
        assert_eq!(error.to_string(), "too large");
        assert_eq!(source.read, 33);
    }

    #[test]
    fn accepts_body_at_limit() {
        let body = read_limited(&b"exact"[..], 5, "too large").unwrap();
        assert_eq!(body, b"exact");
    }
}

/// Enum representing the available API base URLs
///
/// `#[non_exhaustive]`: a region added later is not a breaking change, so a
/// `match` on it needs a `_` arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApiBaseUrl {
    /// Default API URL: https://api.zerobounce.net/v2/
    Default,
    /// USA API URL: https://api-us.zerobounce.net/v2/
    USA,
    /// EU API URL: https://api-eu.zerobounce.net/v2/
    EU,
}

impl ApiBaseUrl {
    /// Get the URL string for this API base URL
    pub fn as_str(&self) -> &'static str {
        match self {
            ApiBaseUrl::Default => "https://api.zerobounce.net/v2/",
            ApiBaseUrl::USA => "https://api-us.zerobounce.net/v2/",
            ApiBaseUrl::EU => "https://api-eu.zerobounce.net/v2/",
        }
    }
}

impl From<ApiBaseUrl> for String {
    fn from(url: ApiBaseUrl) -> Self {
        url.as_str().to_string()
    }
}

impl From<&ApiBaseUrl> for String {
    fn from(url: &ApiBaseUrl) -> Self {
        url.as_str().to_string()
    }
}

/// Percent-encodes a value so it is one path segment.
///
/// Only the unreserved set from RFC 3986 is left alone, so `/`, spaces and the
/// rest are escaped and a file id cannot break out of its segment. Written here
/// rather than pulling in a crate for four lines.
pub fn encode_path_segment(value: &str) -> String {
    let mut encoded = String::with_capacity(value.len());
    for byte in value.as_bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                encoded.push(*byte as char)
            }
            _ => encoded.push_str(&format!("%{:02X}", byte)),
        }
    }
    encoded
}

pub const BULK_URI: &str = "https://bulkapi.zerobounce.net/v2";
/// The list evaluator and the Inbox Placement Tester are not under the bulk /v2 path.
pub const LIST_EVALUATOR_URI: &str = "https://bulkapi.zerobounce.net/v2/listevaluator";
pub const INBOX_PLACEMENT_URI: &str = "https://bulkapi.zerobounce.net/api/ipt";
pub const ENDPOINT_CREDITS: &str = "/getcredits";
pub const ENDPOINT_ACTIVITY_DATA: &str = "/activity";
pub const ENDPOINT_SCORING: &str = "/scoring";
pub const ENDPOINT_VALIDATE: &str = "/validate";
pub const ENDPOINT_API_USAGE: &str = "/getapiusage";
pub const ENDPOINT_BATCH_VALIDATE: &str = "/validatebatch";
pub const ENDPOINT_FILE_SEND: &str = "/sendfile";
pub const ENDPOINT_FILE_STATUS: &str = "/filestatus";
pub const ENDPOINT_FILE_RESULT: &str = "/getfile";
pub const ENDPOINT_FILE_DELETE: &str = "/deletefile";
pub const ENDPOINT_SCORING_SEND: &str = "/scoring/sendfile";
pub const ENDPOINT_SCORING_STATUS: &str = "/scoring/filestatus";
pub const ENDPOINT_SCORING_RESULT: &str = "/scoring/getfile";
pub const ENDPOINT_SCORING_DELETE: &str = "/scoring/deletefile";
pub const ENDPOINT_EMAIL_FINDER: &str = "/guessformat";

// validation statuses
pub const S_VALID: &str = "valid";
pub const S_INVALID: &str = "invalid";
pub const S_CATCH_ALL: &str = "catch-all";
pub const S_UNKNOWN: &str = "unknown";
pub const S_SPAMTRAP: &str = "spamtrap";
pub const S_ABUSE: &str = "abuse";
pub const S_DO_NOT_MAIL: &str = "do_not_mail";

// validation sub statuses
pub const SS_ANTISPAM_SYSTEM: &str = "antispam_system";
pub const SS_GREYLISTED: &str = "greylisted";
pub const SS_MAIL_SERVER_TEMPORARY_ERROR: &str = "mail_server_temporary_error";
pub const SS_FORCIBLE_DISCONNECT: &str = "forcible_disconnect";
pub const SS_MAIL_SERVER_DID_NOT_RESPOND: &str = "mail_server_did_not_respond";
pub const SS_TIMEOUT_EXCEEDED: &str = "timeout_exceeded";
pub const SS_FAILED_SMTP_CONNECTION: &str = "failed_smtp_connection";
pub const SS_MAILBOX_QUOTA_EXCEEDED: &str = "mailbox_quota_exceeded";
pub const SS_EXCEPTION_OCCURRED: &str = "exception_occurred";
pub const SS_POSSIBLE_TRAP: &str = "possible_trap";
pub const SS_ROLE_BASED: &str = "role_based";
pub const SS_GLOBAL_SUPPRESSION: &str = "global_suppression";
pub const SS_MAILBOX_NOT_FOUND: &str = "mailbox_not_found";
pub const SS_NO_DNS_ENTRIES: &str = "no_dns_entries";
pub const SS_FAILED_SYNTAX_CHECK: &str = "failed_syntax_check";
pub const SS_POSSIBLE_TYPO: &str = "possible_typo";
pub const SS_UNROUTABLE_IP_ADDRESS: &str = "unroutable_ip_address";
pub const SS_LEADING_PERIOD_REMOVED: &str = "leading_period_removed";
pub const SS_DOES_NOT_ACCEPT_MAIL: &str = "does_not_accept_mail";
pub const SS_ALIAS_ADDRESS: &str = "alias_address";
pub const SS_ROLE_BASED_CATCH_ALL: &str = "role_based_catch_all";
pub const SS_DISPOSABLE: &str = "disposable";
pub const SS_TOXIC: &str = "toxic";
pub const SS_ACCEPT_ALL: &str = "accept_all";
pub const SS_AI_AGENT_MAILBOX: &str = "ai_agent_mailbox";

/// Every error the SDK returns.
///
/// `#[non_exhaustive]`: a variant added later is not a breaking change, so a
/// `match` on it needs a `_` arm.
#[derive(Debug)]
#[non_exhaustive]
pub enum ZBError {
    /// An error the SDK raised itself: an invalid argument or URL caught before
    /// a request, or a 2xx response body it could not read.
    ExplicitError(String),
    /// The API answered and the answer is a failure: a non-2xx status, an HTML
    /// error page, an error body on an HTTP 200, a bulk `getfile` error, or a
    /// `batch_validate` account-level error. `status` is the HTTP status of that
    /// response, so callers can tell a 403 from Cloudflare apart from a 400/404
    /// from the API and a 429 from the Warmup rate limit. Both the validation
    /// client and the Warmup client return it.
    ApiError { status: u16, message: String },
    JsonError(serde_json::Error),
    IntParseError(std::num::ParseIntError),
    RequestError(reqwest::Error),
    IOError(IOError),
}

pub type ZBResult<T> = Result<T, ZBError>;

impl ZBError {
    pub fn explicit(string: &str) -> ZBError {
        ZBError::ExplicitError(string.to_string())
    }

    pub fn api(status: u16, message: impl Into<String>) -> ZBError {
        ZBError::ApiError {
            status,
            message: message.into(),
        }
    }

    /// The HTTP status of a failed API response: `Some` for every
    /// [`ZBError::ApiError`], including a failure the API reports with an HTTP
    /// 200. `None` when no failed response is involved: an argument or URL
    /// rejected before a request, a transport error, or a 2xx body that could
    /// not be parsed.
    pub fn status_code(&self) -> Option<u16> {
        match self {
            ZBError::ApiError { status, .. } => Some(*status),
            _ => None,
        }
    }
}

impl std::fmt::Display for ZBError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ZBError::ExplicitError(message) => write!(formatter, "{message}"),
            ZBError::ApiError { message, .. } => write!(formatter, "{message}"),
            ZBError::JsonError(_) => {
                write!(
                    formatter,
                    "ZeroBounce returned a response that is not valid JSON."
                )
            }
            ZBError::IntParseError(_) => write!(
                formatter,
                "ZeroBounce returned a response that could not be read."
            ),
            ZBError::RequestError(error) => write!(formatter, "{error}"),
            ZBError::IOError(error) => write!(formatter, "{error}"),
        }
    }
}

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

// Implementation made in order to automatically convert errors
// generated by the reqwuest library into a ZBError instance.
//
// This automatic conversion is expected when using the client
// and issuing http requests.
fn redact_api_key(url: &mut reqwest::Url) {
    if !url.query_pairs().any(|(key, _)| key == "api_key") {
        return;
    }
    let pairs: Vec<(String, String)> = url
        .query_pairs()
        .map(|(key, value)| {
            let value = if key == "api_key" {
                "REDACTED".to_string()
            } else {
                value.into_owned()
            };
            (key.into_owned(), value)
        })
        .collect();
    url.query_pairs_mut().clear().extend_pairs(pairs);
}

impl From<reqwest::Error> for ZBError {
    fn from(mut value: reqwest::Error) -> ZBError {
        if let Some(url) = value.url_mut() {
            redact_api_key(url);
        }
        ZBError::RequestError(value)
    }
}

// Implementation made in order to automatically convert errors
// generated by the serde_json library into a ZBError instance.
//
// This automatic conversion is expected when deserializing.
impl From<serde_json::Error> for ZBError {
    fn from(value: serde_json::Error) -> ZBError {
        ZBError::JsonError(value)
    }
}

impl From<IOError> for ZBError {
    fn from(value: IOError) -> Self {
        ZBError::IOError(value)
    }
}