entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Have I Been Pwned (HIBP) k-anonymity password breach checking.
//!
//! This module is **transport-agnostic**: it computes the SHA-1 hash and
//! prefix needed for the HIBP range API, and parses the response body.
//! The caller is responsible for making the HTTP request to
//! `https://api.pwnedpasswords.com/range/{prefix}`.
//!
//! # Protocol
//!
//! The HIBP Pwned Passwords API uses k-anonymity to avoid sending the
//! full password hash over the network:
//!
//! 1. SHA-1 hash the password, uppercase hex-encode it (40 characters).
//! 2. Send the first 5 characters (the *prefix*) to the API.
//! 3. The API returns all known suffix/count pairs for that prefix.
//! 4. Check locally whether the remaining 35-character suffix appears in
//!    the response.
//!
//! # Example
//!
//! ```
//! use entropy_auth::mfa::hibp::{HibpPrefix, HibpResponse};
//!
//! let prefix = HibpPrefix::from_password("password");
//! assert_eq!(prefix.as_str(), "5BAA6");
//!
//! // In a real application, you would HTTP GET:
//! //   https://api.pwnedpasswords.com/range/{prefix.as_str()}
//! // and pass the response body to HibpResponse::parse().
//! ```

use core::fmt;

use crate::crypto::Sha1;
use crate::crypto::constant_time::constant_time_eq;
use crate::encoding::hex_encode_upper;

// ---------------------------------------------------------------------------
// SHA-1 hex helper
// ---------------------------------------------------------------------------

/// Compute the SHA-1 hash of a password and return it as an uppercase
/// 40-character hexadecimal string.
///
/// This is the format expected by the HIBP Pwned Passwords API.
#[must_use]
pub fn hibp_sha1_hex(password: &str) -> String {
    let digest = Sha1::digest(password.as_bytes());
    hex_encode_upper(&digest)
}

// ---------------------------------------------------------------------------
// HibpPrefix
// ---------------------------------------------------------------------------

/// The 5-character prefix and full hash for a HIBP k-anonymity lookup.
///
/// Constructed from a password via [`from_password`](HibpPrefix::from_password).
/// The prefix is sent to the HIBP range API, while the suffix is used
/// locally to check the response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HibpPrefix {
    hash: String,
}

impl HibpPrefix {
    /// Computes the SHA-1 hash of `password` and stores the uppercase
    /// hex result for prefix/suffix splitting.
    #[must_use]
    pub fn from_password(password: &str) -> Self {
        Self {
            hash: hibp_sha1_hex(password),
        }
    }

    /// Returns the 5-character prefix to send to the HIBP range API.
    #[must_use]
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.hash[..5]
    }

    /// Returns the 35-character suffix used for local comparison against
    /// the API response.
    #[must_use]
    #[inline]
    pub fn suffix(&self) -> &str {
        &self.hash[5..]
    }

    /// Returns the full 40-character uppercase hex SHA-1 hash.
    #[must_use]
    #[inline]
    pub fn full_hash(&self) -> &str {
        &self.hash
    }
}

// ---------------------------------------------------------------------------
// BreachResult
// ---------------------------------------------------------------------------

/// The result of checking a password against the HIBP response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BreachResult {
    /// The password was not found in the breach database.
    NotBreached,
    /// The password was found, with the given breach count.
    Breached {
        /// Number of times the password appeared in data breaches.
        count: u64,
    },
}

impl BreachResult {
    /// Returns `true` if the password was found in the breach database.
    #[must_use]
    #[inline]
    pub fn is_breached(&self) -> bool {
        matches!(self, Self::Breached { .. })
    }

    /// Returns the breach count, or `0` if the password was not breached.
    #[must_use]
    #[inline]
    pub fn count(&self) -> u64 {
        match self {
            Self::NotBreached => 0,
            Self::Breached { count } => *count,
        }
    }
}

// ---------------------------------------------------------------------------
// HibpResponse
// ---------------------------------------------------------------------------

/// A parsed HIBP range API response.
///
/// The HIBP API returns lines of the form `SUFFIX:COUNT`, where `SUFFIX`
/// is a 35-character uppercase hex string and `COUNT` is a positive
/// integer. This struct holds the parsed entries and supports checking
/// whether a given password appears in the response.
#[derive(Debug, Clone)]
pub struct HibpResponse {
    entries: Vec<(String, u64)>,
}

