Skip to main content

zero_bounce/
lib.rs

1pub mod api;
2pub mod utility;
3pub mod warmup;
4
5pub use crate::api::{DomainSearchV2Builder, FindEmailV2Builder};
6pub use crate::utility::structures::bulk::{
7    zb_download_type, ZBBulkResponse, ZBEmailFinderFileOptions, ZBFile, ZBFileFeedback,
8    ZBFileStatus, ZBGetFileOptions,
9};
10pub use crate::utility::structures::validate_enums::{ZBValidateStatus, ZBValidateSubStatus};
11pub use crate::utility::structures::{ActivityData, ApiUsage};
12pub use crate::utility::{format_get_file_error_message, get_file_json_indicates_error};
13pub use crate::utility::{ApiBaseUrl, ZBError, ZBResult};
14#[allow(deprecated)]
15pub use crate::warmup::{EmailContent, ManagedSending};
16pub use crate::warmup::{OnboardingModel, ZbManagedEmailContent, ZbManagedSending, ZeroBounceWarmup};
17
18/// The base URLs requests are built from.
19///
20/// Start from [`ZBUrlProvider::default()`] (the live hosts) and assign the fields
21/// you want to change. The struct is `#[non_exhaustive]`, so it cannot be built
22/// with a struct literal outside this crate and a base URL added later is not a
23/// breaking change.
24///
25/// Every request checks its final URL: it must be `https://`, or `http://` with
26/// the exact host `127.0.0.1`, `localhost` or `[::1]` (for local tests). Any
27/// other URL fails with an error before a connection is opened, so the API key
28/// is never sent in cleartext.
29#[derive(Clone, Debug)]
30#[non_exhaustive]
31pub struct ZBUrlProvider {
32    pub url: String,
33    pub bulk_url: String,
34    /// Overridable; the list evaluator path differs from the other bulk endpoints.
35    pub list_evaluator_url: String,
36    /// Overridable; the Inbox Placement Tester is not under the bulk /v2 path.
37    pub inbox_placement_url: String,
38}
39
40/// `base` and `endpoint` joined by exactly one slash. The built-in base URLs
41/// end in `/v2/` and every endpoint starts with `/`, which used to give
42/// `/v2//validate`; trailing slashes on any base URL are now dropped.
43fn join_url(base: &str, endpoint: &str) -> String {
44    let base = base.trim_end_matches('/');
45    if endpoint.is_empty() || endpoint.starts_with('/') {
46        format!("{base}{endpoint}")
47    } else {
48        format!("{base}/{endpoint}")
49    }
50}
51
52impl ZBUrlProvider {
53    pub fn url_of(&self, endpoint: &str) -> String {
54        join_url(&self.url, endpoint)
55    }
56    pub fn bulk_url_of(&self, endpoint: &str) -> String {
57        join_url(&self.bulk_url, endpoint)
58    }
59    pub fn list_evaluator_url_of(&self, endpoint: &str) -> String {
60        join_url(&self.list_evaluator_url, endpoint)
61    }
62    pub fn inbox_placement_url_of(&self, endpoint: &str) -> String {
63        join_url(&self.inbox_placement_url, endpoint)
64    }
65}
66
67impl Default for ZBUrlProvider {
68    fn default() -> Self {
69        ZBUrlProvider {
70            url: ApiBaseUrl::Default.as_str().to_string(),
71            bulk_url: crate::utility::BULK_URI.to_string(),
72            list_evaluator_url: crate::utility::LIST_EVALUATOR_URI.to_string(),
73            inbox_placement_url: crate::utility::INBOX_PLACEMENT_URI.to_string(),
74        }
75    }
76}
77
78// Client offering methods for different API methods and functionalities
79pub struct ZeroBounce {
80    pub api_key: String,
81    pub base_url: String,
82    pub client: reqwest::blocking::Client,
83    pub url_provider: ZBUrlProvider,
84}
85
86/// Names the type and every field, with the API key shown as `***`.
87impl std::fmt::Debug for ZeroBounce {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_struct("ZeroBounce")
90            .field("api_key", &utility::redacted_key(&self.api_key))
91            .field("base_url", &self.base_url)
92            .field("client", &self.client)
93            .field("url_provider", &self.url_provider)
94            .finish()
95    }
96}
97
98// More method implementations of this class can be found throughout
99// the project.
100impl ZeroBounce {
101    /// Create a new ZeroBounce client instance with the default API URL.
102    ///
103    /// # Arguments
104    /// * `api_key` - Your ZeroBounce API key
105    ///
106    /// # Example
107    /// ```no_run
108    /// use zero_bounce::ZeroBounce;
109    ///
110    /// let zb = ZeroBounce::new("your_api_key");
111    /// ```
112    ///
113    /// # Panics
114    /// When the HTTP client cannot be built (for example, the TLS backend
115    /// fails to initialise), as `reqwest::blocking::Client::new()` does.
116    /// [`with_base_url`](Self::with_base_url) returns that as an error instead.
117    pub fn new(api_key: &str) -> ZeroBounce {
118        Self::build(api_key, ApiBaseUrl::Default.as_str().to_string())
119            .unwrap_or_else(|error| panic!("ZeroBounce::new: {error}"))
120    }
121
122    /// Create a new ZeroBounce client instance with a custom base URL.
123    ///
124    /// # Arguments
125    /// * `api_key` - Your ZeroBounce API key
126    /// * `base_url` - Base URL. Can be:
127    ///   - `ApiBaseUrl::Default` - Uses the default API URL
128    ///   - `ApiBaseUrl::USA` - Uses the USA API URL
129    ///   - `ApiBaseUrl::EU` - Uses the EU API URL
130    ///   - `String` or `&str` - Uses a custom URL string
131    ///
132    /// # Errors
133    /// Returns [`ZBError::ExplicitError`] when `base_url` is not an `https://`
134    /// URL. `http://` is accepted only for the exact hosts `127.0.0.1`,
135    /// `localhost` and `[::1]`, for local tests. Also when the HTTP client
136    /// cannot be built.
137    ///
138    /// # Example
139    /// ```no_run
140    /// use zero_bounce::{ZeroBounce, ApiBaseUrl};
141    ///
142    /// # fn main() -> Result<(), zero_bounce::ZBError> {
143    /// // Using enum
144    /// let zb = ZeroBounce::with_base_url("your_api_key", ApiBaseUrl::USA)?;
145    ///
146    /// // Using custom string
147    /// let zb = ZeroBounce::with_base_url("your_api_key", "https://custom-api.example.com/v2/")?;
148    /// # Ok(())
149    /// # }
150    /// ```
151    pub fn with_base_url<T>(api_key: &str, base_url: T) -> ZBResult<ZeroBounce>
152    where
153        T: Into<String>,
154    {
155        let base_url_string = base_url.into();
156        parse_request_url(&base_url_string)?;
157        Self::build(api_key, base_url_string)
158    }
159
160    /// The client both constructors share. Only [`with_base_url`](Self::with_base_url)
161    /// takes a caller's URL, and it checks it first.
162    fn build(api_key: &str, base_url_string: String) -> ZBResult<ZeroBounce> {
163        let url_provider = ZBUrlProvider {
164            url: base_url_string.clone(),
165            ..ZBUrlProvider::default()
166        };
167
168        Ok(ZeroBounce {
169            api_key: api_key.to_string(),
170            base_url: base_url_string,
171            client: utility::http_client()?,
172            url_provider,
173        })
174    }
175
176    fn require_key(&self) -> ZBResult<()> {
177        if self.api_key.trim().is_empty() {
178            return Err(ZBError::explicit("api_key is required"));
179        }
180        utility::check_key_text(&self.api_key)
181    }
182
183    /// `error` with this client's key masked in its message. Every error built
184    /// from a response body passes through here.
185    fn redact_error(&self, error: ZBError) -> ZBError {
186        error.redacted(&[self.api_key.as_str()])
187    }
188
189    /// The status, content type and body of a response, the body read up to
190    /// the JSON size cap. Checking it is the caller's job.
191    fn read_api_body(response: reqwest::blocking::Response) -> ZBResult<(u16, String, String)> {
192        let status = response.status().as_u16();
193        let content_type = response
194            .headers()
195            .get(reqwest::header::CONTENT_TYPE)
196            .and_then(|value| value.to_str().ok())
197            .unwrap_or("")
198            .to_string();
199        let body = utility::read_limited(
200            response,
201            utility::MAX_JSON_RESPONSE_BYTES,
202            status,
203            "response body exceeds size limit",
204        )?;
205        Ok((status, content_type, String::from_utf8_lossy(&body).into_owned()))
206    }
207}
208
209/// Whether the authority of `url`, as written, holds an `@`. The parsed URL
210/// drops an empty userinfo (`https://@host`, `https://:@host`), so the text
211/// is checked too.
212fn has_userinfo_marker(url: &str) -> bool {
213    let cleaned: String = url.chars().filter(|c| !matches!(c, '\t' | '\n' | '\r')).collect();
214    let after_scheme = cleaned
215        .trim_matches(|c: char| c <= ' ')
216        .split_once(':')
217        .map_or("", |(_, rest)| rest);
218    let authority = after_scheme
219        .trim_start_matches(['/', '\\'])
220        .split(['/', '\\', '?', '#'])
221        .next()
222        .unwrap_or("");
223    authority.contains('@')
224}
225
226/// Fixed refusal texts of [`parse_request_url`]; the Warmup client matches them.
227pub(crate) const USERINFO_MESSAGE: &str = "request URL must not contain a username or password";
228pub(crate) const URL_TEXT_MESSAGE: &str = "request URL must not contain a query, a fragment, a backslash, whitespace or control characters";
229
230/// Parse a request URL and enforce the transport rule every request follows:
231/// `https://`, or `http://` only for the exact loopback hosts `127.0.0.1`,
232/// `localhost` and `[::1]`. Every request path calls this on its final URL,
233/// so an `http://` override on [`ZBUrlProvider`] can never put the API key on
234/// the wire in cleartext.
235///
236/// A URL with a username or a password is refused first, whatever its scheme
237/// (`https://api.zerobounce.net@evil.example/v2` is a request to
238/// `evil.example`). Every message here is fixed text: none quotes the URL,
239/// which may hold credentials.
240pub(crate) fn parse_request_url(url: &str) -> ZBResult<reqwest::Url> {
241    let parsed = reqwest::Url::parse(url)
242        .map_err(|_| ZBError::ExplicitError("request URL is not a valid URL".into()))?;
243    if !parsed.username().is_empty() || parsed.password().is_some() || has_userinfo_marker(url) {
244        return Err(ZBError::ExplicitError(
245            USERINFO_MESSAGE.into(),
246        ));
247    }
248    let scheme_ok = parsed.scheme() == "https"
249        || (parsed.scheme() == "http"
250            && matches!(parsed.host_str(), Some("127.0.0.1") | Some("localhost") | Some("[::1]")));
251    if scheme_ok {
252        // The SDK adds its own path and query, so a query or fragment in the
253        // URL, or whitespace, a control or an invisible character anywhere in
254        // it, would send the request somewhere else.
255        if url.contains(['?', '#', '\\'])
256            || url.chars().any(|c| {
257                c.is_control() || c.is_whitespace() || utility::is_invisible_char(c)
258            })
259        {
260            return Err(ZBError::ExplicitError(URL_TEXT_MESSAGE.into()));
261        }
262        return Ok(parsed);
263    }
264    Err(ZBError::ExplicitError(
265        "request URL must use https:// (http:// is allowed only for 127.0.0.1, localhost and [::1])"
266            .into(),
267    ))
268}
269
270#[cfg(test)]
271mod security_tests {
272    use super::{parse_request_url, ZeroBounce};
273
274    #[test]
275    fn accepts_https() {
276        let zb = ZeroBounce::with_base_url("key", "https://api.zerobounce.net/v2/").unwrap();
277        assert_eq!(zb.base_url, "https://api.zerobounce.net/v2/");
278        assert_eq!(zb.url_provider.url, "https://api.zerobounce.net/v2/");
279    }
280
281    #[test]
282    fn accepts_loopback_http() {
283        for url in [
284            "http://127.0.0.1:1234/",
285            "http://localhost:1234/",
286            "http://[::1]:1234/",
287        ] {
288            let zb = ZeroBounce::with_base_url("key", url).unwrap();
289            assert_eq!(zb.base_url, url);
290        }
291    }
292
293    fn rejected(url: &str) -> String {
294        match ZeroBounce::with_base_url("key", url) {
295            Ok(_) => panic!("{url} was accepted"),
296            Err(error) => error.to_string(),
297        }
298    }
299
300    #[test]
301    fn rejects_remote_http() {
302        assert!(rejected("http://evil.example/v2/").contains("https://"));
303    }
304
305    #[test]
306    fn rejects_loopback_lookalike_host() {
307        assert!(rejected("http://localhost.evil.example/v2/").contains("https://"));
308    }
309
310    #[test]
311    fn rejects_loopback_userinfo_trick() {
312        assert!(rejected("http://127.0.0.1@evil.example/v2/").contains("username or password"));
313    }
314
315    #[test]
316    fn rejects_other_loopback_spellings_and_garbage() {
317        for url in ["http://127.0.0.2/v2/", "http://0.0.0.0/v2/", "ftp://127.0.0.1/"] {
318            assert!(rejected(url).contains("https://"), "{url}");
319        }
320        assert_eq!(rejected("not a url"), "request URL is not a valid URL");
321    }
322
323    #[test]
324    fn request_urls_with_credentials_are_refused_before_the_scheme_check() {
325        for url in [
326            "https://api.zerobounce.net@evil.example/v2",
327            "http://user:pw@127.0.0.1/v2",
328            "https://user:pw@api.zerobounce.net/v2",
329            "http://user@127.0.0.1/v2",
330            "https://:pw@example.com/",
331            "https://@example.com/",
332            "https://:@example.com/",
333        ] {
334            let error = parse_request_url(url).unwrap_err().to_string();
335            assert_eq!(error, "request URL must not contain a username or password", "{url}");
336            assert!(!error.contains("evil") && !error.contains("pw"), "{url}: {error}");
337            assert!(ZeroBounce::with_base_url("key", url).is_err(), "{url}");
338        }
339        // Still the existing scheme rule.
340        assert!(parse_request_url("http://127.0.0.1").is_ok());
341        assert!(parse_request_url("https://example.com").is_ok());
342        let error = parse_request_url("http://example.com").unwrap_err().to_string();
343        assert!(error.contains("https://"), "{error}");
344    }
345
346    #[test]
347    fn a_url_that_does_not_parse_gets_a_fixed_message_without_the_url() {
348        let error = parse_request_url("https://secret-host-xyz:notaport/v2").unwrap_err().to_string();
349        assert_eq!(error, "request URL is not a valid URL");
350        assert!(!error.contains("secret-host-xyz"), "{error}");
351    }
352
353    #[test]
354    fn request_urls_follow_the_same_rule() {
355        assert!(parse_request_url("https://bulkapi.zerobounce.net/v2/sendfile").is_ok());
356        assert!(parse_request_url("http://localhost:8080/v2/getfile").is_ok());
357        let error = parse_request_url("http://bulkapi.zerobounce.net/v2/sendfile").unwrap_err();
358        assert!(error.to_string().contains("https://"), "{error}");
359    }
360}