ironflow-auth 2.4.75

Authentication library for ironflow — JWT, password hashing, extractors
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
//! Argon2id password hashing, verification and strength policy.

use std::collections::HashSet;
use std::sync::LazyLock;

use argon2::password_hash::SaltString;
use argon2::password_hash::rand_core::OsRng;
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use thiserror::Error;

use crate::error::AuthError;

/// Minimum password length accepted by [`check_strength`], in characters.
pub const MIN_PASSWORD_LEN: usize = 12;

/// Maximum password length accepted by [`check_strength`], in characters.
pub const MAX_PASSWORD_LEN: usize = 128;

/// Fewest distinct characters a password may contain.
const MIN_DISTINCT_CHARS: usize = 5;

/// Shortest email or username fragment searched for inside a password.
/// Shorter fragments ("al", "x") would reject unrelated passwords.
const MIN_PERSONAL_FRAGMENT_LEN: usize = 3;

/// The SecLists `10k-most-common` list (MIT, see `common_passwords.LICENSE`).
static COMMON_PASSWORDS: LazyLock<HashSet<String>> = LazyLock::new(|| {
    include_str!("common_passwords.txt")
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(str::to_lowercase)
        .collect()
});

/// Throwaway hash [`verify_dummy`] checks passwords against.
///
/// Built with [`hash`], hence the same Argon2 parameters as real account
/// hashes: a verification against it costs exactly what a real one costs.
static DUMMY_HASH: LazyLock<Result<String, AuthError>> =
    LazyLock::new(|| hash("ironflow-dummy-password-for-unknown-accounts"));

/// Why a password was refused by [`check_strength`].
///
/// The messages are written for the person choosing the password.
///
/// # Examples
///
/// ```
/// use ironflow_auth::password::{PasswordPolicyError, check_strength};
///
/// let err = check_strength("short", &[]).unwrap_err();
/// assert_eq!(err, PasswordPolicyError::TooShort { min: 12 });
/// assert_eq!(err.to_string(), "password must be at least 12 characters");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum PasswordPolicyError {
    /// Fewer than [`MIN_PASSWORD_LEN`] characters.
    #[error("password must be at least {min} characters")]
    TooShort {
        /// The minimum length, in characters.
        min: usize,
    },
    /// More than [`MAX_PASSWORD_LEN`] characters.
    #[error("password must be at most {max} characters")]
    TooLong {
        /// The maximum length, in characters.
        max: usize,
    },
    /// The password contains the email address, its local part, or the username.
    #[error("password must not contain your email address or username")]
    ContainsPersonalInfo,
    /// The password, or the word left once leading and trailing digits and
    /// symbols are removed, is a commonly used password.
    #[error("password is too common, choose a less predictable one")]
    TooCommon,
    /// The password repeats a short pattern or uses too few distinct characters.
    #[error("password is too repetitive, use more varied characters")]
    TooRepetitive,
}

/// Hash a plaintext password using Argon2id.
///
/// # Errors
///
/// Returns [`AuthError::PasswordHash`] if hashing fails.
///
/// # Examples
///
/// ```
/// use ironflow_auth::password;
///
/// let hash = password::hash("hunter2").unwrap();
/// assert!(hash.starts_with("$argon2id$"));
/// ```
pub fn hash(password: &str) -> Result<String, AuthError> {
    let salt = SaltString::generate(&mut OsRng);
    let argon2 = Argon2::default();
    let hash = argon2
        .hash_password(password.as_bytes(), &salt)
        .map_err(|_| AuthError::PasswordHash)?;
    Ok(hash.to_string())
}

/// Verify a plaintext password against an Argon2id hash.
///
/// # Errors
///
/// Returns [`AuthError::PasswordHash`] if the hash is malformed.
///
/// # Examples
///
/// ```
/// use ironflow_auth::password;
///
/// let hash = password::hash("correct").unwrap();
/// assert!(password::verify("correct", &hash).unwrap());
/// assert!(!password::verify("wrong", &hash).unwrap());
/// ```
pub fn verify(password: &str, hash: &str) -> Result<bool, AuthError> {
    let parsed_hash = PasswordHash::new(hash).map_err(|_| AuthError::PasswordHash)?;
    let argon2 = Argon2::default();
    Ok(argon2
        .verify_password(password.as_bytes(), &parsed_hash)
        .is_ok())
}