impl HibpResponse {
    /// Parse the body of a HIBP range API response.
    ///
    /// Each non-empty line must be in the format `SUFFIX:COUNT` where
    /// `SUFFIX` is a 35-character uppercase hex string and `COUNT` is
    /// a positive integer.
    ///
    /// # Errors
    ///
    /// Returns [`HibpError`] if the body is empty, contains malformed
    /// lines, invalid suffixes, or unparseable counts.
    pub fn parse(body: &str) -> Result<Self, HibpError> {
        let mut entries = Vec::new();

        for line in body.split('\n') {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            let Some((suffix, count_str)) = line.split_once(':') else {
                return Err(HibpError::new(HibpErrorKind::MalformedLine));
            };

            // Validate suffix: must be exactly 35 uppercase hex characters.
            if suffix.len() != 35 {
                return Err(HibpError::new(HibpErrorKind::InvalidSuffix));
            }
            if !suffix
                .bytes()
                .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_lowercase())
            {
                return Err(HibpError::new(HibpErrorKind::InvalidSuffix));
            }

            let count: u64 = count_str
                .parse()
                .map_err(|_| HibpError::new(HibpErrorKind::InvalidCount))?;

            entries.push((suffix.to_owned(), count));
        }

        if entries.is_empty() {
            return Err(HibpError::new(HibpErrorKind::EmptyResponse));
        }

        Ok(Self { entries })
    }

    /// Check whether the given password appears in this response.
    ///
    /// Computes the SHA-1 hash of the password, extracts the suffix,
    /// and searches the response entries.
    #[must_use]
    pub fn check_password(&self, password: &str) -> BreachResult {
        let prefix = HibpPrefix::from_password(password);
        self.check_prefix(&prefix)
    }

    /// Check whether the password corresponding to a pre-computed
    /// [`HibpPrefix`] appears in this response.
    ///
    /// # Security
    ///
    /// The scan is constant-time per the crate's secret-comparison
    /// contract: each entry is compared with [`constant_time_eq`] and the
    /// loop never short-circuits, so neither *whether* a match occurred nor
    /// its *position* in the list is revealed through timing. Both operands
    /// are already uppercase hex — the response parser rejects lowercase
    /// suffixes and [`HibpPrefix`] is built with an uppercase encoder — so
    /// no case folding is needed.
    #[must_use]
    pub fn check_prefix(&self, prefix: &HibpPrefix) -> BreachResult {
        let suffix = prefix.suffix().as_bytes();
        let mut count = 0u64;
        let mut found = false;
        for (entry_suffix, entry_count) in &self.entries {
            if constant_time_eq(entry_suffix.as_bytes(), suffix) {
                count = *entry_count;
                found = true;
            }
        }
        if found {
            BreachResult::Breached { count }
        } else {
            BreachResult::NotBreached
        }
    }

    /// Returns the number of entries in this response.
    #[must_use]
    #[inline]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if this response contains no entries.
    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// ---------------------------------------------------------------------------
// HibpError
// ---------------------------------------------------------------------------

/// The kind of HIBP parsing error that occurred.
///
/// Private — callers inspect errors through [`HibpError`]'s `Display`
/// and `std::error::Error` implementations.
#[derive(Debug, Clone, PartialEq, Eq)]
enum HibpErrorKind {
    /// A response line did not contain the expected `SUFFIX:COUNT` format.
    MalformedLine,
    /// A suffix was not a valid 35-character uppercase hex string.
    InvalidSuffix,
    /// A count value could not be parsed as a `u64`.
    InvalidCount,
    /// The response body contained no valid entries.
    EmptyResponse,
}

/// Error returned when parsing a HIBP range API response fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HibpError {
    kind: HibpErrorKind,
}

impl HibpError {
    const fn new(kind: HibpErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for HibpError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            HibpErrorKind::MalformedLine => f.write_str("hibp: malformed response line"),
            HibpErrorKind::InvalidSuffix => f.write_str("hibp: invalid hash suffix"),
            HibpErrorKind::InvalidCount => f.write_str("hibp: invalid breach count"),
            HibpErrorKind::EmptyResponse => f.write_str("hibp: empty response body"),
        }
    }
}

impl std::error::Error for HibpError {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- hibp_sha1_hex ---

    #[test]
    fn sha1_hex_of_password() {
        assert_eq!(
            hibp_sha1_hex("password"),
            "5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8",
        );
    }

    // --- HibpPrefix ---

    #[test]
    fn prefix_from_password() {
        let prefix = HibpPrefix::from_password("password");
        assert_eq!(prefix.as_str(), "5BAA6");
    }

    #[test]
    fn prefix_suffix_from_password() {
        let prefix = HibpPrefix::from_password("password");
        assert_eq!(prefix.suffix(), "1E4C9B93F3F0682250B6CF8331B7EE68FD8");
    }

    #[test]
    fn prefix_full_hash_from_password() {
        let prefix = HibpPrefix::from_password("password");
        assert_eq!(
            prefix.full_hash(),
            "5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8",
        );
    }

    // --- HibpResponse::parse ---

