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#[derive(Clone, Debug)]
30#[non_exhaustive]
31pub struct ZBUrlProvider {
32 pub url: String,
33 pub bulk_url: String,
34 pub list_evaluator_url: String,
36 pub inbox_placement_url: String,
38}
39
40fn 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
78pub 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
86impl 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
98impl ZeroBounce {
101 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 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 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 fn redact_error(&self, error: ZBError) -> ZBError {
186 error.redacted(&[self.api_key.as_str()])
187 }
188
189 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
209fn 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
226pub(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
230pub(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 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 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}