use super::{ZBError, ZBResult};
fn prefix_at_char_boundary(text: &str, max_bytes: usize) -> &str {
if text.len() <= max_bytes {
return text;
}
let mut end = max_bytes;
while !text.is_char_boundary(end) {
end -= 1;
}
&text[..end]
}
pub fn body_looks_like_html(body: &str) -> bool {
let sample = prefix_at_char_boundary(body, 2000);
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(crate) const REDIRECT_REFUSED_MESSAGE: &str =
"ZeroBounce returned a redirect, which this client does not follow.";
pub fn message_from_body(status: u16, content_type: &str, body: &str) -> String {
if (300..400).contains(&status) {
return REDIRECT_REFUSED_MESSAGE.into();
}
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)
{
return Err(ZBError::api(
status,
message_from_body(status, content_type, body),
));
}
let parsed = match serde_json::from_str::<serde_json::Value>(body) {
Ok(parsed) => parsed,
Err(_) if !trimmed.starts_with('{') && !trimmed.starts_with('[') => {
return Err(ZBError::api(
status,
message_from_body(status, content_type, body),
))
}
Err(_) => {
return Err(ZBError::api(
status,
"ZeroBounce returned a response that is not valid JSON.",
))
}
};
if let serde_json::Value::Object(object) = parsed {
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.contains_key("success")
&& object.keys().all(|key| MESSAGE_KEYS.contains(&key.as_str()))
}
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) {
let message = if object.is_empty() {
UNEXPECTED_JSON_SHAPE_MESSAGE.to_string()
} else {
message_from_body(status, content_type, body)
};
return Err(ZBError::api(status, message));
}
}
Ok(())
}
const FILE_STATUS_FIELDS: [&str; 9] = [
"success",
"file_id",
"file_name",
"file_status",
"error_reason",
"file_phase_2_status",
"return_url",
"upload_date",
"complete_percentage",
];
pub(crate) fn object_has_message_key(object: &serde_json::Map<String, serde_json::Value>) -> bool {
object
.keys()
.any(|key| MESSAGE_KEYS.contains(&key.as_str()))
}
pub(crate) fn object_has_non_null_named_field(
object: &serde_json::Map<String, serde_json::Value>,
names: &[&str],
) -> bool {
names
.iter()
.any(|name| matches!(object.get(*name), Some(value) if !value.is_null()))
}
pub(crate) fn parse_unless_message_beside_nulls<T: serde::de::DeserializeOwned>(
status: u16,
body: &str,
names: &[&str],
) -> ZBResult<T> {
if let Ok(serde_json::Value::Object(object)) = serde_json::from_str::<serde_json::Value>(body) {
if object_has_message_key(&object) && !object_has_non_null_named_field(&object, names) {
return Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE));
}
}
parse_json_body_with_status(status, body)
}
pub fn require_status_object_body(status: u16, content_type: &str, body: &str) -> ZBResult<()> {
match serde_json::from_str::<serde_json::Value>(body.trim()) {
Ok(serde_json::Value::Object(object)) => {
reject_message_only_body(status, content_type, body)?;
if object_has_non_null_named_field(&object, &FILE_STATUS_FIELDS) {
Ok(())
} else {
Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE))
}
}
_ => Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE)),
}
}
pub const UNEXPECTED_JSON_SHAPE_MESSAGE: &str =
"ZeroBounce returned JSON that is not the expected response.";
pub fn parse_json_body<T: serde::de::DeserializeOwned>(body: &str) -> ZBResult<T> {
parse_json_body_with_status(200, body)
}
pub fn parse_json_body_with_status<T: serde::de::DeserializeOwned>(
status: u16,
body: &str,
) -> ZBResult<T> {
serde_json::from_str::<serde_json::Value>(body)
.and_then(|value| T::deserialize(ObjectsOnly(value)))
.map_err(|_| ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE))
}
struct ObjectsOnly(serde_json::Value);
impl<'de> serde::Deserializer<'de> for ObjectsOnly {
type Error = serde_json::Error;
fn deserialize_any<V: serde::de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
match self.0 {
serde_json::Value::Array(items) => {
let mut seq = serde::de::value::SeqDeserializer::<_, serde_json::Error>::new(
items.into_iter().map(ObjectsOnly),
);
let value = visitor.visit_seq(&mut seq)?;
seq.end()?;
Ok(value)
}
serde_json::Value::Object(members) => {
let mut map = serde::de::value::MapDeserializer::<_, serde_json::Error>::new(
members.into_iter().map(|(key, value)| (key, ObjectsOnly(value))),
);
let value = visitor.visit_map(&mut map)?;
map.end()?;
Ok(value)
}
other => other.deserialize_any(visitor),
}
}
fn deserialize_struct<V: serde::de::Visitor<'de>>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error> {
match self.0 {
serde_json::Value::Object(_) => self.deserialize_any(visitor),
serde_json::Value::Array(_) => {
Err(serde::de::Error::invalid_type(serde::de::Unexpected::Seq, &visitor))
}
other => other.deserialize_struct(name, fields, visitor),
}
}
fn deserialize_option<V: serde::de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
match self.0 {
serde_json::Value::Null => visitor.visit_none(),
_ => visitor.visit_some(self),
}
}
fn deserialize_newtype_struct<V: serde::de::Visitor<'de>>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error> {
visitor.visit_newtype_struct(self)
}
fn deserialize_enum<V: serde::de::Visitor<'de>>(
self,
name: &'static str,
variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error> {
self.0.deserialize_enum(name, variants, visitor)
}
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf unit unit_struct seq tuple tuple_struct map identifier ignored_any
}
}
impl<'de> serde::de::IntoDeserializer<'de, serde_json::Error> for ObjectsOnly {
type Deserializer = Self;
fn into_deserializer(self) -> Self {
self
}
}
#[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());
}
#[test]
fn test_html_sniff_does_not_split_a_multi_byte_character() {
for wide in ["é", "€", "😀"] {
for start in 2000 - wide.len() + 1..2000 {
let body = format!("{}{wide}{}", "a".repeat(start), "b".repeat(100));
assert!(!body.is_char_boundary(2000), "{wide} at {start}");
assert!(!body_looks_like_html(&body), "{wide} at {start}");
let page = format!("<html>{}{wide}</html>", "a".repeat(start - 6));
assert!(body_looks_like_html(&page), "{wide} at {start}");
assert!(ensure_json_api_body(200, JSON, &format!("{{\"city\":\"{}{wide}\"}}", "a".repeat(start - 9))).is_ok());
}
}
assert_eq!(prefix_at_char_boundary("aé", 2), "a");
assert_eq!(prefix_at_char_boundary("aé", 3), "aé");
assert_eq!(prefix_at_char_boundary("", 0), "");
}
fn reject(status: u16, body: &str) -> ZBResult<()> {
reject_message_only_body(status, JSON, body)
}
#[test]
fn an_empty_object_is_rejected_as_message_only() {
for body in ["{}", "{ }", "{\n}", "{\t}", "{\r\n \t}", " {} "] {
match reject(202, body) {
Err(ZBError::ApiError { status: 202, message }) => {
assert_eq!(message, UNEXPECTED_JSON_SHAPE_MESSAGE, "{body:?}")
}
other => panic!("{body:?}: {other:?}"),
}
}
assert!(reject(200, r#"{"domain":null}"#).is_ok());
assert!(reject(200, r#"{"Message":"m","status":"unknown"}"#).is_ok());
assert!(reject(200, r#"{"success":true,"message":"m"}"#).is_ok());
}
#[test]
fn parse_json_body_with_status_carries_the_status() {
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Row {
id: u32,
}
for status in [200, 201, 299] {
match parse_json_body_with_status::<Row>(status, r#"{"id":"x"}"#) {
Err(ZBError::ApiError { status: got, message }) => {
assert_eq!(got, status);
assert_eq!(message, UNEXPECTED_JSON_SHAPE_MESSAGE);
}
other => panic!("{other:?}"),
}
}
match parse_json_body::<Row>(r#"[1]"#) {
Err(ZBError::ApiError { status: 200, .. }) => {}
other => panic!("{other:?}"),
}
}
#[test]
fn a_status_body_must_be_a_real_status_object() {
for body in ["{}", "{ }", "[]", r#"[{"file_status":"x"}]"#, "0", r#""x""#, "null",
r#"{"message":"m"}"#, r#"{"Message":null}"#, r#"{"error":""}"#] {
match require_status_object_body(203, JSON, body) {
Err(ZBError::ApiError { status: 203, .. }) => {}
other => panic!("{body}: {other:?}"),
}
}
assert!(require_status_object_body(200, JSON, r#"{"success":true,"file_status":"Complete"}"#).is_ok());
assert!(require_status_object_body(200, JSON, r#"{"file_status":"Processing"}"#).is_ok());
}
}