    #[test]
    fn parse_valid_response_lf() {
        let body = "1E4C9B93F3F0682250B6CF8331B7EE68FD8:3861493\n\
                     0018A45C4D1DEF81644B54AB7F969B88D65:1\n";
        let resp = HibpResponse::parse(body).unwrap();
        assert_eq!(resp.len(), 2);
        assert!(!resp.is_empty());
    }

    #[test]
    fn parse_valid_response_crlf() {
        let body = "1E4C9B93F3F0682250B6CF8331B7EE68FD8:3861493\r\n\
                     0018A45C4D1DEF81644B54AB7F969B88D65:1\r\n";
        let resp = HibpResponse::parse(body).unwrap();
        assert_eq!(resp.len(), 2);
    }

    #[test]
    fn check_breached_password() {
        let body = "1E4C9B93F3F0682250B6CF8331B7EE68FD8:3861493\n\
                     0018A45C4D1DEF81644B54AB7F969B88D65:1\n";
        let resp = HibpResponse::parse(body).unwrap();
        let result = resp.check_password("password");
        assert!(result.is_breached());
        assert_eq!(result.count(), 3_861_493);
    }

    #[test]
    fn check_non_breached_password() {
        // Response does not contain the suffix for "password".
        let body = "0018A45C4D1DEF81644B54AB7F969B88D65:1\n\
                     AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1:5\n";
        let resp = HibpResponse::parse(body).unwrap();
        let result = resp.check_password("password");
        assert!(!result.is_breached());
        assert_eq!(result.count(), 0);
    }

    #[test]
    fn check_prefix_breached() {
        let body = "1E4C9B93F3F0682250B6CF8331B7EE68FD8:3861493\n";
        let resp = HibpResponse::parse(body).unwrap();
        let prefix = HibpPrefix::from_password("password");
        let result = resp.check_prefix(&prefix);
        assert!(result.is_breached());
        assert_eq!(result.count(), 3_861_493);
    }

    // --- Parse error cases ---

    #[test]
    fn parse_rejects_empty_body() {
        let err = HibpResponse::parse("").unwrap_err();
        assert_eq!(err, HibpError::new(HibpErrorKind::EmptyResponse));
    }

    #[test]
    fn parse_rejects_whitespace_only() {
        let err = HibpResponse::parse("  \n  \n").unwrap_err();
        assert_eq!(err, HibpError::new(HibpErrorKind::EmptyResponse));
    }

    #[test]
    fn parse_rejects_malformed_line_no_colon() {
        let err = HibpResponse::parse("1E4C9B93F3F0682250B6CF8331B7EE68FD8\n").unwrap_err();
        assert_eq!(err, HibpError::new(HibpErrorKind::MalformedLine));
    }

    #[test]
    fn parse_rejects_wrong_suffix_length() {
        // Suffix is too short (34 chars instead of 35).
        let err = HibpResponse::parse("1E4C9B93F3F0682250B6CF8331B7EE68FD:1\n").unwrap_err();
        assert_eq!(err, HibpError::new(HibpErrorKind::InvalidSuffix));
    }

    #[test]
    fn parse_rejects_lowercase_suffix() {
        let err = HibpResponse::parse("1e4c9b93f3f0682250b6cf8331b7ee68fd8:1\n").unwrap_err();
        assert_eq!(err, HibpError::new(HibpErrorKind::InvalidSuffix));
    }

    #[test]
    fn parse_rejects_invalid_count() {
        let err = HibpResponse::parse("1E4C9B93F3F0682250B6CF8331B7EE68FD8:abc\n").unwrap_err();
        assert_eq!(err, HibpError::new(HibpErrorKind::InvalidCount));
    }

    // --- Error Display ---

    #[test]
    fn error_display_messages_start_with_hibp() {
        let cases = [
            (
                HibpErrorKind::MalformedLine,
                "hibp: malformed response line",
            ),
            (HibpErrorKind::InvalidSuffix, "hibp: invalid hash suffix"),
            (HibpErrorKind::InvalidCount, "hibp: invalid breach count"),
            (HibpErrorKind::EmptyResponse, "hibp: empty response body"),
        ];
        for (kind, expected) in &cases {
            let err = HibpError::new(kind.clone());
            let msg = err.to_string();
            assert!(
                msg.starts_with("hibp:"),
                "expected Display to start with 'hibp:', got: {msg}",
            );
            assert_eq!(&msg, expected);
        }
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(HibpError::new(HibpErrorKind::MalformedLine));
        assert!(err.source().is_none());
        let _ = err.to_string();
    }

    // --- BreachResult ---

    #[test]
    fn breach_result_not_breached() {
        let r = BreachResult::NotBreached;
        assert!(!r.is_breached());
        assert_eq!(r.count(), 0);
    }

    #[test]
    fn breach_result_breached() {
        let r = BreachResult::Breached { count: 42 };
        assert!(r.is_breached());
        assert_eq!(r.count(), 42);
    }
}