Skip to main content

zero_bounce/utility/
mod.rs

1use std::io::Error as IOError;
2use std::io::Read;
3
4pub mod bulk_get_file;
5pub mod http_error;
6// Test fixtures. Not part of the public API; the integration tests include the
7// same file (tests/mod.rs).
8#[cfg(test)]
9#[allow(dead_code)]
10pub(crate) mod mock_constants;
11pub mod structures;
12
13pub use bulk_get_file::{format_get_file_error_message, get_file_json_indicates_error};
14
15/// Invisible characters that are neither whitespace nor control: the default
16/// ignorables, variation selectors, Hangul, braille and Mongolian blanks, and
17/// the Unicode format (Cf) characters that std cannot classify. A key that
18/// holds one looks like a different key on screen.
19pub(crate) fn is_invisible_char(c: char) -> bool {
20    matches!(
21        c,
22        '\u{00AD}'
23            | '\u{034F}'
24            | '\u{0600}'..='\u{0605}'
25            | '\u{0890}'..='\u{0891}'
26            | '\u{061C}'
27            | '\u{06DD}'
28            | '\u{070F}'
29            | '\u{08E2}'
30            | '\u{115F}'
31            | '\u{1160}'
32            | '\u{17B4}'
33            | '\u{17B5}'
34            | '\u{180B}'..='\u{180F}'
35            | '\u{200B}'..='\u{200F}'
36            | '\u{202A}'..='\u{202E}'
37            | '\u{2060}'..='\u{2064}'
38            | '\u{2065}'
39            | '\u{2066}'..='\u{206F}'
40            | '\u{2800}'
41            | '\u{3164}'
42            | '\u{FE00}'..='\u{FE0F}'
43            | '\u{FEFF}'
44            | '\u{FFA0}'
45            | '\u{FFF0}'..='\u{FFF8}'
46            | '\u{FFF9}'..='\u{FFFB}'
47            | '\u{110BD}'
48            | '\u{110CD}'
49            | '\u{13430}'..='\u{1343F}'
50            | '\u{1BCA0}'..='\u{1BCA3}'
51            | '\u{1D173}'..='\u{1D17A}'
52            | '\u{E0000}'..='\u{E0FFF}'
53    )
54}
55
56/// A key with surrounding whitespace, a control character, a Unicode space
57/// other than the ASCII space, or an invisible character anywhere in it would
58/// be quoted, unredacted, in the HTTP library's own error, or would look like
59/// another key, so it is never sent. An ASCII space in the middle is allowed.
60pub(crate) fn check_key_text(api_key: &str) -> ZBResult<()> {
61    if api_key != api_key.trim()
62        || api_key
63            .chars()
64            .any(|c| c.is_control() || (c != ' ' && c.is_whitespace()) || is_invisible_char(c))
65    {
66        return Err(ZBError::explicit(
67            "api_key has surrounding whitespace or control characters",
68        ));
69    }
70    Ok(())
71}
72
73/// What Debug output shows in place of an API key.
74pub(crate) fn redacted_key(api_key: &str) -> &'static str {
75    if api_key.is_empty() {
76        ""
77    } else {
78        "***"
79    }
80}
81
82/// `text` percent-encoded the way a query or form encodes it (space as `+`)
83/// and strictly (path escaping, space as `%20`).
84fn url_forms(text: &str) -> [String; 2] {
85    let mut query = String::new();
86    let mut strict = String::new();
87    for byte in text.bytes() {
88        match byte {
89            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' => {
90                query.push(byte as char);
91                strict.push(byte as char);
92            }
93            b'*' => {
94                query.push('*');
95                strict.push_str("%2A");
96            }
97            b' ' => {
98                query.push('+');
99                strict.push_str("%20");
100            }
101            _ => {
102                query.push_str(&format!("%{byte:02X}"));
103                strict.push_str(&format!("%{byte:02X}"));
104            }
105        }
106    }
107    [query, strict]
108}
109
110/// `text` as it sits inside a JSON string, with `/` as is or as `\/`.
111fn json_escaped(text: &str, escape_slash: bool) -> String {
112    let quoted = serde_json::to_string(text).unwrap_or_default();
113    let inner = quoted
114        .strip_prefix('"')
115        .and_then(|inner| inner.strip_suffix('"'))
116        .unwrap_or(text);
117    if escape_slash {
118        inner.replace('/', "\\/")
119    } else {
120        inner.to_string()
121    }
122}
123
124/// Every form a message can carry `secret` in, composed from the encoders up
125/// to depth 2: {as sent, JSON-escaped, JSON-escaped with `\/` for `/`} x {as
126/// is, percent-encoded the way a query or form encodes it, strictly (path
127/// escaping)}, and each JSON form escaped twice (a JSON error body quoting
128/// the JSON request body). Longest first, so a shorter form is never masked
129/// inside a longer one and part of the longer one left behind.
130fn secret_forms(secret: &str) -> Vec<String> {
131    let mut forms = vec![secret.to_string()];
132    forms.extend(url_forms(secret));
133    for escape_slash in [false, true] {
134        let escaped = json_escaped(secret, escape_slash);
135        forms.extend(url_forms(&escaped));
136        forms.push(json_escaped(&escaped, escape_slash));
137        forms.push(escaped);
138    }
139    forms.sort_by_key(|form| std::cmp::Reverse(form.len()));
140    forms
141}
142
143/// The case folding of one character: its upper case, lower-cased (so `ß`
144/// is found as `SS` and `ss`, and `fi` as `FI`).
145fn fold_char(c: char, out: &mut String) {
146    for upper in c.to_uppercase() {
147        out.extend(upper.to_lowercase());
148    }
149}
150
151/// `text` under [`fold_char`].
152fn fold(text: &str) -> String {
153    let mut out = String::with_capacity(text.len());
154    for c in text.chars() {
155        fold_char(c, &mut out);
156    }
157    out
158}
159
160/// Replace every occurrence of each form in `text` with `***`, ignoring case.
161/// Text and forms are folded and each match is mapped back to the original
162/// text, which is masked whole: a match that covers part of one original
163/// character masks that character. Overlapping matches become one `***`.
164fn mask_forms(text: &str, forms: &[String]) -> String {
165    let mut text = text.to_string();
166    for form in forms.iter().filter(|form| !form.is_empty()) {
167        text = text.replace(form.as_str(), "***");
168    }
169    // For every original char: where it starts and ends in `text`, and where
170    // its folding starts in `folded`.
171    let mut folded = String::with_capacity(text.len());
172    let mut bounds = Vec::new();
173    for (start, c) in text.char_indices() {
174        bounds.push((start, start + c.len_utf8(), folded.len()));
175        fold_char(c, &mut folded);
176    }
177    let char_at = |offset: usize| bounds.partition_point(|bound| bound.2 <= offset) - 1;
178    let mut spans: Vec<(usize, usize)> = Vec::new();
179    let mut seen = std::collections::HashSet::new();
180    for form in forms {
181        let needle = fold(form);
182        if needle.is_empty() || !seen.insert(needle.clone()) {
183            continue;
184        }
185        let mut from = 0;
186        while let Some(at) = folded[from..].find(&needle) {
187            let first = from + at;
188            let last = first + needle.len() - 1;
189            spans.push((bounds[char_at(first)].0, bounds[char_at(last)].1));
190            from = first + folded[first..].chars().next().map_or(1, char::len_utf8);
191        }
192    }
193    if spans.is_empty() {
194        return text;
195    }
196    spans.sort_unstable();
197    let mut out = String::with_capacity(text.len());
198    let mut pos = 0;
199    let mut i = 0;
200    while i < spans.len() {
201        let (start, mut end) = spans[i];
202        i += 1;
203        while i < spans.len() && spans[i].0 <= end {
204            end = end.max(spans[i].1);
205            i += 1;
206        }
207        out.push_str(&text[pos..start]);
208        out.push_str("***");
209        pos = end;
210    }
211    out.push_str(&text[pos..]);
212    out
213}
214
215/// Mask every `api_key=` value in a message, whichever key it holds.
216fn scrub_query_string_values(text: &str) -> String {
217    // ASCII lowercasing keeps every byte offset, so indexes found in `lower`
218    // are char boundaries in `text` too.
219    let lower = text.to_ascii_lowercase();
220    let mut out = String::with_capacity(text.len());
221    let mut from = 0;
222    while let Some(found) = lower[from..].find("api_key=") {
223        let value_start = from + found + "api_key=".len();
224        out.push_str(&text[from..value_start]);
225        let value_end = text[value_start..]
226            .find(|c: char| c == '&' || c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>'))
227            .map_or(text.len(), |offset| value_start + offset);
228        if value_end > value_start {
229            out.push_str("***");
230        }
231        from = value_end;
232    }
233    out.push_str(&text[from..]);
234    out
235}
236
237/// Replace every form of each secret in `text` with `***`, and every
238/// `api_key=` value. Both API clients pass each message built from a
239/// response body through it, so a body that echoes the key (an error quoting
240/// the request URL, `{"error": "Invalid API key <key>"}`) does not hand the
241/// key to the caller.
242///
243/// Redaction is closed under encoding: a message that still holds a secret in
244/// any decoded view ([`secret_survives_decoding`]) is replaced whole by
245/// [`CREDENTIAL_OMITTED_MESSAGE`].
246pub(crate) fn redact_secrets(text: &str, secrets: &[&str]) -> String {
247    let mut value = text.to_string();
248    for secret in secrets.iter().filter(|secret| !secret.is_empty()) {
249        value = mask_forms(&value, &secret_forms(secret));
250    }
251    let value = scrub_query_string_values(&value);
252    if secret_survives_decoding(&value, secrets) {
253        return CREDENTIAL_OMITTED_MESSAGE.to_string();
254    }
255    value
256}
257
258/// What replaces a message that still held a secret after masking.
259pub(crate) const CREDENTIAL_OMITTED_MESSAGE: &str =
260    "ZeroBounce's response was omitted from this error because it contained a credential.";
261
262/// How deep [`secret_survives_decoding`] decodes: the SDK's own request
263/// encoding plus three layers a server or proxy may echo it in.
264const MAX_SECRET_DECODE_LAYERS: usize = 4;
265
266/// Whether any view of `text`, decoded up to [`MAX_SECRET_DECODE_LAYERS`] layers deep in any order
267/// (percent-decoding, percent-decoding with `+` as a space, JSON-unescaping
268/// with `\/` and `\uXXXX`, [`quote_decoded`]), contains a secret, ignoring
269/// case. `secret_forms` masks the spellings this crate can generate; this
270/// catches every other one (lowercase percent escapes, another JSON escaper,
271/// an upper-cased echo).
272fn secret_survives_decoding(text: &str, secrets: &[&str]) -> bool {
273    let secrets: Vec<&str> = secrets.iter().copied().filter(|secret| !secret.is_empty()).collect();
274    if secrets.is_empty() {
275        return false;
276    }
277    let folded_secrets: Vec<String> = secrets.iter().map(|secret| fold(secret)).collect();
278    let decoders: [fn(&str) -> String; 4] = [
279        |text| percent_decoded(text, false),
280        |text| percent_decoded(text, true),
281        json_unescaped,
282        quote_decoded,
283    ];
284    let mut seen = std::collections::HashSet::new();
285    seen.insert(text.to_string());
286    let mut views = vec![text.to_string()];
287    for layer in 0..=MAX_SECRET_DECODE_LAYERS {
288        let mut next = Vec::new();
289        for view in &views {
290            let folded_view = fold(view);
291            if secrets.iter().any(|secret| view.contains(secret))
292                || folded_secrets.iter().any(|secret| folded_view.contains(secret.as_str()))
293            {
294                return true;
295            }
296            if layer == MAX_SECRET_DECODE_LAYERS {
297                continue;
298            }
299            for decode in decoders {
300                let decoded = decode(view);
301                if seen.insert(decoded.clone()) {
302                    next.push(decoded);
303                }
304            }
305        }
306        views = next;
307    }
308    false
309}
310
311/// `text` with each valid `%XX` escape decoded (and `+` as a space when
312/// asked); anything else is kept as it is. Bytes that do not form UTF-8 are
313/// replaced, as they cannot be part of a secret.
314fn percent_decoded(text: &str, plus_is_space: bool) -> String {
315    let bytes = text.as_bytes();
316    let mut out = Vec::with_capacity(bytes.len());
317    let mut i = 0;
318    while i < bytes.len() {
319        let byte = bytes[i];
320        if byte == b'%' && i + 2 < bytes.len() {
321            if let (Some(high), Some(low)) = (
322                (bytes[i + 1] as char).to_digit(16),
323                (bytes[i + 2] as char).to_digit(16),
324            ) {
325                out.push((high * 16 + low) as u8);
326                i += 3;
327                continue;
328            }
329        }
330        out.push(if byte == b'+' && plus_is_space { b' ' } else { byte });
331        i += 1;
332    }
333    String::from_utf8_lossy(&out).into_owned()
334}
335
336/// `text` with each valid JSON string escape decoded (`\"`, `\\`, `\/`,
337/// `\b`, `\f`, `\n`, `\r`, `\t`, `\uXXXX` and surrogate pairs); anything
338/// else is kept as it is.
339fn json_unescaped(text: &str) -> String {
340    fn hex4(chars: &[char], at: usize) -> Option<u32> {
341        let digits: String = chars.get(at..at + 4)?.iter().collect();
342        if digits.len() != 4 || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
343            return None;
344        }
345        u32::from_str_radix(&digits, 16).ok()
346    }
347    let chars: Vec<char> = text.chars().collect();
348    let mut out = String::with_capacity(text.len());
349    let mut i = 0;
350    while i < chars.len() {
351        if chars[i] != '\\' || i + 1 >= chars.len() {
352            out.push(chars[i]);
353            i += 1;
354            continue;
355        }
356        let simple = match chars[i + 1] {
357            '"' => Some('"'),
358            '\\' => Some('\\'),
359            '/' => Some('/'),
360            'b' => Some('\u{8}'),
361            'f' => Some('\u{c}'),
362            'n' => Some('\n'),
363            'r' => Some('\r'),
364            't' => Some('\t'),
365            _ => None,
366        };
367        if let Some(decoded) = simple {
368            out.push(decoded);
369            i += 2;
370            continue;
371        }
372        if chars[i + 1] == 'u' || chars[i + 1] == 'U' {
373            // Rust, JavaScript, Swift and Ruby write a short escape as `\u{27}`.
374            if chars.get(i + 2) == Some(&'{') {
375                if let Some(end) = chars[i + 3..].iter().position(|c| *c == '}') {
376                    let digits: String = chars[i + 3..i + 3 + end].iter().collect();
377                    if !digits.is_empty()
378                        && digits.chars().all(|c| c.is_ascii_hexdigit())
379                        && digits.len() <= 6
380                    {
381                        if let Ok(code) = u32::from_str_radix(&digits, 16) {
382                            out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
383                            i += 4 + end;
384                            continue;
385                        }
386                    }
387                }
388            }
389            if let Some(code) = hex4(&chars, i + 2) {
390                // A surrogate pair (\ud83d\ude00) is one character.
391                if (0xD800..0xDC00).contains(&code)
392                    && chars.get(i + 6) == Some(&'\\')
393                    && chars.get(i + 7) == Some(&'u')
394                {
395                    if let Some(low) = hex4(&chars, i + 8).filter(|low| (0xDC00..0xE000).contains(low)) {
396                        let combined = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);
397                        out.push(char::from_u32(combined).unwrap_or('\u{FFFD}'));
398                        i += 12;
399                        continue;
400                    }
401                }
402                out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
403                i += 6;
404                continue;
405            }
406        }
407        out.push(chars[i]);
408        i += 1;
409    }
410    out
411}
412
413/// One layer of the quote spellings JSON does not cover: a backslash before
414/// a single quote, a `\xHH` or `\XHH` byte, an HTML character reference
415/// (`&#39;`, `&quot;`, `&APOS;`) and a quote doubled the way SQL writes it.
416/// A secret that holds a quote comes back in these forms, and none of them is
417/// a spelling [`secret_forms`] generates.
418/// `\047` (C, Perl, PostgreSQL). Exactly three octal digits, so a lone `\0` is left alone.
419fn octal_escapes_decoded(text: &str) -> String {
420    let chars: Vec<char> = text.chars().collect();
421    let mut out = String::with_capacity(text.len());
422    let mut i = 0;
423    while i < chars.len() {
424        if chars[i] == '\\' {
425            let mut value = 0u32;
426            let mut n = 0;
427            while n < 3 && i + 1 + n < chars.len() && chars[i + 1 + n].is_digit(8) {
428                value = value * 8 + chars[i + 1 + n].to_digit(8).unwrap_or(0);
429                n += 1;
430            }
431            if n == 3 && value <= 0xFF {
432                out.push(char::from_u32(value).unwrap_or('\u{FFFD}'));
433                i += 1 + n;
434                continue;
435            }
436        }
437        out.push(chars[i]);
438        i += 1;
439    }
440    out
441}
442
443fn quote_decoded(text: &str) -> String {
444    let text = text.replace("\\'", "'");
445    let text = octal_escapes_decoded(&text);
446    let text = hex_byte_escapes_decoded(&text);
447    let text = html_unescaped(&text);
448    text.replace("''", "'").replace("\"\"", "\"")
449}
450
451/// `text` with each `\xHH` and `\XHH` turned into that byte. A sequence that
452/// is not two hex digits is kept as it is; bytes that do not form UTF-8 are
453/// replaced, as they cannot be part of a secret.
454fn hex_byte_escapes_decoded(text: &str) -> String {
455    if !text.contains("\\x") && !text.contains("\\X") {
456        return text.to_string();
457    }
458    let bytes = text.as_bytes();
459    let mut out = Vec::with_capacity(bytes.len());
460    let mut i = 0;
461    while i < bytes.len() {
462        if bytes[i] == b'\\' && i + 3 < bytes.len() && matches!(bytes[i + 1], b'x' | b'X') {
463            if let (Some(high), Some(low)) = (
464                (bytes[i + 2] as char).to_digit(16),
465                (bytes[i + 3] as char).to_digit(16),
466            ) {
467                out.push((high * 16 + low) as u8);
468                i += 4;
469                continue;
470            }
471        }
472        out.push(bytes[i]);
473        i += 1;
474    }
475    String::from_utf8_lossy(&out).into_owned()
476}
477
478/// The character a named HTML reference stands for, the name matched in lower
479/// case so `&APOS;` and `&Quot;` are quotes too. Every ASCII punctuation name
480/// of HTML5 is here, plus `nbsp`.
481fn html_entity(name: &str) -> Option<char> {
482    Some(match name.to_ascii_lowercase().as_str() {
483        "amp" => '&',
484        "lt" => '<',
485        "gt" => '>',
486        "quot" => '"',
487        "apos" => '\'',
488        "nbsp" => '\u{a0}',
489        "tab" => '\t',
490        "newline" => '\n',
491        "excl" => '!',
492        "num" => '#',
493        "dollar" => '$',
494        "percnt" => '%',
495        "lpar" => '(',
496        "rpar" => ')',
497        "ast" | "midast" => '*',
498        "plus" => '+',
499        "comma" => ',',
500        "period" => '.',
501        "sol" => '/',
502        "colon" => ':',
503        "semi" => ';',
504        "equals" => '=',
505        "quest" => '?',
506        "commat" => '@',
507        "lsqb" | "lbrack" => '[',
508        "bsol" => '\\',
509        "rsqb" | "rbrack" => ']',
510        "hat" => '^',
511        "lowbar" | "underbar" => '_',
512        "grave" | "diacriticalgrave" => '`',
513        "lcub" | "lbrace" => '{',
514        "verbar" | "vert" | "verticalline" => '|',
515        "rcub" | "rbrace" => '}',
516        _ => return None,
517    })
518}
519
520/// `text` with each HTML character reference decoded: numeric (`&#39;`,
521/// `&#x27;`, with or without the `;`) and named (see [`html_entity`]; `amp`,
522/// `lt`, `gt` and `quot` also without the `;`, as browsers read them).
523/// Anything else is kept as it is.
524fn html_unescaped(text: &str) -> String {
525    if !text.contains('&') {
526        return text.to_string();
527    }
528    let chars: Vec<char> = text.chars().collect();
529    let mut out = String::with_capacity(text.len());
530    let mut i = 0;
531    while i < chars.len() {
532        if chars[i] != '&' {
533            out.push(chars[i]);
534            i += 1;
535            continue;
536        }
537        let rest = &chars[i + 1..];
538        if rest.first() == Some(&'#') {
539            let (radix, digits_from) = match rest.get(1) {
540                Some('x') | Some('X') => (16, 2),
541                _ => (10, 1),
542            };
543            let digits: Vec<u32> = rest[digits_from.min(rest.len())..]
544                .iter()
545                .map_while(|c| c.to_digit(radix))
546                .collect();
547            if !digits.is_empty() {
548                let code = digits
549                    .iter()
550                    .fold(0u32, |code, digit| code.saturating_mul(radix).saturating_add(*digit));
551                let mut used = digits_from + digits.len();
552                if rest.get(used) == Some(&';') {
553                    used += 1;
554                }
555                out.push(char::from_u32(code).filter(|c| *c != '\0').unwrap_or('\u{FFFD}'));
556                i += 1 + used;
557                continue;
558            }
559        } else {
560            let name: String = rest.iter().take_while(|c| c.is_ascii_alphanumeric()).collect();
561            if !name.is_empty() {
562                if rest.get(name.len()) == Some(&';') {
563                    if let Some(decoded) = html_entity(&name) {
564                        out.push(decoded);
565                        i += name.len() + 2;
566                        continue;
567                    }
568                } else {
569                    let lower = name.to_ascii_lowercase();
570                    let legacy = ["amp", "quot", "lt", "gt"].into_iter().find(|legacy| lower.starts_with(legacy));
571                    if let Some(legacy) = legacy {
572                        out.push(html_entity(legacy).unwrap_or('&'));
573                        i += 1 + legacy.len();
574                        continue;
575                    }
576                }
577            }
578        }
579        out.push('&');
580        i += 1;
581    }
582    out
583}
584
585/// The HTTP client both API clients use: explicit timeout, redirects never
586/// followed (the API key travels with every request, and a redirect could
587/// send it to another host). If it cannot be built there is no fallback: a
588/// default client would follow redirects.
589pub(crate) fn http_client() -> ZBResult<reqwest::blocking::Client> {
590    http_client_with_timeout(scaled_for_tests(REQUEST_TIMEOUT))
591}
592
593#[cfg(test)]
594thread_local! {
595    /// This crate's unit tests divide the timeout [`http_client`] builds in
596    /// by this, so a test can prove that the clients the public constructors
597    /// build carry [`REQUEST_TIMEOUT`] without waiting two minutes.
598    static TIMEOUT_DIVISOR: std::cell::Cell<u32> = const { std::cell::Cell::new(1) };
599}
600
601#[cfg(test)]
602thread_local! {
603    /// The timeout of the last client [`http_client_with_timeout`] built on
604    /// this thread, so a unit test can pin the exact value a constructor uses.
605    static LAST_TIMEOUT: std::cell::Cell<Option<std::time::Duration>> = const { std::cell::Cell::new(None) };
606}
607
608/// `timeout` unchanged, except in this crate's unit tests, which may shrink
609/// it ([`TIMEOUT_DIVISOR`]).
610fn scaled_for_tests(timeout: std::time::Duration) -> std::time::Duration {
611    #[cfg(test)]
612    let timeout = timeout / TIMEOUT_DIVISOR.with(|divisor| divisor.get());
613    timeout
614}
615
616/// How long one request may take, from connecting to the last byte of the
617/// body.
618pub(crate) const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
619
620/// [`http_client`] with another timeout, so a test can prove the timeout holds
621/// without waiting two minutes.
622fn http_client_with_timeout(
623    timeout: std::time::Duration,
624) -> ZBResult<reqwest::blocking::Client> {
625    #[cfg(test)]
626    LAST_TIMEOUT.with(|last| last.set(Some(timeout)));
627    client_or_error(
628        reqwest::blocking::Client::builder()
629            .timeout(timeout)
630            .redirect(reqwest::redirect::Policy::none())
631            .build(),
632    )
633}
634
635fn client_or_error(
636    built: reqwest::Result<reqwest::blocking::Client>,
637) -> ZBResult<reqwest::blocking::Client> {
638    built.map_err(|error| ZBError::ExplicitError(format!("could not build the HTTP client: {error}")))
639}
640
641#[cfg(test)]
642mod redaction_tests {
643    use super::redact_secrets;
644
645    /// Redaction is closed under encoding: every sequence of up to four
646    /// encodings of a secret (the SDK's own plus three echoes) (URL with %20 or +, JSON with or without \/),
647    /// then a seeded random sample of them with lowercase percent escapes and
648    /// random surrounding text, leaves no decoded view holding the secret. A
649    /// spelling `secret_forms` does not generate drops the whole message.
650    #[test]
651    fn redaction_is_closed_under_encoding() {
652        let secret = r#"a b"c/d+e%f&g=h<i>j'k\l"#;
653        // URL with %20, URL with +, JSON, JSON with \/.
654        let encoders: [fn(&str) -> String; 4] = [
655            |text| super::url_forms(text)[1].clone(),
656            |text| super::url_forms(text)[0].clone(),
657            |text| super::json_escaped(text, false),
658            |text| super::json_escaped(text, true),
659        ];
660        let mut sequences: Vec<Vec<usize>> = vec![vec![]];
661        for depth in 1..=4 {
662            let mut next = Vec::new();
663            for prefix in sequences.iter().filter(|s| s.len() == depth - 1) {
664                for encoder in 0..encoders.len() {
665                    let mut sequence = prefix.clone();
666                    sequence.push(encoder);
667                    next.push(sequence);
668                }
669            }
670            sequences.extend(next);
671        }
672        assert_eq!(sequences.len(), 341);
673        // A small LCG, seeded, for the random sample.
674        let mut state: u64 = 20261112;
675        let mut random = |below: usize| {
676            state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
677            ((state >> 33) as usize) % below
678        };
679        // (encoder sequence, lowercase it, text around it)
680        type Case = (Vec<usize>, bool, String);
681        let mut cases: Vec<Case> =
682            sequences.iter().map(|sequence| (sequence.clone(), false, String::new())).collect();
683        for _ in 0..500 {
684            let sequence = (0..random(5)).map(|_| random(encoders.len())).collect();
685            cases.push((sequence, random(2) == 0, format!("{{\"x\":{}}} \"q\"", random(1000))));
686        }
687        let mut omitted = 0;
688        for (sequence, lowercase, around) in cases {
689            let mut encoded = secret.to_string();
690            for &encoder in &sequence {
691                encoded = encoders[encoder](&encoded);
692            }
693            if lowercase {
694                encoded = encoded.to_lowercase();
695            }
696            let message = format!("echo {around}[{encoded}] end");
697            for secrets in [vec![secret], vec!["other-key", secret], vec![secret, "smtp-user"]] {
698                let got = redact_secrets(&message, &secrets);
699                if got == super::CREDENTIAL_OMITTED_MESSAGE {
700                    omitted += 1;
701                }
702                let mut views = vec![got.clone()];
703                for _ in 0..4 {
704                    let mut next = Vec::new();
705                    for view in &views {
706                        next.push(super::percent_decoded(view, false));
707                        next.push(super::percent_decoded(view, true));
708                        next.push(super::json_unescaped(view));
709                    }
710                    views.extend(next);
711                }
712                assert!(
713                    views.iter().all(|view| !view.contains(secret)),
714                    "{sequence:?} lowercase={lowercase}: {got:?}"
715                );
716            }
717        }
718        assert!(omitted > 0, "no message needed the decode check");
719        // A message with no secret in it is kept as it is.
720        assert_eq!(
721            redact_secrets(r"Invalid email %2F \u0041", &[secret]),
722            r"Invalid email %2F \u0041"
723        );
724    }
725
726    /// Each decode step of the secret check is needed: every text below holds
727    /// the secret behind exactly one kind of escape that only that step
728    /// undoes, and none of them is a spelling `secret_forms` generates, so
729    /// only the decode check can drop it. Removing a step, its lowercase hex,
730    /// `\uXXXX` or surrogate pairs, or a layer of depth leaks the secret. Each
731    /// UTF-8 sequence length (2, 3 and 4 bytes) is covered behind both the
732    /// percent and the JSON step.
733    #[test]
734    fn each_decode_step_of_the_secret_check_is_needed() {
735        let cases = [
736            // '+' stays a plus: only percent-decoding without + as space works.
737            ("percent, + kept", "k+y/z", "echo k+y%2fz end"),
738            ("percent, upper-case hex", "k+y/z", "echo k+y%2Fz end"),
739            // A space sent as +: only percent-decoding with + as space works.
740            ("percent, + as space", "k y/z", "echo k+y%2fz end"),
741            ("percent, 2-byte UTF-8", "k+y\u{e9}z", "echo k+y%c3%a9z end"),
742            ("percent, 3-byte UTF-8", "k+y\u{20ac}z", "echo k+y%e2%82%acz end"),
743            ("percent, 4-byte UTF-8", "k+y\u{1F600}z", "echo k+y%f0%9f%98%80z end"),
744            ("JSON escape", "k\"y", r#"echo k\"y end"#),
745            (r"JSON \/", "k/y", r"echo k\/y end"),
746            (r"JSON \uXXXX", "k/y", r"echo k\u002fy end"),
747            (r"JSON \uXXXX, 2-byte UTF-8", "k\u{e9}y", r"echo k\u00e9y end"),
748            (r"JSON \uXXXX, 3-byte UTF-8", "k\u{20ac}y", r"echo k\u20acy end"),
749            ("JSON surrogate pair, 4-byte UTF-8", "k\u{1F600}y", r"echo k\ud83d\ude00y end"),
750            ("NUL before", "k+y/z", "a\0b echo k+y%2fz end"),
751            ("%00 before", "k+y/z", "a%00b echo k+y%2fz end"),
752            ("invalid UTF-8 run before", "k+y/z", "%ff%fe echo k+y%2fz end"),
753            // Four layers: four percent-encodings of '/', the last one with %25.
754            ("four layers", "k/y", "echo k%2525252fy end"),
755        ];
756        for (name, needle, text) in cases {
757            let caught = super::secret_survives_decoding(text, &[needle]);
758            assert!(caught, "decode step not covered: {name}");
759        }
760        // Five layers is past the promise: the text is kept, so the depth is
761        // exactly four and the check is not dropping every escaped text.
762        assert!(!super::secret_survives_decoding("echo k%252525252fy end", &["k/y"]));
763    }
764
765    /// Every form of a key, and any api_key value, whichever key it holds.
766    #[test]
767    fn every_form_of_a_secret_is_masked() {
768        let text = r"raw a/b+c d*e, query a%2Fb%2Bc+d*e, path a%2Fb%2Bc%20d%2Ae, json a\/b+c d*e, url https://x.test/v2?api_key=other-key&email=a";
769        assert_eq!(
770            redact_secrets(text, &["a/b+c d*e"]),
771            "raw ***, query ***, path ***, json ***, url https://x.test/v2?api_key=***&email=a"
772        );
773        assert_eq!(redact_secrets("API_KEY=x", &[]), "API_KEY=***");
774        assert_eq!(redact_secrets("no secret here", &["", "absent"]), "no secret here");
775    }
776
777    /// Each form on its own, spelled out, for a secret holding every
778    /// character the encodings treat differently, so dropping any one form
779    /// fails: as sent, query and strict percent-encoding, JSON-escaped with
780    /// and without `\/`, and the query and strict encoding of each JSON form
781    /// (a server echoing a URL-encoded JSON request body). serde_json leaves
782    /// `<`, `>`, `&` and `'` as they are, so there is no HTML-escaped form.
783    #[test]
784    fn every_encoding_of_a_secret_is_masked_on_its_own() {
785        let secret = r#"a b"c/d+e%f&g=h<i>j'k\l"#;
786        let forms = [
787            ("raw", r#"a b"c/d+e%f&g=h<i>j'k\l"#),
788            ("query", "a+b%22c%2Fd%2Be%25f%26g%3Dh%3Ci%3Ej%27k%5Cl"),
789            ("strict", "a%20b%22c%2Fd%2Be%25f%26g%3Dh%3Ci%3Ej%27k%5Cl"),
790            ("json", r#"a b\"c/d+e%f&g=h<i>j'k\\l"#),
791            ("json \\/", r#"a b\"c\/d+e%f&g=h<i>j'k\\l"#),
792            ("query json", "a+b%5C%22c%2Fd%2Be%25f%26g%3Dh%3Ci%3Ej%27k%5C%5Cl"),
793            ("strict json", "a%20b%5C%22c%2Fd%2Be%25f%26g%3Dh%3Ci%3Ej%27k%5C%5Cl"),
794            ("query json \\/", "a+b%5C%22c%5C%2Fd%2Be%25f%26g%3Dh%3Ci%3Ej%27k%5C%5Cl"),
795            ("strict json \\/", "a%20b%5C%22c%5C%2Fd%2Be%25f%26g%3Dh%3Ci%3Ej%27k%5C%5Cl"),
796        ];
797        for (name, text) in forms {
798            assert_eq!(
799                redact_secrets(&format!("echo [{text}] end"), &[secret]),
800                "echo [***] end",
801                "the {name} form was left"
802            );
803        }
804        // The raw form of `"k` sits inside its JSON form `\"k`: masking the
805        // shorter form first would leave a stray backslash behind.
806        assert_eq!(
807            redact_secrets(r#"{"error":"bad key \"k"}"#, &[r#""k"#]),
808            r#"{"error":"bad key ***"}"#
809        );
810    }
811
812    /// Every spelling of a secret, composed here from the encoders
813    /// themselves, is masked whole: {raw, JSON, JSON with `\/`} x {as is,
814    /// query-encoded with `+`, with `%20`}, and each JSON form escaped twice.
815    /// The secret holds every character an encoding changes, so the spellings
816    /// all differ and dropping any one generator from `secret_forms` fails.
817    #[test]
818    fn every_composed_spelling_of_a_secret_is_masked_whole() {
819        type Encoder = Box<dyn Fn(&str) -> String>;
820        let secret = r#"a b"c/d+e%f&g=h<i>j'k\l"#;
821        let json = |text: &str, slash: bool| {
822            let quoted = serde_json::to_string(text).unwrap();
823            let inner = &quoted[1..quoted.len() - 1];
824            if slash {
825                inner.replace('/', "\\/")
826            } else {
827                inner.to_string()
828            }
829        };
830        let query = |text: &str| {
831            let mut url = reqwest::Url::parse("https://x.test/").unwrap();
832            url.query_pairs_mut().append_pair("k", text);
833            url.query().unwrap()["k=".len()..].to_string()
834        };
835        let escapers: Vec<(&str, Encoder)> = vec![
836            ("raw", Box::new(|text| text.to_string())),
837            ("json", Box::new(move |text| json(text, false))),
838            ("json \\/", Box::new(move |text| json(text, true))),
839        ];
840        let url_encoders: Vec<(&str, Encoder)> = vec![
841            ("", Box::new(|text| text.to_string())),
842            (", query +", Box::new(move |text| query(text))),
843            (", query %20", Box::new(move |text| query(text).replace('+', "%20"))),
844        ];
845        let mut spellings = std::collections::BTreeMap::new();
846        for (escape_name, escape) in &escapers {
847            for (url_name, encode) in &url_encoders {
848                spellings.insert(format!("{escape_name}{url_name}"), encode(&escape(secret)));
849            }
850            if *escape_name != "raw" {
851                spellings.insert(format!("{escape_name}, twice"), escape(&escape(secret)));
852            }
853        }
854        assert_eq!(spellings.len(), 3 * 3 + 2);
855        let distinct: std::collections::HashSet<&String> = spellings.values().collect();
856        assert_eq!(distinct.len(), spellings.len(), "{spellings:?}");
857        for (name, text) in &spellings {
858            assert_eq!(redact_secrets(&format!("<{text}>"), &[secret]), "<***>", "the {name} spelling was left");
859        }
860    }
861}
862
863#[cfg(test)]
864mod case_and_quote_tests {
865    use super::{check_key_text, redact_secrets, CREDENTIAL_OMITTED_MESSAGE};
866
867    #[test]
868    fn a_key_with_a_unicode_space_a_control_or_an_invisible_character_is_refused() {
869        let mut refused: Vec<char> = vec!['\u{a0}', '\u{2028}', '\u{3000}', '\u{85}', '\t', '\n', '\0', '\u{7f}'];
870        refused.extend([
871            '\u{200B}', '\u{FEFF}', '\u{180E}', '\u{034F}', '\u{3164}', '\u{2800}', '\u{2065}', '\u{FFF0}',
872            '\u{FFF8}', '\u{E0000}', '\u{E0001}', '\u{E0FFF}', '\u{115F}', '\u{FFA0}', '\u{2060}',
873            '\u{202E}', '\u{2066}', '\u{0600}', '\u{00AD}', '\u{FFF9}', '\u{1D173}', '\u{0890}', '\u{0891}',
874        ]);
875        // One from each remaining range of the match, so deleting any range fails.
876        refused.extend([
877            '\u{061C}', '\u{06DD}', '\u{070F}', '\u{08E2}', '\u{1160}', '\u{17B4}', '\u{17B5}', '\u{110BD}',
878            '\u{110CD}',
879        ]);
880        refused.extend('\u{13430}'..='\u{1343F}');
881        refused.extend('\u{1BCA0}'..='\u{1BCA3}');
882        refused.extend('\u{180B}'..='\u{180F}');
883        refused.extend('\u{FE00}'..='\u{FE0F}');
884        for c in refused {
885            for key in [format!("ab{c}cd"), format!("{c}abcd"), format!("abcd{c}")] {
886                let error = check_key_text(&key).expect_err(&format!("U+{:04X} was accepted in {key:?}", c as u32));
887                assert!(
888                    error.to_string().contains("surrounding whitespace or control characters"),
889                    "{error}"
890                );
891            }
892        }
893    }
894
895    #[test]
896    fn an_ordinary_key_and_an_inner_ascii_space_are_accepted() {
897        for key in ["0123456789abcdef0123456789abcdef", "a b", "key-with_symbols.~+/=", "é"] {
898            assert!(check_key_text(key).is_ok(), "{key:?}");
899        }
900        for key in [" a", "a ", "\ta", "a\n"] {
901            assert!(check_key_text(key).is_err(), "{key:?}");
902        }
903    }
904
905    #[test]
906    fn a_secret_is_masked_whatever_its_case() {
907        for echo in ["k'ey-abc", "K'EY-ABC", "k'EY-aBc", "K'ey-Abc"] {
908            assert_eq!(redact_secrets(&format!("echo [{echo}] end"), &["K'ey-Abc"]), "echo [***] end", "{echo}");
909        }
910        // Full case folding: ß is found as SS.
911        assert_eq!(redact_secrets("echo [STRASSE1] end", &["straße1"]), "echo [***] end");
912        assert_eq!(redact_secrets("echo [straße1] end", &["STRASSE1"]), "echo [***] end");
913        // Another case of the percent and JSON forms.
914        assert_eq!(redact_secrets("[K%2FEY]", &["k/ey"]), "[***]");
915        assert_eq!(redact_secrets(r#"[K\"EY]"#, &[r#"k"ey"#]), "[***]");
916        // A different secret is left alone.
917        assert_eq!(redact_secrets("echo [K'EZ-ABC] end", &["K'ey-Abc"]), "echo [K'EZ-ABC] end");
918    }
919
920    /// An upper-cased echo of a secret holding a quote, with the quote
921    /// spelled every way a server or proxy may, does not survive. Each
922    /// spelling alone needs its own decoder.
923    #[test]
924    fn an_upper_cased_echo_with_any_quote_spelling_does_not_survive() {
925        let secret = "k'ey1";
926        for (name, echo) in [
927            ("plain", "K'EY1"),
928            ("percent", "K%27EY1"),
929            ("backslash", r"K\'EY1"),
930            ("doubled", "K''EY1"),
931            ("hex, lower x", r"K\x27EY1"),
932            ("hex, upper X", r"K\X27EY1"),
933            ("named, lower", "K&apos;EY1"),
934            ("named, upper", "K&APOS;EY1"),
935            ("named, mixed", "K&Apos;EY1"),
936            ("decimal", "K&#39;EY1"),
937            ("hex reference", "K&#x27;EY1"),
938            ("hex reference, upper", "K&#X27;EY1"),
939            ("hex reference, no semicolon", "K&#39EY1"),
940            ("entity of the ampersand, then the quote", "K&amp;apos;EY1"),
941            ("percent of an upper-cased hex escape", "K%5CX27EY1"),
942        ] {
943            let got = redact_secrets(&format!("bad key [{echo}] here"), &[secret]);
944            assert!(got == CREDENTIAL_OMITTED_MESSAGE || got == "bad key [***] here", "{name}: {got}");
945        }
946    }
947
948    #[test]
949    fn every_quote_decoder_is_needed_on_its_own() {
950        let secret = "k'ey1";
951        for echo in [
952            "K%27EY1",
953            r"K\'EY1",
954            "K''EY1",
955            r"K\x27EY1",
956            r"K\X27EY1",
957            "K&apos;EY1",
958            "K&APOS;EY1",
959            "K&#39;EY1",
960            "K&#X27;EY1",
961        ] {
962            let got = redact_secrets(&format!("bad key [{echo}] here"), &[secret]);
963            assert!(got == CREDENTIAL_OMITTED_MESSAGE || got == "bad key [***] here", "{echo}: {got}");
964            assert!(!got.to_lowercase().contains("ey1"), "{echo}: {got}");
965        }
966        // Not the secret in any view: unchanged.
967        for echo in ["K%27EY2", r"K\'EY2", "K''EY2", r"K\X27EY2", "K&APOS;EY2", "K&#39;EY2"] {
968            let message = format!("bad key [{echo}] here");
969            assert_eq!(redact_secrets(&message, &[secret]), message, "{echo}");
970        }
971    }
972
973    #[test]
974    fn a_quote_in_each_secret_spelling_is_covered_for_a_key_and_a_password() {
975        let key = "ab'cd\"ef";
976        let password = "p@ss'w\"rd";
977        for secret in [key, password] {
978            let upper = secret.to_uppercase();
979            let spellings = [
980                upper.replace('\'', "&APOS;").replace('"', "&QUOT;"),
981                upper.replace('\'', r"\'").replace('"', r#"\""#),
982                upper.replace('\'', "''").replace('"', "\"\""),
983                upper.replace('\'', r"\X27").replace('"', r"\X22"),
984                upper.replace('\'', "%27").replace('"', "%22"),
985            ];
986            for spelling in spellings {
987                let got = redact_secrets(&format!("[{spelling}]"), &[key, password]);
988                assert!(got == CREDENTIAL_OMITTED_MESSAGE || got == "[***]", "{spelling}: {got}");
989            }
990        }
991    }
992}
993
994#[cfg(test)]
995mod http_client_tests {
996    use super::{client_or_error, http_client_with_timeout, ZBError, LAST_TIMEOUT, REQUEST_TIMEOUT, TIMEOUT_DIVISOR};
997    use std::io::Read;
998    use std::net::TcpListener;
999    use std::sync::mpsc;
1000    use std::time::{Duration, Instant};
1001
1002    #[test]
1003    fn the_request_timeout_is_two_minutes() {
1004        assert_eq!(REQUEST_TIMEOUT, Duration::from_secs(120));
1005    }
1006
1007    /// The Warmup client's default timeout is exactly REQUEST_TIMEOUT: the
1008    /// behavioural test below only bounds it to within a few tenths.
1009    #[test]
1010    fn the_warmup_client_is_built_with_exactly_the_request_timeout() {
1011        LAST_TIMEOUT.with(|last| last.set(None));
1012        let _warmup = crate::ZeroBounceWarmup::new("timeout-key").unwrap();
1013        assert_eq!(LAST_TIMEOUT.with(|last| last.get()), Some(Duration::from_secs(120)));
1014    }
1015
1016    /// A local server that accepts every request, reads it and never answers.
1017    fn never_answering_server() -> u16 {
1018        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1019        let port = listener.local_addr().unwrap().port();
1020        std::thread::spawn(move || {
1021            let mut held = Vec::new();
1022            for mut stream in listener.incoming().flatten() {
1023                let mut buffer = [0u8; 4096];
1024                let _ = stream.read(&mut buffer);
1025                held.push(stream);
1026            }
1027        });
1028        port
1029    }
1030
1031    /// A server that accepts the request and never answers. Without a
1032    /// timeout the call would hang for ever; the test gives up after 20
1033    /// seconds and fails instead.
1034    #[test]
1035    fn a_server_that_never_answers_times_out() {
1036        let port = never_answering_server();
1037        let client = http_client_with_timeout(Duration::from_millis(300)).unwrap();
1038        let (sender, receiver) = mpsc::channel();
1039        std::thread::spawn(move || {
1040            let started = Instant::now();
1041            let result = client.get(format!("http://127.0.0.1:{port}/v2/getcredits")).send();
1042            let _ = sender.send((result.map(|response| response.status()), started.elapsed()));
1043        });
1044        let (result, elapsed) = receiver
1045            .recv_timeout(Duration::from_secs(20))
1046            .expect("the request was still waiting after 20 s: the client has no timeout");
1047        let error = result.expect_err("a server that never answered gave a response");
1048        assert!(error.is_timeout(), "{error}");
1049        assert!(elapsed < Duration::from_secs(10), "{elapsed:?}");
1050    }
1051
1052    /// The clients `ZeroBounce::new`, `ZeroBounce::with_base_url` and
1053    /// `ZeroBounceWarmup::with_base_url` (which `ZeroBounceWarmup::new` calls)
1054    /// build give up after REQUEST_TIMEOUT. The test shrinks that 100-fold
1055    /// (to 1.2 s), so a client built with any other timeout (or none) fails
1056    /// here: too soon, too late, or still waiting after 20 s.
1057    #[test]
1058    fn the_public_constructors_build_clients_with_the_request_timeout() {
1059        const DIVISOR: u32 = 100;
1060        let port = never_answering_server();
1061        let base = format!("http://127.0.0.1:{port}");
1062        TIMEOUT_DIVISOR.with(|divisor| divisor.set(DIVISOR));
1063        let mut from_new = crate::ZeroBounce::new("timeout-key");
1064        from_new.url_provider.url = format!("{base}/v2");
1065        let from_base_url = crate::ZeroBounce::with_base_url("timeout-key", format!("{base}/v2")).unwrap();
1066        let warmup = crate::ZeroBounceWarmup::with_base_url("timeout-key", &base).unwrap();
1067        TIMEOUT_DIVISOR.with(|divisor| divisor.set(1));
1068
1069        type Call = Box<dyn FnOnce() -> Result<String, ZBError> + Send>;
1070        let calls: Vec<(&str, Call)> = vec![
1071            ("ZeroBounce::new", Box::new(move || from_new.get_credits().map(|v| format!("{v:?}")))),
1072            ("ZeroBounce::with_base_url", Box::new(move || from_base_url.get_credits().map(|v| format!("{v:?}")))),
1073            ("ZeroBounceWarmup::with_base_url", Box::new(move || warmup.get_seeds().map(|v| format!("{v:?}")))),
1074        ];
1075        let expected = REQUEST_TIMEOUT / DIVISOR;
1076        for (name, call) in calls {
1077            let (sender, receiver) = mpsc::channel();
1078            std::thread::spawn(move || {
1079                let started = Instant::now();
1080                let result = call();
1081                let _ = sender.send((result, started.elapsed()));
1082            });
1083            let (result, elapsed) = receiver
1084                .recv_timeout(Duration::from_secs(20))
1085                .unwrap_or_else(|_| panic!("{name}: still waiting after 20 s, want a timeout after {expected:?}"));
1086            assert!(result.is_err(), "{name}: a server that never answered gave {result:?}");
1087            assert!(
1088                elapsed >= expected * 9 / 10 && elapsed <= expected * 3 / 2,
1089                "{name}: gave up after {elapsed:?}, want about {expected:?}"
1090            );
1091        }
1092    }
1093
1094    /// Both API clients get their reqwest client from `http_client`, so the
1095    /// timeout and the redirect policy reach every request. A client built
1096    /// anywhere else in `src/` would skip them.
1097    #[test]
1098    fn every_http_client_is_built_by_http_client() {
1099        fn rust_files(dir: &std::path::Path, found: &mut Vec<std::path::PathBuf>) {
1100            for entry in std::fs::read_dir(dir).unwrap() {
1101                let path = entry.unwrap().path();
1102                if path.is_dir() {
1103                    rust_files(&path, found);
1104                } else if path.extension().is_some_and(|ext| ext == "rs") {
1105                    found.push(path);
1106                }
1107            }
1108        }
1109        let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
1110        let mut files = Vec::new();
1111        rust_files(&src, &mut files);
1112        assert!(files.len() > 5, "no Rust sources under {}", src.display());
1113        let mut found = Vec::new();
1114        for file in files {
1115            let source = std::fs::read_to_string(&file).unwrap();
1116            // This file is the one place a client is built (and its tests
1117            // build one more to get a builder error).
1118            if file.ends_with("utility/mod.rs") {
1119                continue;
1120            }
1121            for (number, line) in source.lines().enumerate() {
1122                let code = line.trim_start();
1123                if code.starts_with("//") {
1124                    continue;
1125                }
1126                for pattern in [
1127                    "Client::new(",
1128                    "Client::builder(",
1129                    "Client::default(",
1130                    "ClientBuilder::new(",
1131                    "blocking::get(",
1132                ] {
1133                    if code.contains(pattern) {
1134                        found.push(format!("{}:{}: {code}", file.display(), number + 1));
1135                    }
1136                }
1137            }
1138        }
1139        assert!(found.is_empty(), "HTTP clients built outside http_client: {found:#?}");
1140    }
1141
1142    /// A builder failure used to fall back to `Client::default()`, which
1143    /// follows redirects. It is now an error.
1144    #[test]
1145    fn a_client_that_cannot_be_built_is_an_error_not_a_default_client() {
1146        let builder_error = reqwest::blocking::Client::new()
1147            .get("not a url")
1148            .build()
1149            .unwrap_err();
1150        match client_or_error(Err(builder_error)) {
1151            Err(ZBError::ExplicitError(message)) => {
1152                assert!(message.starts_with("could not build the HTTP client"), "{message}")
1153            }
1154            other => panic!("expected an error, got {other:?}"),
1155        }
1156    }
1157}
1158
1159pub const CONTENT_TYPE_JSON: &str = "application/json";
1160pub const CONTENT_TYPE_STREAM: &str = "application/octet-stream";
1161/// Cap JSON API responses so error pages cannot exhaust memory (RS-05).
1162pub const MAX_JSON_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
1163/// Cap bulk getfile downloads (still large enough for typical CSV exports).
1164pub const MAX_GETFILE_BYTES: usize = 256 * 1024 * 1024;
1165
1166/// Stop reading after one byte past the cap, so an oversized response cannot
1167/// consume unbounded memory before the caller checks its length. A body over
1168/// the cap is the server's answer, so it keeps the response's HTTP status: a
1169/// [`ZBError::ApiError`] with `status` (a 500 stays 500, a 200 is an API
1170/// error with status 200).
1171pub(crate) fn read_limited(
1172    mut reader: impl Read,
1173    max_bytes: usize,
1174    status: u16,
1175    message: &str,
1176) -> ZBResult<Vec<u8>> {
1177    let mut body = Vec::new();
1178    reader.by_ref().take(max_bytes as u64 + 1).read_to_end(&mut body)?;
1179    if body.len() > max_bytes {
1180        return Err(ZBError::api(status, message));
1181    }
1182    Ok(body)
1183}
1184
1185#[cfg(test)]
1186mod response_limit_tests {
1187    use super::read_limited;
1188    use std::io::{self, Read};
1189
1190    struct CountingReader {
1191        remaining: usize,
1192        read: usize,
1193    }
1194
1195    impl Read for CountingReader {
1196        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1197            let n = buf.len().min(self.remaining);
1198            buf[..n].fill(b'x');
1199            self.remaining -= n;
1200            self.read += n;
1201            Ok(n)
1202        }
1203    }
1204
1205    #[test]
1206    fn stops_at_one_byte_past_limit() {
1207        let mut source = CountingReader {
1208            remaining: 10_000,
1209            read: 0,
1210        };
1211        let error = read_limited(&mut source, 32, 500, "too large").unwrap_err();
1212        assert_eq!(error.to_string(), "too large");
1213        assert_eq!(error.status_code(), Some(500));
1214        assert_eq!(source.read, 33);
1215    }
1216
1217    #[test]
1218    fn accepts_body_at_limit() {
1219        let body = read_limited(&b"exact"[..], 5, 200, "too large").unwrap();
1220        assert_eq!(body, b"exact");
1221    }
1222}
1223
1224/// Enum representing the available API base URLs
1225///
1226/// `#[non_exhaustive]`: a region added later is not a breaking change, so a
1227/// `match` on it needs a `_` arm.
1228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1229#[non_exhaustive]
1230pub enum ApiBaseUrl {
1231    /// Default API URL: <https://api.zerobounce.net/v2/>
1232    Default,
1233    /// USA API URL: <https://api-us.zerobounce.net/v2/>
1234    USA,
1235    /// EU API URL: <https://api-eu.zerobounce.net/v2/>
1236    EU,
1237}
1238
1239impl ApiBaseUrl {
1240    /// Get the URL string for this API base URL
1241    pub fn as_str(&self) -> &'static str {
1242        match self {
1243            ApiBaseUrl::Default => "https://api.zerobounce.net/v2/",
1244            ApiBaseUrl::USA => "https://api-us.zerobounce.net/v2/",
1245            ApiBaseUrl::EU => "https://api-eu.zerobounce.net/v2/",
1246        }
1247    }
1248}
1249
1250impl From<ApiBaseUrl> for String {
1251    fn from(url: ApiBaseUrl) -> Self {
1252        url.as_str().to_string()
1253    }
1254}
1255
1256impl From<&ApiBaseUrl> for String {
1257    fn from(url: &ApiBaseUrl) -> Self {
1258        url.as_str().to_string()
1259    }
1260}
1261
1262/// Percent-encodes a value so it is one path segment.
1263///
1264/// Only the unreserved set from RFC 3986 is left alone, so `/`, spaces and the
1265/// rest are escaped and a file id cannot break out of its segment. Written here
1266/// rather than pulling in a crate for four lines.
1267pub fn encode_path_segment(value: &str) -> String {
1268    let mut encoded = String::with_capacity(value.len());
1269    for byte in value.as_bytes() {
1270        match byte {
1271            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
1272                encoded.push(*byte as char)
1273            }
1274            _ => encoded.push_str(&format!("%{:02X}", byte)),
1275        }
1276    }
1277    encoded
1278}
1279
1280pub const BULK_URI: &str = "https://bulkapi.zerobounce.net/v2";
1281/// The list evaluator and the Inbox Placement Tester are not under the bulk /v2 path.
1282pub const LIST_EVALUATOR_URI: &str = "https://bulkapi.zerobounce.net/v2/listevaluator";
1283pub const INBOX_PLACEMENT_URI: &str = "https://bulkapi.zerobounce.net/api/ipt";
1284pub const ENDPOINT_CREDITS: &str = "/getcredits";
1285pub const ENDPOINT_ACTIVITY_DATA: &str = "/activity";
1286pub const ENDPOINT_SCORING: &str = "/scoring";
1287pub const ENDPOINT_VALIDATE: &str = "/validate";
1288pub const ENDPOINT_API_USAGE: &str = "/getapiusage";
1289pub const ENDPOINT_BATCH_VALIDATE: &str = "/validatebatch";
1290pub const ENDPOINT_FILE_SEND: &str = "/sendfile";
1291pub const ENDPOINT_FILE_STATUS: &str = "/filestatus";
1292pub const ENDPOINT_FILE_RESULT: &str = "/getfile";
1293pub const ENDPOINT_FILE_DELETE: &str = "/deletefile";
1294pub const ENDPOINT_SCORING_SEND: &str = "/scoring/sendfile";
1295pub const ENDPOINT_SCORING_STATUS: &str = "/scoring/filestatus";
1296pub const ENDPOINT_SCORING_RESULT: &str = "/scoring/getfile";
1297pub const ENDPOINT_SCORING_DELETE: &str = "/scoring/deletefile";
1298pub const ENDPOINT_EMAIL_FINDER: &str = "/guessformat";
1299
1300// validation statuses
1301pub const S_VALID: &str = "valid";
1302pub const S_INVALID: &str = "invalid";
1303pub const S_CATCH_ALL: &str = "catch-all";
1304pub const S_UNKNOWN: &str = "unknown";
1305pub const S_SPAMTRAP: &str = "spamtrap";
1306pub const S_ABUSE: &str = "abuse";
1307pub const S_DO_NOT_MAIL: &str = "do_not_mail";
1308
1309// validation sub statuses
1310pub const SS_ANTISPAM_SYSTEM: &str = "antispam_system";
1311pub const SS_GREYLISTED: &str = "greylisted";
1312pub const SS_MAIL_SERVER_TEMPORARY_ERROR: &str = "mail_server_temporary_error";
1313pub const SS_FORCIBLE_DISCONNECT: &str = "forcible_disconnect";
1314pub const SS_MAIL_SERVER_DID_NOT_RESPOND: &str = "mail_server_did_not_respond";
1315pub const SS_TIMEOUT_EXCEEDED: &str = "timeout_exceeded";
1316pub const SS_FAILED_SMTP_CONNECTION: &str = "failed_smtp_connection";
1317pub const SS_MAILBOX_QUOTA_EXCEEDED: &str = "mailbox_quota_exceeded";
1318pub const SS_EXCEPTION_OCCURRED: &str = "exception_occurred";
1319pub const SS_POSSIBLE_TRAP: &str = "possible_trap";
1320pub const SS_ROLE_BASED: &str = "role_based";
1321pub const SS_GLOBAL_SUPPRESSION: &str = "global_suppression";
1322pub const SS_MAILBOX_NOT_FOUND: &str = "mailbox_not_found";
1323pub const SS_NO_DNS_ENTRIES: &str = "no_dns_entries";
1324pub const SS_FAILED_SYNTAX_CHECK: &str = "failed_syntax_check";
1325pub const SS_POSSIBLE_TYPO: &str = "possible_typo";
1326pub const SS_UNROUTABLE_IP_ADDRESS: &str = "unroutable_ip_address";
1327pub const SS_LEADING_PERIOD_REMOVED: &str = "leading_period_removed";
1328pub const SS_DOES_NOT_ACCEPT_MAIL: &str = "does_not_accept_mail";
1329pub const SS_ALIAS_ADDRESS: &str = "alias_address";
1330pub const SS_ROLE_BASED_CATCH_ALL: &str = "role_based_catch_all";
1331pub const SS_DISPOSABLE: &str = "disposable";
1332pub const SS_TOXIC: &str = "toxic";
1333pub const SS_ACCEPT_ALL: &str = "accept_all";
1334pub const SS_AI_AGENT_MAILBOX: &str = "ai_agent_mailbox";
1335
1336/// Every error the SDK returns.
1337///
1338/// `#[non_exhaustive]`: a variant added later is not a breaking change, so a
1339/// `match` on it needs a `_` arm.
1340#[derive(Debug)]
1341#[non_exhaustive]
1342pub enum ZBError {
1343    /// An error the SDK raised itself: an invalid argument or URL caught before
1344    /// a request, or a local failure such as a file that cannot be written.
1345    ExplicitError(String),
1346    /// The API answered and the answer is a failure: a non-2xx status, an HTML
1347    /// error page, an error body on an HTTP 200, a bulk `getfile` error, or a
1348    /// `batch_validate` account-level error. `status` is the HTTP status of that
1349    /// response, so callers can tell a 403 from Cloudflare apart from a 400/404
1350    /// from the API and a 429 from the Warmup rate limit. A 2xx body that is
1351    /// not strict JSON, or is JSON of the wrong shape for the call (`0`,
1352    /// `"x"`, `null`, a list where an object is expected, a field of the wrong
1353    /// type), is an `ApiError` with status 200. Both the validation client and
1354    /// the Warmup client return it.
1355    ApiError { status: u16, message: String },
1356    /// A `serde_json::Error` converted with `From` (`?`). The SDK's own calls
1357    /// no longer return it: a 2xx body of the wrong shape is an
1358    /// [`ZBError::ApiError`] with status 200. Kept for code that converts its
1359    /// own serde errors. The inner error names only the kind of error and its
1360    /// line and column, never the input (serde's own message quotes the value
1361    /// it rejected).
1362    JsonError(serde_json::Error),
1363    /// The SDK's own calls no longer return it: an unreadable `Credits` value
1364    /// is an [`ZBError::ApiError`] with status 200. Kept for compatibility.
1365    IntParseError(std::num::ParseIntError),
1366    RequestError(reqwest::Error),
1367    IOError(IOError),
1368}
1369
1370pub type ZBResult<T> = Result<T, ZBError>;
1371
1372impl ZBError {
1373    pub fn explicit(string: &str) -> ZBError {
1374        ZBError::ExplicitError(string.to_string())
1375    }
1376
1377    pub fn api(status: u16, message: impl Into<String>) -> ZBError {
1378        ZBError::ApiError {
1379            status,
1380            message: message.into(),
1381        }
1382    }
1383
1384    /// This error with every secret masked in an API error's message
1385    /// ([`redact_secrets`]). Other errors carry no response body.
1386    pub(crate) fn redacted(self, secrets: &[&str]) -> ZBError {
1387        match self {
1388            ZBError::ApiError { status, message } => ZBError::ApiError {
1389                status,
1390                message: redact_secrets(&message, secrets),
1391            },
1392            other => other,
1393        }
1394    }
1395
1396    /// The HTTP status of a failed API response: `Some` for every
1397    /// [`ZBError::ApiError`], including a failure the API reports with an HTTP
1398    /// 200 and a 2xx body that is not JSON or not the call's shape (`Some(200)`).
1399    /// `None` when no response is involved: an argument or URL rejected before
1400    /// a request, or a transport error.
1401    pub fn status_code(&self) -> Option<u16> {
1402        match self {
1403            ZBError::ApiError { status, .. } => Some(*status),
1404            _ => None,
1405        }
1406    }
1407}
1408
1409impl std::fmt::Display for ZBError {
1410    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1411        match self {
1412            ZBError::ExplicitError(message) => write!(formatter, "{message}"),
1413            ZBError::ApiError { message, .. } => write!(formatter, "{message}"),
1414            ZBError::JsonError(_) => {
1415                write!(
1416                    formatter,
1417                    "ZeroBounce returned a response that is not valid JSON."
1418                )
1419            }
1420            ZBError::IntParseError(_) => write!(
1421                formatter,
1422                "ZeroBounce returned a response that could not be read."
1423            ),
1424            ZBError::RequestError(error) => write!(formatter, "{error}"),
1425            ZBError::IOError(error) => write!(formatter, "{error}"),
1426        }
1427    }
1428}
1429
1430impl std::error::Error for ZBError {}
1431
1432// Implementation made in order to automatically convert errors
1433// generated by the reqwuest library into a ZBError instance.
1434//
1435// This automatic conversion is expected when using the client
1436// and issuing http requests.
1437fn redact_api_key(url: &mut reqwest::Url) {
1438    if !url.query_pairs().any(|(key, _)| key == "api_key") {
1439        return;
1440    }
1441    let pairs: Vec<(String, String)> = url
1442        .query_pairs()
1443        .map(|(key, value)| {
1444            let value = if key == "api_key" {
1445                "REDACTED".to_string()
1446            } else {
1447                value.into_owned()
1448            };
1449            (key.into_owned(), value)
1450        })
1451        .collect();
1452    url.query_pairs_mut().clear().extend_pairs(pairs);
1453}
1454
1455impl From<reqwest::Error> for ZBError {
1456    fn from(mut value: reqwest::Error) -> ZBError {
1457        if let Some(url) = value.url_mut() {
1458            redact_api_key(url);
1459        }
1460        ZBError::RequestError(value)
1461    }
1462}
1463
1464// Implementation made in order to automatically convert errors
1465// generated by the serde_json library into a ZBError instance.
1466//
1467// This automatic conversion is expected when deserializing.
1468//
1469// serde's own message quotes the value it could not read (`invalid type:
1470// string "<value>", expected u64`, `unknown variant `<value>``), so a 2xx body
1471// that echoed the API key in a wrongly typed field handed the key on in the
1472// `JsonError`'s Debug output and in the error it carries. The error kept here
1473// says only what kind of error it was and where: no body content.
1474impl From<serde_json::Error> for ZBError {
1475    fn from(value: serde_json::Error) -> ZBError {
1476        use serde::de::Error as _;
1477        let kind = match value.classify() {
1478            serde_json::error::Category::Io => "I/O error",
1479            serde_json::error::Category::Syntax => "invalid JSON",
1480            serde_json::error::Category::Data => "unexpected JSON data",
1481            serde_json::error::Category::Eof => "unexpected end of JSON",
1482        };
1483        ZBError::JsonError(serde_json::Error::custom(format!(
1484            "{kind} at line {} column {}",
1485            value.line(),
1486            value.column()
1487        )))
1488    }
1489}
1490
1491impl From<IOError> for ZBError {
1492    fn from(value: IOError) -> Self {
1493        ZBError::IOError(value)
1494    }
1495}
1496
1497#[cfg(test)]
1498mod json_error_tests {
1499    use super::ZBError;
1500
1501    /// serde quotes the value it rejected; the error kept drops it and keeps
1502    /// the position.
1503    #[test]
1504    fn a_json_error_keeps_the_position_and_drops_the_value() {
1505        let parsed: Result<u64, _> = serde_json::from_str("\n  \"secret-value\"");
1506        let error = ZBError::from(parsed.unwrap_err());
1507        let ZBError::JsonError(inner) = &error else {
1508            panic!("{error:?}");
1509        };
1510        assert_eq!((inner.line(), inner.column()), (2, 16));
1511        assert_eq!(inner.to_string(), "unexpected JSON data at line 2 column 16");
1512        for text in [error.to_string(), format!("{error:?}"), format!("{inner:?}")] {
1513            assert!(!text.contains("secret-value"), "{text}");
1514        }
1515        let syntax: Result<serde_json::Value, _> = serde_json::from_str("[1 secret]");
1516        let error = ZBError::from(syntax.unwrap_err());
1517        assert!(!format!("{error:?}").contains("secret"), "{error:?}");
1518        assert!(format!("{error:?}").contains("invalid JSON"), "{error:?}");
1519    }
1520}