pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Explicit account-exposure lookup.
//!
//! HIBP account queries disclose the complete address to the provider. Results
//! describe historical corpus membership, not current mailbox existence or
//! safety, and never affect a Pata validation verdict.

use std::fmt;

use serde::Deserialize;
use sha1::{Digest as _, Sha1};

use crate::Address;

const API_BASE: &str = "https://haveibeenpwned.com/api/v3/";
const BODY_LIMIT: usize = 2 * 1024 * 1024;

/// One breach returned by Have I Been Pwned.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Breach {
    name: String,
    title: String,
    domain: String,
    breach_date: String,
    added_date: String,
    pwn_count: u64,
    data_classes: Vec<String>,
    is_verified: bool,
    is_sensitive: bool,
}

impl Breach {
    /// Returns the provider-stable breach name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the human-facing breach title.
    #[must_use]
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Returns the breached service domain when supplied.
    #[must_use]
    pub fn domain(&self) -> &str {
        &self.domain
    }

    /// Returns the provider's ISO calendar breach date.
    #[must_use]
    pub fn breach_date(&self) -> &str {
        &self.breach_date
    }

    /// Returns the provider's ISO timestamp for corpus inclusion.
    #[must_use]
    pub fn added_date(&self) -> &str {
        &self.added_date
    }

    /// Returns the provider's estimated number of affected accounts.
    #[must_use]
    pub const fn affected_accounts(&self) -> u64 {
        self.pwn_count
    }

    /// Returns the exposed data categories.
    #[must_use]
    pub fn data_classes(&self) -> &[String] {
        &self.data_classes
    }

    /// Returns whether HIBP verified this breach.
    #[must_use]
    pub const fn is_verified(&self) -> bool {
        self.is_verified
    }

    /// Returns whether HIBP marks this breach as sensitive.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.is_sensitive
    }
}

/// Why an exposure query could not produce an authoritative result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ExposureUnavailable {
    /// The request could not be completed.
    Transport,
    /// HIBP rejected the API credential.
    Authentication,
    /// The subscription or request policy does not permit the lookup.
    AccessDenied,
    /// HIBP rate-limited the request.
    RateLimited {
        /// The provider's requested delay when it supplied whole seconds.
        retry_after: Option<std::time::Duration>,
    },
    /// HIBP returned an unexpected response.
    Provider,
}

/// The semantic result of an explicit account-exposure query.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ExposureStatus {
    /// HIBP returned one or more historical breaches.
    Exposed(Vec<Breach>),
    /// HIBP returned no match from its public breach results.
    NotFound,
    /// The provider could not answer authoritatively.
    Unavailable(ExposureUnavailable),
}

/// The semantic result of a privacy-preserving HIBP hash-range query.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum HashRangeStatus {
    /// HIBP associated the address hash with these public breach names.
    Exposed(Vec<String>),
    /// The public range contained no match for the complete address hash.
    NotFound,
    /// The provider could not answer authoritatively.
    Unavailable(ExposureUnavailable),
}

/// An authenticated, bounded, runtime-neutral HIBP account client.
///
/// A response larger than 2 MiB produces a provider-unavailable result.
#[derive(Clone)]
pub struct BreachClient {
    http: tez::Client,
}

