Skip to main content

zero_bounce/
lib.rs

1pub mod api;
2pub mod utility;
3pub mod warmup;
4
5use std::collections::HashMap;
6use std::time::Duration;
7
8pub use crate::api::{DomainSearchV2Builder, FindEmailV2Builder};
9pub use crate::utility::structures::bulk::{
10    zb_download_type, ZBBulkResponse, ZBEmailFinderFileOptions, ZBFile, ZBFileFeedback,
11    ZBFileStatus, ZBGetFileOptions,
12};
13pub use crate::utility::structures::validate_enums::{ZBValidateStatus, ZBValidateSubStatus};
14pub use crate::utility::structures::{ActivityData, ApiUsage};
15pub use crate::utility::{format_get_file_error_message, get_file_json_indicates_error};
16pub use crate::utility::{ApiBaseUrl, ZBError, ZBResult};
17pub use crate::warmup::{EmailContent, ManagedSending, OnboardingModel, ZeroBounceWarmup};
18
19/// The base URLs requests are built from.
20///
21/// Start from [`ZBUrlProvider::default()`] (the live hosts) and assign the fields
22/// you want to change. The struct is `#[non_exhaustive]`, so it cannot be built
23/// with a struct literal outside this crate and a base URL added later is not a
24/// breaking change.
25///
26/// Every request checks its final URL: it must be `https://`, or `http://` with
27/// the exact host `127.0.0.1`, `localhost` or `[::1]` (for local tests). Any
28/// other URL fails with an error before a connection is opened, so the API key
29/// is never sent in cleartext.
30#[derive(Clone, Debug)]
31#[non_exhaustive]
32pub struct ZBUrlProvider {
33    pub url: String,
34    pub bulk_url: String,
35    /// Overridable; the list evaluator path differs from the other bulk endpoints.
36    pub list_evaluator_url: String,
37    /// Overridable; the Inbox Placement Tester is not under the bulk /v2 path.
38    pub inbox_placement_url: String,
39}
40
41impl ZBUrlProvider {
42    pub fn url_of(&self, endpoint: &str) -> String {
43        self.url.to_owned() + endpoint
44    }
45    pub fn bulk_url_of(&self, endpoint: &str) -> String {
46        self.bulk_url.to_owned() + endpoint
47    }
48    pub fn list_evaluator_url_of(&self, endpoint: &str) -> String {
49        self.list_evaluator_url.to_owned() + endpoint
50    }
51    pub fn inbox_placement_url_of(&self, endpoint: &str) -> String {
52        self.inbox_placement_url.to_owned() + endpoint
53    }
54}
55
56impl Default for ZBUrlProvider {
57    fn default() -> Self {
58        ZBUrlProvider {
59            url: ApiBaseUrl::Default.as_str().to_string(),
60            bulk_url: crate::utility::BULK_URI.to_string(),
61            list_evaluator_url: crate::utility::LIST_EVALUATOR_URI.to_string(),
62            inbox_placement_url: crate::utility::INBOX_PLACEMENT_URI.to_string(),
63        }
64    }
65}
66
67// Client offering methods for different API methods and functionalities
68pub struct ZeroBounce {
69    pub api_key: String,
70    pub base_url: String,
71    pub client: reqwest::blocking::Client,
72    pub url_provider: ZBUrlProvider,
73}
74
75// More method implementations of this class can be found throughout
76// the project.
77impl ZeroBounce {
78    /// Create a new ZeroBounce client instance with the default API URL.
79    ///
80    /// # Arguments
81    /// * `api_key` - Your ZeroBounce API key
82    ///
83    /// # Example
84    /// ```no_run
85    /// use zero_bounce::ZeroBounce;
86    ///
87    /// let zb = ZeroBounce::new("your_api_key");
88    /// ```
89    pub fn new(api_key: &str) -> ZeroBounce {
90        Self::build(api_key, ApiBaseUrl::Default.as_str().to_string())
91    }
92
93    /// Create a new ZeroBounce client instance with a custom base URL.
94    ///
95    /// # Arguments
96    /// * `api_key` - Your ZeroBounce API key
97    /// * `base_url` - Base URL. Can be:
98    ///   - `ApiBaseUrl::Default` - Uses the default API URL
99    ///   - `ApiBaseUrl::USA` - Uses the USA API URL
100    ///   - `ApiBaseUrl::EU` - Uses the EU API URL
101    ///   - `String` or `&str` - Uses a custom URL string
102    ///
103    /// # Errors
104    /// Returns [`ZBError::ExplicitError`] when `base_url` is not an `https://`
105    /// URL. `http://` is accepted only for the exact hosts `127.0.0.1`,
106    /// `localhost` and `[::1]`, for local tests.
107    ///
108    /// # Example
109    /// ```no_run
110    /// use zero_bounce::{ZeroBounce, ApiBaseUrl};
111    ///
112    /// # fn main() -> Result<(), zero_bounce::ZBError> {
113    /// // Using enum
114    /// let zb = ZeroBounce::with_base_url("your_api_key", ApiBaseUrl::USA)?;
115    ///
116    /// // Using custom string
117    /// let zb = ZeroBounce::with_base_url("your_api_key", "https://custom-api.example.com/v2/")?;
118    /// # Ok(())
119    /// # }
120    /// ```
121    pub fn with_base_url<T>(api_key: &str, base_url: T) -> ZBResult<ZeroBounce>
122    where
123        T: Into<String>,
124    {
125        let base_url_string = base_url.into();
126        parse_request_url(&base_url_string)
127            .map_err(|_| ZBError::explicit("base_url must be an https:// URL"))?;
128        Ok(Self::build(api_key, base_url_string))
129    }
130
131    /// The client both constructors share. Only [`with_base_url`](Self::with_base_url)
132    /// takes a caller's URL, and it checks it first.
133    fn build(api_key: &str, base_url_string: String) -> ZeroBounce {
134        let url_provider = ZBUrlProvider {
135            url: base_url_string.clone(),
136            ..ZBUrlProvider::default()
137        };
138
139        ZeroBounce {
140            api_key: api_key.to_string(),
141            base_url: base_url_string,
142            client: reqwest::blocking::Client::builder()
143                .timeout(Duration::from_secs(120))
144                .redirect(reqwest::redirect::Policy::none())
145                .build()
146                .unwrap_or_else(|_| reqwest::blocking::Client::default()),
147            url_provider,
148        }
149    }
150
151    fn require_key(&self) -> ZBResult<()> {
152        if self.api_key.trim().is_empty() {
153            return Err(ZBError::explicit("api_key is required"));
154        }
155        Ok(())
156    }
157
158    fn read_api_response(&self, response: reqwest::blocking::Response) -> ZBResult<String> {
159        self.read_api_response_checked(response, false)
160    }
161
162    fn read_api_response_checked(
163        &self,
164        response: reqwest::blocking::Response,
165        message_only_is_failure: bool,
166    ) -> ZBResult<String> {
167        let status = response.status().as_u16();
168        let content_type = response
169            .headers()
170            .get(reqwest::header::CONTENT_TYPE)
171            .and_then(|value| value.to_str().ok())
172            .unwrap_or("")
173            .to_string();
174        let body = utility::read_limited(
175            response,
176            utility::MAX_JSON_RESPONSE_BYTES,
177            "response body exceeds size limit",
178        )?;
179        let response_content = String::from_utf8_lossy(&body).into_owned();
180        utility::http_error::ensure_json_api_body(status, &content_type, &response_content)?;
181        if message_only_is_failure {
182            utility::http_error::reject_message_only_body(status, &content_type, &response_content)?;
183        }
184        Ok(response_content)
185    }
186
187    fn generic_get_request<'a>(
188        &'a self,
189        url: String,
190        query_args: HashMap<&'a str, &'a str>,
191    ) -> ZBResult<String> {
192        self.get_request_checked(url, query_args, false)
193    }
194
195    /// `generic_get_request` for a call whose result is never a bare message
196    /// (the email finder and domain search), so a message-only body is an error.
197    fn finder_get_request<'a>(
198        &'a self,
199        url: String,
200        query_args: HashMap<&'a str, &'a str>,
201    ) -> ZBResult<String> {
202        self.get_request_checked(url, query_args, true)
203    }
204
205    fn get_request_checked<'a>(
206        &'a self,
207        url: String,
208        mut query_args: HashMap<&'a str, &'a str>,
209        message_only_is_failure: bool,
210    ) -> ZBResult<String> {
211        self.require_key()?;
212        query_args.insert("api_key", self.api_key.as_str());
213
214        let response = self
215            .client
216            .get(parse_request_url(&url)?)
217            .query(&query_args)
218            .send()?;
219        self.read_api_response_checked(response, message_only_is_failure)
220    }
221
222    fn generic_form_post_request<'a>(
223        &'a self,
224        url: String,
225        mut form_args: HashMap<&'a str, &'a str>,
226    ) -> ZBResult<String> {
227        self.require_key()?;
228        form_args.insert("api_key", self.api_key.as_str());
229
230        let response = self
231            .client
232            .post(parse_request_url(&url)?)
233            .form(&form_args)
234            .send()?;
235        self.read_api_response(response)
236    }
237}
238
239/// Parse a request URL and enforce the transport rule every request follows:
240/// `https://`, or `http://` only for the exact loopback hosts `127.0.0.1`,
241/// `localhost` and `[::1]`. Every request path calls this on its final URL,
242/// so an `http://` override on [`ZBUrlProvider`] can never put the API key on
243/// the wire in cleartext.
244pub(crate) fn parse_request_url(url: &str) -> ZBResult<reqwest::Url> {
245    let parsed = reqwest::Url::parse(url).map_err(|e| ZBError::ExplicitError(e.to_string()))?;
246    if parsed.scheme() == "https" {
247        return Ok(parsed);
248    }
249    if parsed.scheme() == "http" {
250        match parsed.host_str() {
251            Some("127.0.0.1") | Some("localhost") | Some("[::1]") => return Ok(parsed),
252            _ => {}
253        }
254    }
255    Err(ZBError::ExplicitError(
256        "request URL must use https:// (http:// is allowed only for 127.0.0.1, localhost and [::1])"
257            .into(),
258    ))
259}
260
261#[cfg(test)]
262mod security_tests {
263    use super::{parse_request_url, ZeroBounce};
264
265    #[test]
266    fn accepts_https() {
267        let zb = ZeroBounce::with_base_url("key", "https://api.zerobounce.net/v2/").unwrap();
268        assert_eq!(zb.base_url, "https://api.zerobounce.net/v2/");
269        assert_eq!(zb.url_provider.url, "https://api.zerobounce.net/v2/");
270    }
271
272    #[test]
273    fn accepts_loopback_http() {
274        for url in [
275            "http://127.0.0.1:1234/",
276            "http://localhost:1234/",
277            "http://[::1]:1234/",
278        ] {
279            let zb = ZeroBounce::with_base_url("key", url).unwrap();
280            assert_eq!(zb.base_url, url);
281        }
282    }
283
284    fn rejected(url: &str) -> String {
285        match ZeroBounce::with_base_url("key", url) {
286            Ok(_) => panic!("{url} was accepted"),
287            Err(error) => error.to_string(),
288        }
289    }
290
291    #[test]
292    fn rejects_remote_http() {
293        assert!(rejected("http://evil.example/v2/").contains("https://"));
294    }
295
296    #[test]
297    fn rejects_loopback_lookalike_host() {
298        assert!(rejected("http://localhost.evil.example/v2/").contains("https://"));
299    }
300
301    #[test]
302    fn rejects_loopback_userinfo_trick() {
303        assert!(rejected("http://127.0.0.1@evil.example/v2/").contains("https://"));
304    }
305
306    #[test]
307    fn rejects_other_loopback_spellings_and_garbage() {
308        for url in ["http://127.0.0.2/v2/", "http://0.0.0.0/v2/", "ftp://127.0.0.1/", "not a url"] {
309            assert!(rejected(url).contains("https://"), "{url}");
310        }
311    }
312
313    #[test]
314    fn request_urls_follow_the_same_rule() {
315        assert!(parse_request_url("https://bulkapi.zerobounce.net/v2/sendfile").is_ok());
316        assert!(parse_request_url("http://localhost:8080/v2/getfile").is_ok());
317        let error = parse_request_url("http://bulkapi.zerobounce.net/v2/sendfile").unwrap_err();
318        assert!(error.to_string().contains("https://"), "{error}");
319    }
320}