use super::{ZBError, ZBResult};
pub fn body_looks_like_html(body: &str) -> bool {
let sample = if body.len() > 2000 {
&body[..2000]
} else {
body
};
let lower = sample.to_ascii_lowercase();
lower.contains("<!doctype html")
|| lower.contains("<html")
|| lower.contains("<head")
|| lower.contains("<body")
}
pub fn content_type_is_html(content_type: &str) -> bool {
content_type.to_ascii_lowercase().contains("text/html")
}
pub fn strip_error_prefix(message: &str) -> String {
let mut message = message.trim().to_string();
loop {
let trimmed = message.trim();
if let Some(rest) = trimmed.strip_prefix("Error:") {
message = rest.trim().to_string();
continue;
}
if let Some(rest) = trimmed.strip_prefix("[Error]:") {
message = rest.trim().to_string();
continue;
}
return trimmed.to_string();
}
}
fn html_title(body: &str) -> String {
let lower = body.to_ascii_lowercase();
let Some(start) = lower.find("<title") else {
return String::new();
};
let Some(open_end_rel) = lower[start..].find('>') else {
return String::new();
};
let open_end = start + open_end_rel;
let Some(close_rel) = lower[open_end..].find("</title>") else {
return String::new();
};
body[open_end + 1..open_end + close_rel].trim().to_string()
}
const ERROR_ONLY_KEYS: [&str; 3] = ["error", "error_message", "Error"];
const MESSAGE_KEYS: [&str; 6] = ["error", "message", "error_message", "Message", "Error", "detail"];
fn api_error_field(
object: &serde_json::Map<String, serde_json::Value>,
keys: &[&str],
) -> String {
for key in keys {
match object.get(*key) {
Some(serde_json::Value::String(text)) if !text.trim().is_empty() => {
return text.trim().to_string();
}
Some(serde_json::Value::Array(items)) => {
if let Some(serde_json::Value::String(text)) = items.first() {
if !text.trim().is_empty() {
return text.trim().to_string();
}
}
}
_ => {}
}
}
String::new()
}
fn first_api_error_field(object: &serde_json::Map<String, serde_json::Value>) -> String {
api_error_field(object, &MESSAGE_KEYS)
}
fn error_only_body(object: &serde_json::Map<String, serde_json::Value>) -> String {
if object.contains_key("success") {
return String::new();
}
api_error_field(object, &ERROR_ONLY_KEYS)
}
pub fn message_from_body(status: u16, content_type: &str, body: &str) -> String {
if body_looks_like_html(body) || content_type_is_html(content_type) {
let title = html_title(body);
if title.is_empty() {
return "ZeroBounce returned an HTML error page instead of an API response.".into();
}
return format!(
"ZeroBounce returned an HTML error page (\"{title}\") instead of an API response."
);
}
let trimmed = body.trim();
if trimmed.is_empty() {
return format!("Empty response from ZeroBounce (HTTP {status})");
}
if trimmed.starts_with('{') || trimmed.starts_with('[') {
match serde_json::from_str::<serde_json::Value>(trimmed) {
Ok(serde_json::Value::Object(object)) => {
if let Some(serde_json::Value::String(title)) = object.get("title") {
let access = title.contains("Access denied") || title.contains("1020");
let cloudflare =
object.get("cloudflare_error") == Some(&serde_json::Value::Bool(true));
if access && cloudflare {
return title.clone();
}
}
let message = first_api_error_field(&object);
if !message.is_empty() {
return strip_error_prefix(&message);
}
if trimmed.len() > 1000 {
return "ZeroBounce returned a response that is not valid JSON.".into();
}
return strip_error_prefix(trimmed);
}
Ok(_) => {
if trimmed.len() > 1000 {
return "ZeroBounce returned a response that is not valid JSON.".into();
}
return strip_error_prefix(trimmed);
}
Err(_) => return "ZeroBounce returned a response that is not valid JSON.".into(),
}
}
if trimmed.len() > 1000 {
return "ZeroBounce returned a response that is not valid JSON.".into();
}
let message = strip_error_prefix(trimmed);
if message.is_empty() {
return format!("Empty response from ZeroBounce (HTTP {status})");
}
message
}
fn is_falsy_api_success(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::Bool(flag) => !flag,
serde_json::Value::String(text) => text.eq_ignore_ascii_case("false"),
_ => false,
}
}
pub fn ensure_json_api_body(status: u16, content_type: &str, body: &str) -> ZBResult<()> {
let success = (200..300).contains(&status);
let trimmed = body.trim();
if !success
|| trimmed.is_empty()
|| body_looks_like_html(body)
|| content_type_is_html(content_type)
|| (!trimmed.starts_with('{') && !trimmed.starts_with('['))
{
return Err(ZBError::api(
status,
message_from_body(status, content_type, body),
));
}
if trimmed.starts_with('{') {
if let Ok(serde_json::Value::Object(object)) =
serde_json::from_str::<serde_json::Value>(trimmed)
{
if object.get("success").is_some_and(is_falsy_api_success) {
return Err(ZBError::api(
status,
message_from_body(status, content_type, body),
));
}
if !error_only_body(&object).is_empty() {
return Err(ZBError::api(
status,
message_from_body(status, content_type, body),
));
}
}
}
Ok(())
}
fn message_only_body(object: &serde_json::Map<String, serde_json::Value>) -> bool {
!object.is_empty()
&& !object.contains_key("success")
&& object.keys().all(|key| MESSAGE_KEYS.contains(&key.as_str()))
&& !api_error_field(object, &MESSAGE_KEYS).is_empty()
}
pub fn reject_message_only_body(status: u16, content_type: &str, body: &str) -> ZBResult<()> {
if let Ok(serde_json::Value::Object(object)) = serde_json::from_str::<serde_json::Value>(body.trim()) {
if message_only_body(&object) {
return Err(ZBError::api(
status,
message_from_body(status, content_type, body),
));
}
}
Ok(())
}
pub fn parse_json_body<T: serde::de::DeserializeOwned>(body: &str) -> ZBResult<T> {
serde_json::from_str(body)
.map_err(|_| ZBError::explicit("ZeroBounce returned a response that is not valid JSON."))
}
#[cfg(test)]
mod test {
use super::*;
use crate::utility::ZBError;
const JSON: &str = "application/json";
fn error_message(status: u16, body: &str) -> String {
match ensure_json_api_body(status, JSON, body) {
Err(ZBError::ApiError { message, .. }) => message,
other => panic!("expected an ApiError, got {other:#?}"),
}
}
#[test]
fn test_200_with_error_field_is_an_api_error() {
assert_eq!(
error_message(200, r#"{"error":"Invalid API key"}"#),
"Invalid API key"
);
assert_eq!(
error_message(
200,
r#"{"error":"Invalid API key or your account ran out of credits"}"#
),
"Invalid API key or your account ran out of credits"
);
}
#[test]
fn test_200_with_error_message_field_is_an_api_error() {
assert_eq!(
error_message(200, r#"{"error_message":"Missing parameter: api_key."}"#),
"Missing parameter: api_key."
);
}
#[test]
fn test_200_with_empty_error_field_is_not_an_error() {
assert!(ensure_json_api_body(200, JSON, r#"{"error":"","found":true}"#).is_ok());
}
#[test]
fn test_success_field_still_decides() {
assert_eq!(
error_message(200, r#"{"success":false,"message":"File cannot be found."}"#),
"File cannot be found."
);
assert!(ensure_json_api_body(
200,
JSON,
r#"{"success":true,"message":"File Accepted","file_id":"abc"}"#
)
.is_ok());
}
#[test]
fn test_greylisted_validation_is_not_an_error() {
assert!(ensure_json_api_body(
200,
JSON,
r#"{"address":"a@b.com","status":"unknown","sub_status":"greylisted","Message":"Greylisted, try again later"}"#
)
.is_ok());
}
#[test]
fn test_batch_nested_errors_are_not_a_failure() {
assert!(ensure_json_api_body(
200,
JSON,
r#"{"email_batch":[],"errors":[{"error":"Invalid email address","email_address":"bad@"}]}"#
)
.is_ok());
}
}