Skip to main content

aurelin_framework/auth/
compromised_password.rs

1use std::time::Duration;
2
3use reqwest::Client;
4use sha1::{Digest, Sha1};
5
6use crate::http::install_tls_provider;
7
8const HIBP_RANGE_ENDPOINT: &str = "https://api.pwnedpasswords.com/range";
9
10#[derive(Clone, Debug)]
11pub struct CompromisedPasswordChecker {
12    client: Client,
13    endpoint: String,
14}
15
16impl Default for CompromisedPasswordChecker {
17    fn default() -> Self {
18        Self::for_endpoint(HIBP_RANGE_ENDPOINT)
19    }
20}
21
22impl CompromisedPasswordChecker {
23    pub fn for_endpoint(endpoint: impl Into<String>) -> Self {
24        install_tls_provider();
25        Self { client: Client::new(), endpoint: endpoint.into() }
26    }
27
28    pub async fn is_compromised(&self, password: &str) -> Result<bool, reqwest::Error> {
29        let digest = Sha1::digest(password.as_bytes());
30        let mut hash = String::with_capacity(digest.len() * 2);
31        for byte in digest {
32            const HEX: &[u8; 16] = b"0123456789ABCDEF";
33            hash.push(char::from(HEX[usize::from(byte >> 4)]));
34            hash.push(char::from(HEX[usize::from(byte & 0x0f)]));
35        }
36        let (prefix, suffix) = hash.split_at(5);
37        let response = self
38            .client
39            .get(format!("{}/{prefix}", self.endpoint.trim_end_matches('/')))
40            .header("Add-Padding", "true")
41            .timeout(Duration::from_secs(30))
42            .send()
43            .await?
44            .error_for_status()?
45            .text()
46            .await?;
47
48        Ok(response.lines().any(|line| {
49            let Some((candidate, count)) = line.trim().split_once(':') else {
50                return false;
51            };
52            candidate.eq_ignore_ascii_case(suffix) && count.trim().parse::<u64>().is_ok_and(|count| count > 0)
53        }))
54    }
55}