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#[derive(Clone, Debug)]
31#[non_exhaustive]
32pub struct ZBUrlProvider {
33 pub url: String,
34 pub bulk_url: String,
35 pub list_evaluator_url: String,
37 pub inbox_placement_url: String,
39}
40
41fn join_url(base: &str, endpoint: &str) -> String {
45 let base = base.trim_end_matches('/');
46 if endpoint.is_empty() || endpoint.starts_with('/') {
47 format!("{base}{endpoint}")
48 } else {
49 format!("{base}/{endpoint}")
50 }
51}
52
53impl ZBUrlProvider {
54 pub fn url_of(&self, endpoint: &str) -> String {
55 join_url(&self.url, endpoint)
56 }
57 pub fn bulk_url_of(&self, endpoint: &str) -> String {
58 join_url(&self.bulk_url, endpoint)
59 }
60 pub fn list_evaluator_url_of(&self, endpoint: &str) -> String {
61 join_url(&self.list_evaluator_url, endpoint)
62 }
63 pub fn inbox_placement_url_of(&self, endpoint: &str) -> String {
64 join_url(&self.inbox_placement_url, endpoint)
65 }
66}
67
68impl Default for ZBUrlProvider {
69 fn default() -> Self {
70 ZBUrlProvider {
71 url: ApiBaseUrl::Default.as_str().to_string(),
72 bulk_url: crate::utility::BULK_URI.to_string(),
73 list_evaluator_url: crate::utility::LIST_EVALUATOR_URI.to_string(),
74 inbox_placement_url: crate::utility::INBOX_PLACEMENT_URI.to_string(),
75 }
76 }
77}
78
79pub struct ZeroBounce {
81 pub api_key: String,
82 pub base_url: String,
83 pub client: reqwest::blocking::Client,
84 pub url_provider: ZBUrlProvider,
85}
86
87impl std::fmt::Debug for ZeroBounce {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct("ZeroBounce")
91 .field("api_key", &utility::redacted_key(&self.api_key))
92 .field("base_url", &self.base_url)
93 .field("client", &self.client)
94 .field("url_provider", &self.url_provider)
95 .finish()
96 }
97}
98
99impl ZeroBounce {
102 pub fn new(api_key: &str) -> ZeroBounce {
114 Self::build(api_key, ApiBaseUrl::Default.as_str().to_string())
115 }
116
117 pub fn with_base_url<T>(api_key: &str, base_url: T) -> ZBResult<ZeroBounce>
146 where
147 T: Into<String>,
148 {
149 let base_url_string = base_url.into();
150 parse_request_url(&base_url_string)
151 .map_err(|_| ZBError::explicit("base_url must be an https:// URL"))?;
152 Ok(Self::build(api_key, base_url_string))
153 }
154
155 fn build(api_key: &str, base_url_string: String) -> ZeroBounce {
158 let url_provider = ZBUrlProvider {
159 url: base_url_string.clone(),
160 ..ZBUrlProvider::default()
161 };
162
163 ZeroBounce {
164 api_key: api_key.to_string(),
165 base_url: base_url_string,
166 client: reqwest::blocking::Client::builder()
167 .timeout(Duration::from_secs(120))
168 .redirect(reqwest::redirect::Policy::none())
169 .build()
170 .unwrap_or_else(|_| reqwest::blocking::Client::default()),
171 url_provider,
172 }
173 }
174
175 fn require_key(&self) -> ZBResult<()> {
176 if self.api_key.trim().is_empty() {
177 return Err(ZBError::explicit("api_key is required"));
178 }
179 utility::check_key_text(&self.api_key)
180 }
181
182 fn read_api_response(&self, response: reqwest::blocking::Response) -> ZBResult<String> {
183 self.read_api_response_checked(response, false)
184 }
185
186 fn read_api_response_checked(
187 &self,
188 response: reqwest::blocking::Response,
189 message_only_is_failure: bool,
190 ) -> ZBResult<String> {
191 let status = response.status().as_u16();
192 let content_type = response
193 .headers()
194 .get(reqwest::header::CONTENT_TYPE)
195 .and_then(|value| value.to_str().ok())
196 .unwrap_or("")
197 .to_string();
198 let body = utility::read_limited(
199 response,
200 utility::MAX_JSON_RESPONSE_BYTES,
201 "response body exceeds size limit",
202 )?;
203 let response_content = String::from_utf8_lossy(&body).into_owned();
204 utility::http_error::ensure_json_api_body(status, &content_type, &response_content)?;
205 if message_only_is_failure {
206 utility::http_error::reject_message_only_body(status, &content_type, &response_content)?;
207 }
208 Ok(response_content)
209 }
210
211 fn generic_get_request<'a>(
212 &'a self,
213 url: String,
214 query_args: HashMap<&'a str, &'a str>,
215 ) -> ZBResult<String> {
216 self.get_request_checked(url, query_args, false)
217 }
218
219 fn finder_get_request<'a>(
222 &'a self,
223 url: String,
224 query_args: HashMap<&'a str, &'a str>,
225 ) -> ZBResult<String> {
226 self.get_request_checked(url, query_args, true)
227 }
228
229 fn get_request_checked<'a>(
230 &'a self,
231 url: String,
232 mut query_args: HashMap<&'a str, &'a str>,
233 message_only_is_failure: bool,
234 ) -> ZBResult<String> {
235 self.require_key()?;
236 query_args.insert("api_key", self.api_key.as_str());
237
238 let response = self
239 .client
240 .get(parse_request_url(&url)?)
241 .query(&query_args)
242 .send()?;
243 self.read_api_response_checked(response, message_only_is_failure)
244 }
245
246 fn generic_form_post_request<'a>(
247 &'a self,
248 url: String,
249 mut form_args: HashMap<&'a str, &'a str>,
250 ) -> ZBResult<String> {
251 self.require_key()?;
252 form_args.insert("api_key", self.api_key.as_str());
253
254 let response = self
255 .client
256 .post(parse_request_url(&url)?)
257 .form(&form_args)
258 .send()?;
259 self.read_api_response(response)
260 }
261}
262
263pub(crate) fn parse_request_url(url: &str) -> ZBResult<reqwest::Url> {
269 let parsed = reqwest::Url::parse(url).map_err(|e| ZBError::ExplicitError(e.to_string()))?;
270 if parsed.scheme() == "https" {
271 return Ok(parsed);
272 }
273 if parsed.scheme() == "http" {
274 match parsed.host_str() {
275 Some("127.0.0.1") | Some("localhost") | Some("[::1]") => return Ok(parsed),
276 _ => {}
277 }
278 }
279 Err(ZBError::ExplicitError(
280 "request URL must use https:// (http:// is allowed only for 127.0.0.1, localhost and [::1])"
281 .into(),
282 ))
283}
284
285#[cfg(test)]
286mod security_tests {
287 use super::{parse_request_url, ZeroBounce};
288
289 #[test]
290 fn accepts_https() {
291 let zb = ZeroBounce::with_base_url("key", "https://api.zerobounce.net/v2/").unwrap();
292 assert_eq!(zb.base_url, "https://api.zerobounce.net/v2/");
293 assert_eq!(zb.url_provider.url, "https://api.zerobounce.net/v2/");
294 }
295
296 #[test]
297 fn accepts_loopback_http() {
298 for url in [
299 "http://127.0.0.1:1234/",
300 "http://localhost:1234/",
301 "http://[::1]:1234/",
302 ] {
303 let zb = ZeroBounce::with_base_url("key", url).unwrap();
304 assert_eq!(zb.base_url, url);
305 }
306 }
307
308 fn rejected(url: &str) -> String {
309 match ZeroBounce::with_base_url("key", url) {
310 Ok(_) => panic!("{url} was accepted"),
311 Err(error) => error.to_string(),
312 }
313 }
314
315 #[test]
316 fn rejects_remote_http() {
317 assert!(rejected("http://evil.example/v2/").contains("https://"));
318 }
319
320 #[test]
321 fn rejects_loopback_lookalike_host() {
322 assert!(rejected("http://localhost.evil.example/v2/").contains("https://"));
323 }
324
325 #[test]
326 fn rejects_loopback_userinfo_trick() {
327 assert!(rejected("http://127.0.0.1@evil.example/v2/").contains("https://"));
328 }
329
330 #[test]
331 fn rejects_other_loopback_spellings_and_garbage() {
332 for url in ["http://127.0.0.2/v2/", "http://0.0.0.0/v2/", "ftp://127.0.0.1/", "not a url"] {
333 assert!(rejected(url).contains("https://"), "{url}");
334 }
335 }
336
337 #[test]
338 fn request_urls_follow_the_same_rule() {
339 assert!(parse_request_url("https://bulkapi.zerobounce.net/v2/sendfile").is_ok());
340 assert!(parse_request_url("http://localhost:8080/v2/getfile").is_ok());
341 let error = parse_request_url("http://bulkapi.zerobounce.net/v2/sendfile").unwrap_err();
342 assert!(error.to_string().contains("https://"), "{error}");
343 }
344}