pub mod api;
pub mod utility;
pub mod warmup;
use std::collections::HashMap;
use std::time::Duration;
pub use crate::api::{DomainSearchV2Builder, FindEmailV2Builder};
pub use crate::utility::structures::bulk::{
zb_download_type, ZBBulkResponse, ZBEmailFinderFileOptions, ZBFile, ZBFileFeedback,
ZBFileStatus, ZBGetFileOptions,
};
pub use crate::utility::structures::validate_enums::{ZBValidateStatus, ZBValidateSubStatus};
pub use crate::utility::structures::{ActivityData, ApiUsage};
pub use crate::utility::{format_get_file_error_message, get_file_json_indicates_error};
pub use crate::utility::{ApiBaseUrl, ZBError, ZBResult};
pub use crate::warmup::{EmailContent, ManagedSending, OnboardingModel, ZeroBounceWarmup};
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ZBUrlProvider {
pub url: String,
pub bulk_url: String,
pub list_evaluator_url: String,
pub inbox_placement_url: String,
}
impl ZBUrlProvider {
pub fn url_of(&self, endpoint: &str) -> String {
self.url.to_owned() + endpoint
}
pub fn bulk_url_of(&self, endpoint: &str) -> String {
self.bulk_url.to_owned() + endpoint
}
pub fn list_evaluator_url_of(&self, endpoint: &str) -> String {
self.list_evaluator_url.to_owned() + endpoint
}
pub fn inbox_placement_url_of(&self, endpoint: &str) -> String {
self.inbox_placement_url.to_owned() + endpoint
}
}
impl Default for ZBUrlProvider {
fn default() -> Self {
ZBUrlProvider {
url: ApiBaseUrl::Default.as_str().to_string(),
bulk_url: crate::utility::BULK_URI.to_string(),
list_evaluator_url: crate::utility::LIST_EVALUATOR_URI.to_string(),
inbox_placement_url: crate::utility::INBOX_PLACEMENT_URI.to_string(),
}
}
}
pub struct ZeroBounce {
pub api_key: String,
pub base_url: String,
pub client: reqwest::blocking::Client,
pub url_provider: ZBUrlProvider,
}
impl ZeroBounce {
pub fn new(api_key: &str) -> ZeroBounce {
Self::build(api_key, ApiBaseUrl::Default.as_str().to_string())
}
pub fn with_base_url<T>(api_key: &str, base_url: T) -> ZBResult<ZeroBounce>
where
T: Into<String>,
{
let base_url_string = base_url.into();
parse_request_url(&base_url_string)
.map_err(|_| ZBError::explicit("base_url must be an https:// URL"))?;
Ok(Self::build(api_key, base_url_string))
}
fn build(api_key: &str, base_url_string: String) -> ZeroBounce {
let url_provider = ZBUrlProvider {
url: base_url_string.clone(),
..ZBUrlProvider::default()
};
ZeroBounce {
api_key: api_key.to_string(),
base_url: base_url_string,
client: reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap_or_else(|_| reqwest::blocking::Client::default()),
url_provider,
}
}
fn require_key(&self) -> ZBResult<()> {
if self.api_key.trim().is_empty() {
return Err(ZBError::explicit("api_key is required"));
}
Ok(())
}
fn read_api_response(&self, response: reqwest::blocking::Response) -> ZBResult<String> {
self.read_api_response_checked(response, false)
}
fn read_api_response_checked(
&self,
response: reqwest::blocking::Response,
message_only_is_failure: bool,
) -> ZBResult<String> {
let status = response.status().as_u16();
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("")
.to_string();
let body = utility::read_limited(
response,
utility::MAX_JSON_RESPONSE_BYTES,
"response body exceeds size limit",
)?;
let response_content = String::from_utf8_lossy(&body).into_owned();
utility::http_error::ensure_json_api_body(status, &content_type, &response_content)?;
if message_only_is_failure {
utility::http_error::reject_message_only_body(status, &content_type, &response_content)?;
}
Ok(response_content)
}
fn generic_get_request<'a>(
&'a self,
url: String,
query_args: HashMap<&'a str, &'a str>,
) -> ZBResult<String> {
self.get_request_checked(url, query_args, false)
}
fn finder_get_request<'a>(
&'a self,
url: String,
query_args: HashMap<&'a str, &'a str>,
) -> ZBResult<String> {
self.get_request_checked(url, query_args, true)
}
fn get_request_checked<'a>(
&'a self,
url: String,
mut query_args: HashMap<&'a str, &'a str>,
message_only_is_failure: bool,
) -> ZBResult<String> {
self.require_key()?;
query_args.insert("api_key", self.api_key.as_str());
let response = self
.client
.get(parse_request_url(&url)?)
.query(&query_args)
.send()?;
self.read_api_response_checked(response, message_only_is_failure)
}
fn generic_form_post_request<'a>(
&'a self,
url: String,
mut form_args: HashMap<&'a str, &'a str>,
) -> ZBResult<String> {
self.require_key()?;
form_args.insert("api_key", self.api_key.as_str());
let response = self
.client
.post(parse_request_url(&url)?)
.form(&form_args)
.send()?;
self.read_api_response(response)
}
}
pub(crate) fn parse_request_url(url: &str) -> ZBResult<reqwest::Url> {
let parsed = reqwest::Url::parse(url).map_err(|e| ZBError::ExplicitError(e.to_string()))?;
if parsed.scheme() == "https" {
return Ok(parsed);
}
if parsed.scheme() == "http" {
match parsed.host_str() {
Some("127.0.0.1") | Some("localhost") | Some("[::1]") => return Ok(parsed),
_ => {}
}
}
Err(ZBError::ExplicitError(
"request URL must use https:// (http:// is allowed only for 127.0.0.1, localhost and [::1])"
.into(),
))
}
#[cfg(test)]
mod security_tests {
use super::{parse_request_url, ZeroBounce};
#[test]
fn accepts_https() {
let zb = ZeroBounce::with_base_url("key", "https://api.zerobounce.net/v2/").unwrap();
assert_eq!(zb.base_url, "https://api.zerobounce.net/v2/");
assert_eq!(zb.url_provider.url, "https://api.zerobounce.net/v2/");
}
#[test]
fn accepts_loopback_http() {
for url in [
"http://127.0.0.1:1234/",
"http://localhost:1234/",
"http://[::1]:1234/",
] {
let zb = ZeroBounce::with_base_url("key", url).unwrap();
assert_eq!(zb.base_url, url);
}
}
fn rejected(url: &str) -> String {
match ZeroBounce::with_base_url("key", url) {
Ok(_) => panic!("{url} was accepted"),
Err(error) => error.to_string(),
}
}
#[test]
fn rejects_remote_http() {
assert!(rejected("http://evil.example/v2/").contains("https://"));
}
#[test]
fn rejects_loopback_lookalike_host() {
assert!(rejected("http://localhost.evil.example/v2/").contains("https://"));
}
#[test]
fn rejects_loopback_userinfo_trick() {
assert!(rejected("http://127.0.0.1@evil.example/v2/").contains("https://"));
}
#[test]
fn rejects_other_loopback_spellings_and_garbage() {
for url in ["http://127.0.0.2/v2/", "http://0.0.0.0/v2/", "ftp://127.0.0.1/", "not a url"] {
assert!(rejected(url).contains("https://"), "{url}");
}
}
#[test]
fn request_urls_follow_the_same_rule() {
assert!(parse_request_url("https://bulkapi.zerobounce.net/v2/sendfile").is_ok());
assert!(parse_request_url("http://localhost:8080/v2/getfile").is_ok());
let error = parse_request_url("http://bulkapi.zerobounce.net/v2/sendfile").unwrap_err();
assert!(error.to_string().contains("https://"), "{error}");
}
}