Skip to main content

zero_bounce/utility/
mod.rs

1use std::io::Error as IOError;
2use std::io::Read;
3
4pub mod bulk_get_file;
5pub mod http_error;
6// Test fixtures. Not part of the public API; the integration tests include the
7// same file (tests/mod.rs).
8#[cfg(test)]
9#[allow(dead_code)]
10pub(crate) mod mock_constants;
11pub mod structures;
12
13pub use bulk_get_file::{format_get_file_error_message, get_file_json_indicates_error};
14
15/// A key with surrounding whitespace or control characters would be quoted,
16/// unredacted, in the HTTP library's own error, so it is never sent.
17pub(crate) fn check_key_text(api_key: &str) -> ZBResult<()> {
18    if api_key != api_key.trim() || api_key.chars().any(|c| c.is_control()) {
19        return Err(ZBError::explicit(
20            "api_key has surrounding whitespace or control characters",
21        ));
22    }
23    Ok(())
24}
25
26/// What Debug output shows in place of an API key.
27pub(crate) fn redacted_key(api_key: &str) -> &'static str {
28    if api_key.is_empty() {
29        ""
30    } else {
31        "***"
32    }
33}
34
35pub const CONTENT_TYPE_JSON: &str = "application/json";
36pub const CONTENT_TYPE_STREAM: &str = "application/octet-stream";
37/// Cap JSON API responses so error pages cannot exhaust memory (RS-05).
38pub const MAX_JSON_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
39/// Cap bulk getfile downloads (still large enough for typical CSV exports).
40pub const MAX_GETFILE_BYTES: usize = 256 * 1024 * 1024;
41
42/// Stop reading after one byte past the cap, so an oversized response cannot
43/// consume unbounded memory before the caller checks its length.
44pub(crate) fn read_limited(
45    mut reader: impl Read,
46    max_bytes: usize,
47    message: &str,
48) -> ZBResult<Vec<u8>> {
49    let mut body = Vec::new();
50    reader.by_ref().take(max_bytes as u64 + 1).read_to_end(&mut body)?;
51    if body.len() > max_bytes {
52        return Err(ZBError::explicit(message));
53    }
54    Ok(body)
55}
56
57#[cfg(test)]
58mod response_limit_tests {
59    use super::read_limited;
60    use std::io::{self, Read};
61
62    struct CountingReader {
63        remaining: usize,
64        read: usize,
65    }
66
67    impl Read for CountingReader {
68        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
69            let n = buf.len().min(self.remaining);
70            buf[..n].fill(b'x');
71            self.remaining -= n;
72            self.read += n;
73            Ok(n)
74        }
75    }
76
77    #[test]
78    fn stops_at_one_byte_past_limit() {
79        let mut source = CountingReader {
80            remaining: 10_000,
81            read: 0,
82        };
83        let error = read_limited(&mut source, 32, "too large").unwrap_err();
84        assert_eq!(error.to_string(), "too large");
85        assert_eq!(source.read, 33);
86    }
87
88    #[test]
89    fn accepts_body_at_limit() {
90        let body = read_limited(&b"exact"[..], 5, "too large").unwrap();
91        assert_eq!(body, b"exact");
92    }
93}
94
95/// Enum representing the available API base URLs
96///
97/// `#[non_exhaustive]`: a region added later is not a breaking change, so a
98/// `match` on it needs a `_` arm.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum ApiBaseUrl {
102    /// Default API URL: https://api.zerobounce.net/v2/
103    Default,
104    /// USA API URL: https://api-us.zerobounce.net/v2/
105    USA,
106    /// EU API URL: https://api-eu.zerobounce.net/v2/
107    EU,
108}
109
110impl ApiBaseUrl {
111    /// Get the URL string for this API base URL
112    pub fn as_str(&self) -> &'static str {
113        match self {
114            ApiBaseUrl::Default => "https://api.zerobounce.net/v2/",
115            ApiBaseUrl::USA => "https://api-us.zerobounce.net/v2/",
116            ApiBaseUrl::EU => "https://api-eu.zerobounce.net/v2/",
117        }
118    }
119}
120
121impl From<ApiBaseUrl> for String {
122    fn from(url: ApiBaseUrl) -> Self {
123        url.as_str().to_string()
124    }
125}
126
127impl From<&ApiBaseUrl> for String {
128    fn from(url: &ApiBaseUrl) -> Self {
129        url.as_str().to_string()
130    }
131}
132
133/// Percent-encodes a value so it is one path segment.
134///
135/// Only the unreserved set from RFC 3986 is left alone, so `/`, spaces and the
136/// rest are escaped and a file id cannot break out of its segment. Written here
137/// rather than pulling in a crate for four lines.
138pub fn encode_path_segment(value: &str) -> String {
139    let mut encoded = String::with_capacity(value.len());
140    for byte in value.as_bytes() {
141        match byte {
142            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
143                encoded.push(*byte as char)
144            }
145            _ => encoded.push_str(&format!("%{:02X}", byte)),
146        }
147    }
148    encoded
149}
150
151pub const BULK_URI: &str = "https://bulkapi.zerobounce.net/v2";
152/// The list evaluator and the Inbox Placement Tester are not under the bulk /v2 path.
153pub const LIST_EVALUATOR_URI: &str = "https://bulkapi.zerobounce.net/v2/listevaluator";
154pub const INBOX_PLACEMENT_URI: &str = "https://bulkapi.zerobounce.net/api/ipt";
155pub const ENDPOINT_CREDITS: &str = "/getcredits";
156pub const ENDPOINT_ACTIVITY_DATA: &str = "/activity";
157pub const ENDPOINT_SCORING: &str = "/scoring";
158pub const ENDPOINT_VALIDATE: &str = "/validate";
159pub const ENDPOINT_API_USAGE: &str = "/getapiusage";
160pub const ENDPOINT_BATCH_VALIDATE: &str = "/validatebatch";
161pub const ENDPOINT_FILE_SEND: &str = "/sendfile";
162pub const ENDPOINT_FILE_STATUS: &str = "/filestatus";
163pub const ENDPOINT_FILE_RESULT: &str = "/getfile";
164pub const ENDPOINT_FILE_DELETE: &str = "/deletefile";
165pub const ENDPOINT_SCORING_SEND: &str = "/scoring/sendfile";
166pub const ENDPOINT_SCORING_STATUS: &str = "/scoring/filestatus";
167pub const ENDPOINT_SCORING_RESULT: &str = "/scoring/getfile";
168pub const ENDPOINT_SCORING_DELETE: &str = "/scoring/deletefile";
169pub const ENDPOINT_EMAIL_FINDER: &str = "/guessformat";
170
171// validation statuses
172pub const S_VALID: &str = "valid";
173pub const S_INVALID: &str = "invalid";
174pub const S_CATCH_ALL: &str = "catch-all";
175pub const S_UNKNOWN: &str = "unknown";
176pub const S_SPAMTRAP: &str = "spamtrap";
177pub const S_ABUSE: &str = "abuse";
178pub const S_DO_NOT_MAIL: &str = "do_not_mail";
179
180// validation sub statuses
181pub const SS_ANTISPAM_SYSTEM: &str = "antispam_system";
182pub const SS_GREYLISTED: &str = "greylisted";
183pub const SS_MAIL_SERVER_TEMPORARY_ERROR: &str = "mail_server_temporary_error";
184pub const SS_FORCIBLE_DISCONNECT: &str = "forcible_disconnect";
185pub const SS_MAIL_SERVER_DID_NOT_RESPOND: &str = "mail_server_did_not_respond";
186pub const SS_TIMEOUT_EXCEEDED: &str = "timeout_exceeded";
187pub const SS_FAILED_SMTP_CONNECTION: &str = "failed_smtp_connection";
188pub const SS_MAILBOX_QUOTA_EXCEEDED: &str = "mailbox_quota_exceeded";
189pub const SS_EXCEPTION_OCCURRED: &str = "exception_occurred";
190pub const SS_POSSIBLE_TRAP: &str = "possible_trap";
191pub const SS_ROLE_BASED: &str = "role_based";
192pub const SS_GLOBAL_SUPPRESSION: &str = "global_suppression";
193pub const SS_MAILBOX_NOT_FOUND: &str = "mailbox_not_found";
194pub const SS_NO_DNS_ENTRIES: &str = "no_dns_entries";
195pub const SS_FAILED_SYNTAX_CHECK: &str = "failed_syntax_check";
196pub const SS_POSSIBLE_TYPO: &str = "possible_typo";
197pub const SS_UNROUTABLE_IP_ADDRESS: &str = "unroutable_ip_address";
198pub const SS_LEADING_PERIOD_REMOVED: &str = "leading_period_removed";
199pub const SS_DOES_NOT_ACCEPT_MAIL: &str = "does_not_accept_mail";
200pub const SS_ALIAS_ADDRESS: &str = "alias_address";
201pub const SS_ROLE_BASED_CATCH_ALL: &str = "role_based_catch_all";
202pub const SS_DISPOSABLE: &str = "disposable";
203pub const SS_TOXIC: &str = "toxic";
204pub const SS_ACCEPT_ALL: &str = "accept_all";
205pub const SS_AI_AGENT_MAILBOX: &str = "ai_agent_mailbox";
206
207/// Every error the SDK returns.
208///
209/// `#[non_exhaustive]`: a variant added later is not a breaking change, so a
210/// `match` on it needs a `_` arm.
211#[derive(Debug)]
212#[non_exhaustive]
213pub enum ZBError {
214    /// An error the SDK raised itself: an invalid argument or URL caught before
215    /// a request, or a 2xx response body it could not read.
216    ExplicitError(String),
217    /// The API answered and the answer is a failure: a non-2xx status, an HTML
218    /// error page, an error body on an HTTP 200, a bulk `getfile` error, or a
219    /// `batch_validate` account-level error. `status` is the HTTP status of that
220    /// response, so callers can tell a 403 from Cloudflare apart from a 400/404
221    /// from the API and a 429 from the Warmup rate limit. Both the validation
222    /// client and the Warmup client return it.
223    ApiError { status: u16, message: String },
224    JsonError(serde_json::Error),
225    IntParseError(std::num::ParseIntError),
226    RequestError(reqwest::Error),
227    IOError(IOError),
228}
229
230pub type ZBResult<T> = Result<T, ZBError>;
231
232impl ZBError {
233    pub fn explicit(string: &str) -> ZBError {
234        ZBError::ExplicitError(string.to_string())
235    }
236
237    pub fn api(status: u16, message: impl Into<String>) -> ZBError {
238        ZBError::ApiError {
239            status,
240            message: message.into(),
241        }
242    }
243
244    /// The HTTP status of a failed API response: `Some` for every
245    /// [`ZBError::ApiError`], including a failure the API reports with an HTTP
246    /// 200. `None` when no failed response is involved: an argument or URL
247    /// rejected before a request, a transport error, or a 2xx body that could
248    /// not be parsed.
249    pub fn status_code(&self) -> Option<u16> {
250        match self {
251            ZBError::ApiError { status, .. } => Some(*status),
252            _ => None,
253        }
254    }
255}
256
257impl std::fmt::Display for ZBError {
258    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
259        match self {
260            ZBError::ExplicitError(message) => write!(formatter, "{message}"),
261            ZBError::ApiError { message, .. } => write!(formatter, "{message}"),
262            ZBError::JsonError(_) => {
263                write!(
264                    formatter,
265                    "ZeroBounce returned a response that is not valid JSON."
266                )
267            }
268            ZBError::IntParseError(_) => write!(
269                formatter,
270                "ZeroBounce returned a response that could not be read."
271            ),
272            ZBError::RequestError(error) => write!(formatter, "{error}"),
273            ZBError::IOError(error) => write!(formatter, "{error}"),
274        }
275    }
276}
277
278impl std::error::Error for ZBError {}
279
280// Implementation made in order to automatically convert errors
281// generated by the reqwuest library into a ZBError instance.
282//
283// This automatic conversion is expected when using the client
284// and issuing http requests.
285fn redact_api_key(url: &mut reqwest::Url) {
286    if !url.query_pairs().any(|(key, _)| key == "api_key") {
287        return;
288    }
289    let pairs: Vec<(String, String)> = url
290        .query_pairs()
291        .map(|(key, value)| {
292            let value = if key == "api_key" {
293                "REDACTED".to_string()
294            } else {
295                value.into_owned()
296            };
297            (key.into_owned(), value)
298        })
299        .collect();
300    url.query_pairs_mut().clear().extend_pairs(pairs);
301}
302
303impl From<reqwest::Error> for ZBError {
304    fn from(mut value: reqwest::Error) -> ZBError {
305        if let Some(url) = value.url_mut() {
306            redact_api_key(url);
307        }
308        ZBError::RequestError(value)
309    }
310}
311
312// Implementation made in order to automatically convert errors
313// generated by the serde_json library into a ZBError instance.
314//
315// This automatic conversion is expected when deserializing.
316impl From<serde_json::Error> for ZBError {
317    fn from(value: serde_json::Error) -> ZBError {
318        ZBError::JsonError(value)
319    }
320}
321
322impl From<IOError> for ZBError {
323    fn from(value: IOError) -> Self {
324        ZBError::IOError(value)
325    }
326}