impl BreachClient {
    /// Builds a client for HIBP's breached-account API.
    ///
    /// `user_agent` must identify the consuming application as required by
    /// HIBP. The key is retained by Tez as secret authentication state.
    pub fn new(
        api_key: impl AsRef<str>,
        user_agent: impl AsRef<str>,
    ) -> Result<Self, BreachClientError> {
        if api_key.as_ref().len() != 32
            || !api_key
                .as_ref()
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit())
        {
            return Err(BreachClientError::Configuration(
                "API key must be 32 hexadecimal characters",
            ));
        }
        if user_agent.as_ref().trim().is_empty() {
            return Err(BreachClientError::Configuration(
                "user agent must not be empty",
            ));
        }
        let authentication = tez::auth::ApiKeyAuth::new(
            "hibp-api-key",
            secrecy::SecretString::from(api_key.as_ref().to_owned()),
        )
        .map_err(|_| BreachClientError::Configuration("API key is invalid"))?;
        let http = tez::Client::builder()
            .base_url(API_BASE)
            .user_agent(user_agent)
            .timeout(std::time::Duration::from_secs(15))
            .auth(authentication)
            .build()
            .map_err(|_| BreachClientError::Initialization)?;
        Ok(Self { http })
    }

    /// Sends the complete address to HIBP and does not cache the result.
    pub async fn lookup(&self, address: &Address) -> ExposureStatus {
        let mut target = match url::Url::parse(API_BASE) {
            Ok(target) => target,
            Err(_) => return ExposureStatus::Unavailable(ExposureUnavailable::Provider),
        };
        match target.path_segments_mut() {
            Ok(mut path) => {
                path.push("breachedaccount");
                path.push(&address.to_string());
            }
            Err(()) => return ExposureStatus::Unavailable(ExposureUnavailable::Provider),
        }
        target
            .query_pairs_mut()
            .append_pair("truncateResponse", "false");

        let response = self.http.get(target.as_str()).send().await;
        let response = match response {
            Ok(response) => response,
            Err(_) => return ExposureStatus::Unavailable(ExposureUnavailable::Transport),
        };

        match response.status().as_u16() {
            200 => {
                match crate::provider_response::json::<Vec<Breach>>(response, BODY_LIMIT).await {
                    Ok(breaches) if !breaches.is_empty() => ExposureStatus::Exposed(breaches),
                    Ok(_) | Err(_) => ExposureStatus::Unavailable(ExposureUnavailable::Provider),
                }
            }
            status => account_status(status, crate::provider_response::retry_after(&response)),
        }
    }

    /// Queries HIBP by a six-character SHA-1 prefix.
    ///
    /// The request does not disclose the complete address or its complete
    /// hash. HIBP returns breach names rather than full breach metadata. The
    /// API key's subscription must include k-anonymity search.
    pub async fn lookup_by_hash_range(&self, address: &Address) -> HashRangeStatus {
        let (prefix, suffix) = hash_range(address);
        let response = self
            .http
            .get(format!("{API_BASE}breachedaccount/range/{prefix}"))
            .send()
            .await;
        let response = match response {
            Ok(response) => response,
            Err(_) => return HashRangeStatus::Unavailable(ExposureUnavailable::Transport),
        };

        match response.status().as_u16() {
            200 => {
                match crate::provider_response::json::<Vec<HashRange>>(response, BODY_LIMIT).await {
                    Ok(entries) => match_hash_range(entries, &suffix),
                    Err(_) => HashRangeStatus::Unavailable(ExposureUnavailable::Provider),
                }
            }
            status => range_status(status, crate::provider_response::retry_after(&response)),
        }
    }
}

fn account_status(status: u16, retry_after: Option<std::time::Duration>) -> ExposureStatus {
    match status {
        404 => ExposureStatus::NotFound,
        401 => ExposureStatus::Unavailable(ExposureUnavailable::Authentication),
        403 => ExposureStatus::Unavailable(ExposureUnavailable::AccessDenied),
        429 => ExposureStatus::Unavailable(ExposureUnavailable::RateLimited { retry_after }),
        _ => ExposureStatus::Unavailable(ExposureUnavailable::Provider),
    }
}

fn range_status(status: u16, retry_after: Option<std::time::Duration>) -> HashRangeStatus {
    match status {
        404 => HashRangeStatus::NotFound,
        401 => HashRangeStatus::Unavailable(ExposureUnavailable::Authentication),
        403 => HashRangeStatus::Unavailable(ExposureUnavailable::AccessDenied),
        429 => HashRangeStatus::Unavailable(ExposureUnavailable::RateLimited { retry_after }),
        _ => HashRangeStatus::Unavailable(ExposureUnavailable::Provider),
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct HashRange {
    hash_suffix: String,
    websites: Vec<String>,
}

fn hash_range(address: &Address) -> (String, String) {
    let normalized = address.to_string().to_lowercase();
    let digest = Sha1::digest(normalized.as_bytes());
    let hash = hex(&digest);
    (hash[..6].to_owned(), hash[6..].to_owned())
}

fn match_hash_range(entries: Vec<HashRange>, suffix: &str) -> HashRangeStatus {
    let mut matches = entries
        .into_iter()
        .filter(|entry| entry.hash_suffix.eq_ignore_ascii_case(suffix));
    let Some(mut matched) = matches.next() else {
        return HashRangeStatus::NotFound;
    };
    if matches.next().is_some()
        || matched.websites.is_empty()
        || matched.websites.iter().any(|name| name.trim().is_empty())
    {
        return HashRangeStatus::Unavailable(ExposureUnavailable::Provider);
    }
    matched.websites.sort_unstable();
    matched.websites.dedup();
    HashRangeStatus::Exposed(matched.websites)
}

fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
        output.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
    }
    output
}