/// Run one Argon2id verification against a throwaway hash, for a request
/// whose account does not exist, so it takes as long as one whose password is wrong.
///
/// The result of the comparison is discarded: only the time spent matters.
///
/// # Errors
///
/// Returns [`AuthError::PasswordHash`] if the throwaway hash could not be built.
///
/// # Examples
///
/// ```
/// use ironflow_auth::error::AuthError;
/// use ironflow_auth::password;
///
/// # fn example() -> Result<(), AuthError> {
/// password::verify_dummy("whatever the caller sent")?;
/// # Ok(())
/// # }
/// ```
pub fn verify_dummy(password: &str) -> Result<(), AuthError> {
    let dummy = DUMMY_HASH.as_ref().map_err(|_| AuthError::PasswordHash)?;
    verify(password, dummy).map(|_| ())
}

/// Check a new password against the strength policy.
///
/// `personal` holds what the account is known by (email address, username).
/// The checks, in order:
///
/// 1. between [`MIN_PASSWORD_LEN`] and [`MAX_PASSWORD_LEN`] characters
///    (Unicode scalar values, not bytes);
/// 2. does not contain, case-insensitively, an entry of `personal`, nor the
///    local part of an email address in it (fragments under 3 characters
///    are ignored);
/// 3. neither the password nor its core (leading and trailing digits and
///    symbols removed, so `Password2024!!` gives `password`) is a common
///    password;
/// 4. not a short pattern repeated (`passwordpassword`), and at least five
///    distinct characters.
///
/// Call it wherever a password is chosen. Sign-in never calls it: existing
/// passwords keep working.
///
/// # Errors
///
/// Returns the first [`PasswordPolicyError`] the password violates.
///
/// # Examples
///
/// ```
/// use ironflow_auth::password::{PasswordPolicyError, check_strength};
///
/// let personal = ["alice@ironflow.dev", "alice"];
/// assert!(check_strength("correct horse battery staple", &personal).is_ok());
/// assert_eq!(
///     check_strength("alice@ironflow.dev", &personal),
///     Err(PasswordPolicyError::ContainsPersonalInfo),
/// );
/// assert_eq!(
///     check_strength("Password2024!!", &personal),
///     Err(PasswordPolicyError::TooCommon),
/// );
/// ```
pub fn check_strength(password: &str, personal: &[&str]) -> Result<(), PasswordPolicyError> {
    let len = password.chars().count();
    if len < MIN_PASSWORD_LEN {
        return Err(PasswordPolicyError::TooShort {
            min: MIN_PASSWORD_LEN,
        });
    }
    if len > MAX_PASSWORD_LEN {
        return Err(PasswordPolicyError::TooLong {
            max: MAX_PASSWORD_LEN,
        });
    }

    let lowered = password.to_lowercase();

    if personal_fragments(personal).any(|fragment| lowered.contains(&fragment)) {
        return Err(PasswordPolicyError::ContainsPersonalInfo);
    }

    let core = lowered.trim_matches(|c: char| !c.is_alphabetic());
    if COMMON_PASSWORDS.contains(&lowered) || COMMON_PASSWORDS.contains(core) {
        return Err(PasswordPolicyError::TooCommon);
    }

    let distinct: HashSet<char> = lowered.chars().collect();
    if distinct.len() < MIN_DISTINCT_CHARS || is_repeated_pattern(&lowered) {
        return Err(PasswordPolicyError::TooRepetitive);
    }

    Ok(())
}

