forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

password.rs167 lines, 6.4 KiBHistoryRawDownload
1//! Password hashing with argon2id, and the password policy.
2//!
3//! Hashes are PHC strings with a random salt. Hashing and verifying take hundreds of milliseconds
4//! by design, so the async wrappers move that work onto the blocking thread pool; a request task
5//! must never run argon2 inline.
6
7use argon2::Argon2;
8use argon2::password_hash::phc::PasswordHash;
9use argon2::password_hash::{PasswordHasher, PasswordVerifier};
10use tokio::sync::{Semaphore, SemaphorePermit};
11
12use crate::error::{Error, Result};
13
14/// Shortest accepted password, in characters. Length is the main defence against guessing, so it
15/// is set well above what people choose by habit.
16pub const MIN_PASSWORD_CHARS: usize = 10;
17
18/// Longest accepted password, in characters. Bounds the work an attacker can force argon2 to do
19/// per request.
20pub const MAX_PASSWORD_CHARS: usize = 256;
21
22/// Most argon2 operations running at once. Each one takes tens of megabytes, so a burst of requests
23/// queues here instead of starting one blocking thread and one hash per request.
24const HASH_PERMITS: usize = 4;
25
26/// The gate of every async hash and verify.
27static HASHING: Semaphore = Semaphore::const_new(HASH_PERMITS);
28
29/// True for a password longer than [`MAX_PASSWORD_CHARS`]. Such a password is never hashed or verified.
30fn too_long(pw: &str) -> bool {
31 pw.chars().count() > MAX_PASSWORD_CHARS
32}
33
34/// Shortest word of the name or email local part that a password may not contain, in characters.
35/// Shorter words are too common to forbid: a two-letter word would reject many good passwords.
36pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4;
37
38/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string. A
39/// password over [`MAX_PASSWORD_CHARS`] is refused before any hashing.
40pub fn hash_password(pw: &str) -> Result<String> {
41 if too_long(pw) {
42 return Err(Error::Invalid("the password is too long".into()));
43 }
44 Argon2::default()
45 .hash_password(pw.as_bytes())
46 .map(|h| h.to_string())
47 .map_err(|e| Error::Crypto(format!("argon2: {e}")))
48}
49
50/// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never
51/// a panic. A password over [`MAX_PASSWORD_CHARS`] gives false without any hashing.
52pub fn verify_password(pw: &str, hash: &str) -> bool {
53 if too_long(pw) {
54 return false;
55 }
56 let Ok(parsed) = PasswordHash::new(hash) else {
57 return false;
58 };
59 Argon2::default()
60 .verify_password(pw.as_bytes(), &parsed)
61 .is_ok()
62}
63
64/// Takes one of the [`HASH_PERMITS`] slots. Held until the blocking work ends.
65async fn gate() -> Result<SemaphorePermit<'static>> {
66 HASHING
67 .acquire()
68 .await
69 .map_err(|e| Error::Crypto(format!("hashing gate closed: {e}")))
70}
71
72/// [`hash_password`] on the blocking thread pool, behind the hashing gate.
73pub async fn hash_password_async(pw: String) -> Result<String> {
74 let _permit = gate().await?;
75 tokio::task::spawn_blocking(move || hash_password(&pw))
76 .await
77 .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))?
78}
79
80/// [`verify_password`] on the blocking thread pool, behind the hashing gate. An over-long password is
81/// answered without taking a slot.
82pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {
83 if too_long(&pw) {
84 return Ok(false);
85 }
86 let _permit = gate().await?;
87 tokio::task::spawn_blocking(move || verify_password(&pw, &hash))
88 .await
89 .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))
90}
91
92/// Why a new password is refused by [`check_policy`]. The web layer maps each reason to a
93/// translated message, so the reasons are kept apart from any text.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum PolicyViolation {
96 /// Fewer than [`MIN_PASSWORD_CHARS`] characters.
97 TooShort,
98 /// More than [`MAX_PASSWORD_CHARS`] characters.
99 TooLong,
100 /// Contains the email local part or a word of the name.
101 ContainsIdentity,
102}
103
104/// Checks a new password against the policy.
105///
106/// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least
107/// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared
108/// case-insensitively. The rule that the password differs from the current one needs the stored
109/// hash and is checked by the caller.
110pub fn check_policy(
111 password: &str,
112 email: &str,
113 name: &str,
114) -> std::result::Result<(), PolicyViolation> {
115 let chars = password.chars().count();
116 if chars < MIN_PASSWORD_CHARS {
117 return Err(PolicyViolation::TooShort);
118 }
119 if chars > MAX_PASSWORD_CHARS {
120 return Err(PolicyViolation::TooLong);
121 }
122
123 let lowered = password.to_lowercase();
124 let local_part = email.split('@').next().unwrap_or_default();
125 let forbidden = std::iter::once(local_part)
126 .chain(name.split(|c: char| !c.is_alphanumeric()))
127 .map(str::to_lowercase)
128 .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS);
129 for word in forbidden {
130 if lowered.contains(&word) {
131 return Err(PolicyViolation::ContainsIdentity);
132 }
133 }
134 Ok(())
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn hash_then_verify_accepts_only_the_same_password() {
143 let hash = hash_password("correct horse").unwrap();
144 assert!(hash.starts_with("$argon2id$"));
145 assert!(verify_password("correct horse", &hash));
146 assert!(!verify_password("wrong", &hash));
147 assert!(!verify_password("pw", "not a phc string"));
148 }
149
150 #[test]
151 fn policy_enforces_length_bounds() {
152 assert!(check_policy("short", "a@example.com", "Ada").is_err());
153 assert!(check_policy("nine-char", "a@example.com", "Ada").is_err());
154 assert!(check_policy("ten-chars!", "a@example.com", "Ada").is_ok());
155 let long = "x".repeat(MAX_PASSWORD_CHARS + 1);
156 assert!(check_policy(&long, "a@example.com", "Ada").is_err());
157 }
158
159 #[test]
160 fn policy_rejects_email_local_part_and_name_words_case_insensitively() {
161 let email = "tahinli@example.com";
162 assert!(check_policy("My-TAHINLI-pass", email, "Ada").is_err());
163 assert!(check_policy("correct Lovelace horse", email, "Ada Lovelace").is_err());
164 // Words under four characters do not count, so "Ada" alone does not block a password.
165 assert!(check_policy("my ada horse 1", email, "Ada").is_ok());
166 }
167}