impl fmt::Debug for BreachClient {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("BreachClient")
            .finish_non_exhaustive()
    }
}

/// A breach client construction failure.
#[derive(Clone, Copy, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BreachClientError {
    /// A caller-supplied setting is invalid.
    #[error("breach client configuration is invalid: {0}")]
    Configuration(&'static str),
    /// The private HTTP capability could not be initialized.
    #[error("breach HTTP client could not be initialized")]
    Initialization,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn client_debug_redacts_api_key() {
        let key = "0123456789abcdef0123456789abcdef";
        let client = BreachClient::new(key, "pata-tests/1").unwrap();
        assert!(!format!("{client:?}").contains(key));
    }

    #[test]
    fn invalid_configuration_does_not_echo_secrets() {
        let error = BreachClient::new("private-key\n", "pata-tests/1").unwrap_err();
        assert!(!error.to_string().contains("private-key"));
    }

    #[test]
    fn hash_range_matches_hibp_normalization() {
        let address = Address::parse("test@example.com").unwrap();
        let (prefix, suffix) = hash_range(&address);

        assert_eq!(prefix, "567159");
        assert_eq!(suffix, "D622FFBB50B11B0EFD307BE358624A26EE");
    }

    #[test]
    fn hash_range_discards_unrelated_entries_and_normalizes_names() {
        let status = match_hash_range(
            vec![
                HashRange {
                    hash_suffix: "unrelated".to_owned(),
                    websites: vec!["Private".to_owned()],
                },
                HashRange {
                    hash_suffix: "MATCH".to_owned(),
                    websites: vec!["Gawker".to_owned(), "Adobe".to_owned(), "Adobe".to_owned()],
                },
            ],
            "match",
        );

        assert_eq!(
            status,
            HashRangeStatus::Exposed(vec!["Adobe".to_owned(), "Gawker".to_owned()])
        );
    }

    #[test]
    fn hash_range_rejects_empty_breach_names() {
        let status = match_hash_range(
            vec![HashRange {
                hash_suffix: "MATCH".to_owned(),
                websites: vec![String::new()],
            }],
            "match",
        );

        assert_eq!(
            status,
            HashRangeStatus::Unavailable(ExposureUnavailable::Provider)
        );
    }

    #[test]
    fn account_statuses_preserve_provider_meaning() {
        let retry_after = Some(std::time::Duration::from_secs(30));

        assert_eq!(account_status(404, None), ExposureStatus::NotFound);
        assert_eq!(
            account_status(401, None),
            ExposureStatus::Unavailable(ExposureUnavailable::Authentication)
        );
        assert_eq!(
            account_status(403, None),
            ExposureStatus::Unavailable(ExposureUnavailable::AccessDenied)
        );
        assert_eq!(
            account_status(429, retry_after),
            ExposureStatus::Unavailable(ExposureUnavailable::RateLimited { retry_after })
        );
        assert_eq!(
            account_status(503, None),
            ExposureStatus::Unavailable(ExposureUnavailable::Provider)
        );
    }

    #[test]
    fn empty_hash_range_is_an_authoritative_absence() {
        assert_eq!(range_status(404, None), HashRangeStatus::NotFound);
    }

    #[test]
    fn hash_range_statuses_preserve_provider_failures() {
        let retry_after = Some(std::time::Duration::from_secs(30));

        assert_eq!(
            range_status(401, None),
            HashRangeStatus::Unavailable(ExposureUnavailable::Authentication)
        );
        assert_eq!(
            range_status(403, None),
            HashRangeStatus::Unavailable(ExposureUnavailable::AccessDenied)
        );
        assert_eq!(
            range_status(429, retry_after),
            HashRangeStatus::Unavailable(ExposureUnavailable::RateLimited { retry_after })
        );
        assert_eq!(
            range_status(503, None),
            HashRangeStatus::Unavailable(ExposureUnavailable::Provider)
        );
    }

    #[test]
    fn breach_decodes_the_provider_field_names() {
        let breach: Breach = serde_json::from_str(
            r#"{
                "Name": "Example",
                "Title": "Example breach",
                "Domain": "example.com",
                "BreachDate": "2026-01-02",
                "AddedDate": "2026-01-03T04:05:06Z",
                "PwnCount": 42,
                "DataClasses": ["Email addresses"],
                "IsVerified": true,
                "IsSensitive": false
            }"#,
        )
        .unwrap();

        assert_eq!(breach.name(), "Example");
        assert_eq!(breach.affected_accounts(), 42);
    }
}