/// Lowercased fragments of `personal` a password must not contain: each
/// entry, plus the local part of the ones that are email addresses.
fn personal_fragments<'a>(personal: &'a [&'a str]) -> impl Iterator<Item = String> + 'a {
    personal
        .iter()
        .flat_map(|entry| {
            let entry = entry.trim();
            let local = entry.split_once('@').map(|(local, _)| local);
            [Some(entry), local]
        })
        .flatten()
        .filter(|fragment| fragment.chars().count() >= MIN_PERSONAL_FRAGMENT_LEN)
        .map(str::to_lowercase)
}

/// Whether `s` is a shorter chunk repeated end to end (`abcabc`).
fn is_repeated_pattern(s: &str) -> bool {
    let chars: Vec<char> = s.chars().collect();
    (1..=chars.len() / 2).any(|period| {
        chars.len().is_multiple_of(period)
            && chars.chunks(period).all(|chunk| chunk == &chars[..period])
    })
}

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

    const PERSONAL: [&str; 2] = ["alice@ironflow.dev", "alice"];

    #[test]
    fn strong_password_is_accepted() {
        assert_eq!(
            check_strength("correct horse battery staple", &PERSONAL),
            Ok(())
        );
        assert_eq!(check_strength("Tq9!vR2#mZ7$", &PERSONAL), Ok(()));
    }

    #[test]
    fn eleven_characters_is_too_short() {
        assert_eq!(
            check_strength("Tq9!vR2#mZ7", &[]),
            Err(PasswordPolicyError::TooShort { min: 12 })
        );
    }

    #[test]
    fn empty_password_is_too_short() {
        assert_eq!(
            check_strength("", &[]),
            Err(PasswordPolicyError::TooShort { min: 12 })
        );
    }

    #[test]
    fn length_counts_characters_not_bytes() {
        // 11 characters, 22 bytes: still too short.
        assert_eq!(
            check_strength("éàçùêâîôûëï", &[]),
            Err(PasswordPolicyError::TooShort { min: 12 })
        );
        // 12 characters, all distinct.
        assert_eq!(check_strength("éàçùêâîôûëïü", &[]), Ok(()));
    }

    #[test]
    fn length_bounds_are_inclusive() {
        let max: String = "Tq9!vR2#mZ7$".chars().cycle().take(128).collect();
        let over: String = "Tq9!vR2#mZ7$".chars().cycle().take(129).collect();
        // 128 is not a multiple of 12, so the cycle is not an exact repetition.
        assert_eq!(check_strength(&max, &[]), Ok(()));
        assert_eq!(
            check_strength(&over, &[]),
            Err(PasswordPolicyError::TooLong { max: 128 })
        );
    }

    #[test]
    fn password_equal_to_email_is_refused() {
        assert_eq!(
            check_strength("alice@ironflow.dev", &PERSONAL),
            Err(PasswordPolicyError::ContainsPersonalInfo)
        );
    }

    #[test]
    fn password_containing_username_is_refused_case_insensitively() {
        assert_eq!(
            check_strength("my-ALICE-secret-42", &PERSONAL),
            Err(PasswordPolicyError::ContainsPersonalInfo)
        );
    }

    #[test]
    fn password_containing_email_local_part_is_refused() {
        assert_eq!(
            check_strength("xx-jdoe.ops-2024", &["jdoe.ops@corp.example"]),
            Err(PasswordPolicyError::ContainsPersonalInfo)
        );
    }

    #[test]
    fn short_personal_fragments_are_ignored() {
        assert_eq!(check_strength("Tq9!vR2#mZ7$al", &["al@x.io", "al"]), Ok(()));
    }

    #[test]
    fn common_password_is_refused() {
        // In the list and at least 12 characters long.
        assert_eq!(
            check_strength("Unbelievable", &[]),
            Err(PasswordPolicyError::TooCommon)
        );
    }

    #[test]
    fn common_word_padded_with_digits_and_symbols_is_refused() {
        assert_eq!(
            check_strength("Password2024!!", &[]),
            Err(PasswordPolicyError::TooCommon)
        );
        assert_eq!(
            check_strength("!!!Qwertyuiop1", &[]),
            Err(PasswordPolicyError::TooCommon)
        );
    }

    #[test]
    fn repeated_pattern_is_refused() {
        assert_eq!(
            check_strength("passwordpassword", &[]),
            Err(PasswordPolicyError::TooRepetitive)
        );
        assert_eq!(
            check_strength("Xk9#Xk9#Xk9#", &[]),
            Err(PasswordPolicyError::TooRepetitive)
        );
    }

    #[test]
    fn too_few_distinct_characters_is_refused() {
        assert_eq!(
            check_strength("aaaa1111bbbb", &[]),
            Err(PasswordPolicyError::TooRepetitive)
        );
    }

    #[test]
    fn hash_produces_argon2id() {
        let h = hash("password123").unwrap();
        assert!(h.starts_with("$argon2id$"));
    }

    #[test]
    fn verify_correct_password() {
        let h = hash("mypassword").unwrap();
        assert!(verify("mypassword", &h).unwrap());
    }

    #[test]
    fn verify_wrong_password() {
        let h = hash("mypassword").unwrap();
        assert!(!verify("wrongpassword", &h).unwrap());
    }

    #[test]
    fn different_hashes_for_same_password() {
        let h1 = hash("same").unwrap();
        let h2 = hash("same").unwrap();
        assert_ne!(h1, h2);
    }

    #[test]
    fn malformed_hash_returns_error() {
        assert!(verify("pw", "not-a-valid-hash").is_err());
    }

    #[test]
    fn verify_dummy_succeeds_for_any_password() {
        let long = "x".repeat(10_000);
        for password in [
            "",
            "mot de passe \u{e9}\u{fc} \u{5bc6}\u{7801}",
            long.as_str(),
        ] {
            assert!(verify_dummy(password).is_ok());
        }
    }
}