pub mod api;
pub mod utility;
pub mod warmup;
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};
#[allow(deprecated)]
pub use crate::warmup::{EmailContent, ManagedSending};
pub use crate::warmup::{OnboardingModel, ZbManagedEmailContent, ZbManagedSending, 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,
}
fn join_url(base: &str, endpoint: &str) -> String {
let base = base.trim_end_matches('/');
if endpoint.is_empty() || endpoint.starts_with('/') {
format!("{base}{endpoint}")
} else {
format!("{base}/{endpoint}")
}
}
impl ZBUrlProvider {
pub fn url_of(&self, endpoint: &str) -> String {
join_url(&self.url, endpoint)
}
pub fn bulk_url_of(&self, endpoint: &str) -> String {
join_url(&self.bulk_url, endpoint)
}
pub fn list_evaluator_url_of(&self, endpoint: &str) -> String {
join_url(&self.list_evaluator_url, endpoint)
}
pub fn inbox_placement_url_of(&self, endpoint: &str) -> String {
join_url(&self.inbox_placement_url, 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 std::fmt::Debug for ZeroBounce {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZeroBounce")
.field("api_key", &utility::redacted_key(&self.api_key))
.field("base_url", &self.base_url)
.field("client", &self.client)
.field("url_provider", &self.url_provider)
.finish()
}
}
impl ZeroBounce {
pub fn new(api_key: &str) -> ZeroBounce {
Self::build(api_key, ApiBaseUrl::Default.as_str().to_string())
.unwrap_or_else(|error| panic!("ZeroBounce::new: {error}"))
}
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)?;
Self::build(api_key, base_url_string)
}
fn build(api_key: &str, base_url_string: String) -> ZBResult<ZeroBounce> {
let url_provider = ZBUrlProvider {
url: base_url_string.clone(),
..ZBUrlProvider::default()
};
Ok(ZeroBounce {
api_key: api_key.to_string(),
base_url: base_url_string,
client: utility::http_client()?,
url_provider,
})
}
fn require_key(&self) -> ZBResult<()> {
if self.api_key.trim().is_empty() {
return Err(ZBError::explicit("api_key is required"));
}
utility::check_key_text(&self.api_key)
}
fn redact_error(&self, error: ZBError) -> ZBError {
error.redacted(&[self.api_key.as_str()])
}
fn read_api_body(response: reqwest::blocking::Response) -> ZBResult<(u16, String, 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,
status,
"response body exceeds size limit",
)?;
Ok((status, content_type, String::from_utf8_lossy(&body).into_owned()))
}
}
fn has_userinfo_marker(url: &str) -> bool {
let cleaned: String = url.chars().filter(|c| !matches!(c, '\t' | '\n' | '\r')).collect();
let after_scheme = cleaned
.trim_matches(|c: char| c <= ' ')
.split_once(':')
.map_or("", |(_, rest)| rest);
let authority = after_scheme
.trim_start_matches(['/', '\\'])
.split(['/', '\\', '?', '#'])
.next()
.unwrap_or("");
authority.contains('@')
}
pub(crate) const USERINFO_MESSAGE: &str = "request URL must not contain a username or password";
pub(crate) const URL_TEXT_MESSAGE: &str = "request URL must not contain a query, a fragment, a backslash, whitespace or control characters";
pub(crate) fn parse_request_url(url: &str) -> ZBResult<reqwest::Url> {
let parsed = reqwest::Url::parse(url)
.map_err(|_| ZBError::ExplicitError("request URL is not a valid URL".into()))?;
if !parsed.username().is_empty() || parsed.password().is_some() || has_userinfo_marker(url) {
return Err(ZBError::ExplicitError(
USERINFO_MESSAGE.into(),
));
}
let scheme_ok = parsed.scheme() == "https"
|| (parsed.scheme() == "http"
&& matches!(parsed.host_str(), Some("127.0.0.1") | Some("localhost") | Some("[::1]")));
if scheme_ok {
if url.contains(['?', '#', '\\'])
|| url.chars().any(|c| {
c.is_control() || c.is_whitespace() || utility::is_invisible_char(c)
})
{
return Err(ZBError::ExplicitError(URL_TEXT_MESSAGE.into()));
}
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("username or password"));
}
#[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/"] {
assert!(rejected(url).contains("https://"), "{url}");
}
assert_eq!(rejected("not a url"), "request URL is not a valid URL");
}
#[test]
fn request_urls_with_credentials_are_refused_before_the_scheme_check() {
for url in [
"https://api.zerobounce.net@evil.example/v2",
"http://user:pw@127.0.0.1/v2",
"https://user:pw@api.zerobounce.net/v2",
"http://user@127.0.0.1/v2",
"https://:pw@example.com/",
"https://@example.com/",
"https://:@example.com/",
] {
let error = parse_request_url(url).unwrap_err().to_string();
assert_eq!(error, "request URL must not contain a username or password", "{url}");
assert!(!error.contains("evil") && !error.contains("pw"), "{url}: {error}");
assert!(ZeroBounce::with_base_url("key", url).is_err(), "{url}");
}
assert!(parse_request_url("http://127.0.0.1").is_ok());
assert!(parse_request_url("https://example.com").is_ok());
let error = parse_request_url("http://example.com").unwrap_err().to_string();
assert!(error.contains("https://"), "{error}");
}
#[test]
fn a_url_that_does_not_parse_gets_a_fixed_message_without_the_url() {
let error = parse_request_url("https://secret-host-xyz:notaport/v2").unwrap_err().to_string();
assert_eq!(error, "request URL is not a valid URL");
assert!(!error.contains("secret-host-xyz"), "{error}");
}
#[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}");
}
}