1use std::{fmt, num::NonZeroUsize};
4
5static PASSWORD_VERIFICATION: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
6
7use argon2::password_hash::rand_core::OsRng;
8use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
9use argon2::{Algorithm, Argon2, Params, Version};
10use getrandom::fill as fill_random;
11use zeroize::Zeroizing;
12
13#[derive(Clone, PartialEq, Eq)]
15pub struct BootstrapAccount {
16 email: String,
17 full_name: String,
18 password: Zeroizing<String>,
19}
20
21impl BootstrapAccount {
22 pub fn required_from_env() -> Result<Self, BootstrapAccountError> {
29 Self::from_required_values(
30 read_bootstrap_value("BOOTSTRAP_EMAIL")?,
31 read_bootstrap_value("BOOTSTRAP_PASSWORD")?,
32 read_bootstrap_value("BOOTSTRAP_FULL_NAME")?,
33 )
34 }
35
36 pub fn optional_from_env() -> Result<Option<Self>, BootstrapAccountError> {
46 Self::from_optional_values(
47 read_bootstrap_value("BOOTSTRAP_EMAIL")?,
48 read_bootstrap_value("BOOTSTRAP_PASSWORD")?,
49 read_bootstrap_value("BOOTSTRAP_FULL_NAME")?,
50 )
51 }
52
53 pub fn from_required_values(
60 email: Option<String>,
61 password: Option<String>,
62 full_name: Option<String>,
63 ) -> Result<Self, BootstrapAccountError> {
64 Self::from_optional_values(email, password, full_name)?
65 .ok_or(BootstrapAccountError::Missing)
66 }
67
68 pub fn from_optional_values(
75 email: Option<String>,
76 password: Option<String>,
77 full_name: Option<String>,
78 ) -> Result<Option<Self>, BootstrapAccountError> {
79 let email = normalize_bootstrap_value(email);
80 let password = normalize_bootstrap_value(password);
81 let full_name = normalize_bootstrap_value(full_name);
82
83 match (email, password, full_name) {
84 (None, None, None) => Ok(None),
85 (Some(email), Some(password), Some(full_name)) => Ok(Some(Self {
86 email,
87 full_name,
88 password: Zeroizing::new(password),
89 })),
90 _ => Err(BootstrapAccountError::Incomplete),
91 }
92 }
93
94 #[must_use]
96 pub fn email(&self) -> &str {
97 self.email.as_str()
98 }
99
100 #[must_use]
102 pub fn full_name(&self) -> &str {
103 self.full_name.as_str()
104 }
105
106 #[must_use]
108 pub fn password(&self) -> &str {
109 self.password.as_str()
110 }
111}
112
113impl fmt::Debug for BootstrapAccount {
114 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
115 formatter
116 .debug_struct("BootstrapAccount")
117 .field("email", &self.email)
118 .field("full_name", &self.full_name)
119 .field("password", &"[REDACTED]")
120 .finish()
121 }
122}
123
124#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum BootstrapAccountError {
128 #[error("BOOTSTRAP_EMAIL, BOOTSTRAP_FULL_NAME and BOOTSTRAP_PASSWORD must all be set")]
130 Missing,
131 #[error(
133 "BOOTSTRAP_EMAIL, BOOTSTRAP_FULL_NAME and BOOTSTRAP_PASSWORD must either all be set or all be omitted"
134 )]
135 Incomplete,
136 #[error("bootstrap environment variable {key} contains invalid Unicode")]
138 InvalidUnicode {
139 key: &'static str,
141 },
142}
143
144fn read_bootstrap_value(key: &'static str) -> Result<Option<String>, BootstrapAccountError> {
145 ch_config::environment::var_os(key)
146 .map(|value| {
147 value
148 .into_string()
149 .map_err(|_| BootstrapAccountError::InvalidUnicode { key })
150 })
151 .transpose()
152}
153
154fn normalize_bootstrap_value(value: Option<String>) -> Option<String> {
155 value
156 .map(|value| value.trim().to_owned())
157 .filter(|value| !value.is_empty())
158}
159
160pub const ARGON2_MEMORY_COST_KIB: u32 = 19_456;
162pub const ARGON2_TIME_COST: u32 = 2;
164pub const ARGON2_PARALLELISM: u32 = 1;
166
167#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
169#[non_exhaustive]
170pub enum PasswordHashError {
171 #[error("invalid Argon2 password policy")]
173 InvalidPolicy,
174 #[error("failed to hash password")]
176 Hashing,
177 #[error("stored password hash is invalid")]
179 InvalidHash,
180 #[error("password verification task failed")]
182 Execution,
183}
184
185#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187pub struct PasswordVerification {
188 pub verified: bool,
190 pub needs_rehash: bool,
192}
193
194pub fn hash_password(password: &str) -> Result<String, PasswordHashError> {
196 let salt = SaltString::generate(&mut OsRng);
197 password_hasher()?
198 .hash_password(password.as_bytes(), &salt)
199 .map(|hash| hash.to_string())
200 .map_err(|_| PasswordHashError::Hashing)
201}
202
203pub fn validate_password_hash(stored_hash: &str) -> Result<(), PasswordHashError> {
207 let parsed = PasswordHash::new(stored_hash).map_err(|_| PasswordHashError::InvalidHash)?;
208 if !uses_current_policy(&parsed)
209 || parsed.salt.is_none()
210 || parsed.hash.is_none_or(|value| value.len() != 32)
211 {
212 return Err(PasswordHashError::InvalidHash);
213 }
214 Ok(())
215}
216
217pub fn verify_password_detailed(
219 password: &str,
220 stored_hash: &str,
221) -> Result<PasswordVerification, PasswordHashError> {
222 let parsed = PasswordHash::new(stored_hash).map_err(|_| PasswordHashError::InvalidHash)?;
223 let verified = password_hasher()?
224 .verify_password(password.as_bytes(), &parsed)
225 .is_ok();
226
227 Ok(PasswordVerification {
228 verified,
229 needs_rehash: verified && !uses_current_policy(&parsed),
230 })
231}
232
233pub async fn verify_password(password: &str, stored_hash: &str) -> Result<bool, PasswordHashError> {
237 let password = Zeroizing::new(password.to_owned());
238 let stored_hash = stored_hash.to_owned();
239 let permit = PASSWORD_VERIFICATION
240 .acquire()
241 .await
242 .expect("the private password semaphore is never closed");
243 tokio::task::spawn_blocking(move || {
244 let _permit = permit;
245 verify_password_detailed(&password, &stored_hash).map(|result| result.verified)
246 })
247 .await
248 .map_err(|_| PasswordHashError::Execution)?
249}
250
251pub fn hash_backup_code(code: &str) -> Result<String, PasswordHashError> {
253 hash_password(code)
254}
255
256pub fn verify_backup_code(code: &str, hash: &str) -> Result<bool, PasswordHashError> {
258 verify_password_detailed(code, hash).map(|result| result.verified)
259}
260
261#[derive(Clone, Copy, Debug)]
263pub struct RandomCodeSpec<'a> {
264 length: NonZeroUsize,
265 alphabet: &'a str,
266}
267
268impl<'a> RandomCodeSpec<'a> {
269 pub fn new(length: usize, alphabet: &'a str) -> Result<Self, RandomCodeSpecError> {
271 let length = NonZeroUsize::new(length).ok_or(RandomCodeSpecError::EmptyCode)?;
272 let alphabet_bytes = alphabet.as_bytes();
273
274 if alphabet_bytes.is_empty() {
275 return Err(RandomCodeSpecError::EmptyAlphabet);
276 }
277 if alphabet_bytes.len() > usize::from(u8::MAX) + 1 {
278 return Err(RandomCodeSpecError::AlphabetTooLarge);
279 }
280 if !alphabet_bytes.is_ascii() {
281 return Err(RandomCodeSpecError::NonAsciiAlphabet);
282 }
283 if alphabet_bytes
284 .iter()
285 .enumerate()
286 .any(|(index, byte)| alphabet_bytes[..index].contains(byte))
287 {
288 return Err(RandomCodeSpecError::DuplicateAlphabetCharacter);
289 }
290
291 Ok(Self { length, alphabet })
292 }
293
294 #[must_use]
296 pub const fn length(self) -> NonZeroUsize {
297 self.length
298 }
299
300 #[must_use]
302 pub fn alphabet(self) -> &'a str {
303 self.alphabet
304 }
305}
306
307#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
309#[non_exhaustive]
310pub enum RandomCodeSpecError {
311 #[error("random code length must be greater than zero")]
313 EmptyCode,
314 #[error("random code alphabet must not be empty")]
316 EmptyAlphabet,
317 #[error("random code alphabet must contain at most 256 characters")]
319 AlphabetTooLarge,
320 #[error("random code alphabet must contain ASCII characters only")]
322 NonAsciiAlphabet,
323 #[error("random code alphabet must not contain duplicate characters")]
325 DuplicateAlphabetCharacter,
326}
327
328#[derive(Debug, thiserror::Error)]
330#[error("failed to generate a random code")]
331pub struct RandomCodeGenerationError(#[source] getrandom::Error);
332
333pub fn generate_random_code(spec: RandomCodeSpec<'_>) -> Result<String, RandomCodeGenerationError> {
335 let mut code = String::with_capacity(spec.length.get());
336 let mut random = [0_u8; 64];
337 let alphabet = spec.alphabet.as_bytes();
338 let acceptance_bound = (usize::from(u8::MAX) + 1) / alphabet.len() * alphabet.len();
339
340 while code.len() < spec.length.get() {
341 fill_random(&mut random).map_err(RandomCodeGenerationError)?;
342 for byte in random {
343 if usize::from(byte) >= acceptance_bound {
344 continue;
345 }
346
347 code.push(char::from(alphabet[usize::from(byte) % alphabet.len()]));
348 if code.len() == spec.length.get() {
349 break;
350 }
351 }
352 }
353
354 Ok(code)
355}
356
357fn password_hasher() -> Result<Argon2<'static>, PasswordHashError> {
358 let params = Params::new(
359 ARGON2_MEMORY_COST_KIB,
360 ARGON2_TIME_COST,
361 ARGON2_PARALLELISM,
362 None,
363 )
364 .map_err(|_| PasswordHashError::InvalidPolicy)?;
365 Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
366}
367
368fn uses_current_policy(hash: &PasswordHash<'_>) -> bool {
369 hash.algorithm.as_str() == "argon2id"
370 && hash.version == Some(Version::V0x13 as u32)
371 && hash.params.get_decimal("m") == Some(ARGON2_MEMORY_COST_KIB)
372 && hash.params.get_decimal("t") == Some(ARGON2_TIME_COST)
373 && hash.params.get_decimal("p") == Some(ARGON2_PARALLELISM)
374}
375
376#[cfg(test)]
377mod tests {
378 use super::{
379 BootstrapAccount, BootstrapAccountError, PasswordHashError, RandomCodeSpec,
380 RandomCodeSpecError, generate_random_code, hash_backup_code, hash_password,
381 validate_password_hash, verify_backup_code, verify_password, verify_password_detailed,
382 };
383
384 #[tokio::test(flavor = "current_thread")]
385 async fn password_checks_yield_and_keep_typed_failures() {
386 let hash = super::hash_password("correct password").expect("fixture hash");
387 let progressed = std::sync::atomic::AtomicBool::new(false);
388 tokio::join!(
389 async {
390 assert!(
391 super::verify_password("correct password", &hash)
392 .await
393 .expect("valid hash")
394 );
395 assert!(
396 progressed.load(std::sync::atomic::Ordering::SeqCst),
397 "executor must progress during password verification"
398 );
399 },
400 async {
401 tokio::task::yield_now().await;
402 progressed.store(true, std::sync::atomic::Ordering::SeqCst);
403 },
404 );
405 assert!(
406 !super::verify_password("wrong password", &hash)
407 .await
408 .expect("valid hash")
409 );
410 let error = super::verify_password("private-password", "private-broken-hash")
411 .await
412 .expect_err("malformed hash");
413 assert!(!format!("{error:?} {error}").contains("private-"));
414 }
415
416 #[test]
417 fn bootstrap_account_normalizes_complete_values() {
418 let account = BootstrapAccount::from_required_values(
419 Some(" admin@example.com ".to_owned()),
420 Some(" correct horse battery staple ".to_owned()),
421 Some(" Administrator ".to_owned()),
422 )
423 .expect("complete bootstrap values should be accepted");
424
425 assert_eq!(account.email(), "admin@example.com");
426 assert_eq!(account.full_name(), "Administrator");
427 assert_eq!(account.password(), "correct horse battery staple");
428 assert!(!format!("{account:?}").contains("correct horse"));
429 }
430
431 #[test]
432 fn required_bootstrap_account_rejects_absent_values() {
433 assert_eq!(
434 BootstrapAccount::from_required_values(None, None, None),
435 Err(BootstrapAccountError::Missing),
436 );
437 }
438
439 #[test]
440 fn optional_bootstrap_account_accepts_absence_and_rejects_partial_values() {
441 assert_eq!(
442 BootstrapAccount::from_optional_values(None, None, None),
443 Ok(None),
444 );
445 assert_eq!(
446 BootstrapAccount::from_optional_values(
447 Some("admin@example.com".to_owned()),
448 None,
449 Some("Administrator".to_owned()),
450 ),
451 Err(BootstrapAccountError::Incomplete),
452 );
453 }
454
455 #[test]
456 fn bootstrap_errors_are_safe_for_application_boundaries() {
457 fn assert_error<E: std::error::Error + Send + Sync + 'static>() {}
458
459 assert_error::<BootstrapAccountError>();
460 let error = BootstrapAccountError::InvalidUnicode {
461 key: "BOOTSTRAP_PASSWORD",
462 };
463 assert_eq!(
464 error.to_string(),
465 "bootstrap environment variable BOOTSTRAP_PASSWORD contains invalid Unicode"
466 );
467 }
468
469 #[test]
470 fn received_password_hashes_require_complete_bounded_argon2id_policy() {
471 let hash = hash_password("device-password").unwrap();
472 assert_eq!(validate_password_hash(&hash), Ok(()));
473 for invalid in [
474 "",
475 "5f4dcc3b5aa765d61d8327deb882cf99",
476 "$argon2id$v=19$m=19456,t=2,p=1",
477 &hash.replace("m=19456", "m=2147483647"),
478 &hash.replace("argon2id", "argon2i"),
479 &hash.replace("t=2", "t=999999"),
480 &hash.replace("v=19", "v=16"),
481 ] {
482 assert_eq!(
483 validate_password_hash(invalid),
484 Err(PasswordHashError::InvalidHash)
485 );
486 }
487 }
488
489 #[tokio::test]
490 async fn hashes_and_verifies_passwords() {
491 let hash = hash_password("correct-horse").expect("hash should succeed");
492 assert!(
493 verify_password("correct-horse", &hash)
494 .await
495 .expect("valid hash")
496 );
497 assert!(
498 !verify_password("wrong-battery", &hash)
499 .await
500 .expect("valid hash")
501 );
502
503 let result =
504 verify_password_detailed("correct-horse", &hash).expect("generated hash should parse");
505 assert!(result.verified);
506 assert!(!result.needs_rehash);
507 }
508
509 #[tokio::test]
510 async fn malformed_hashes_return_a_typed_error() {
511 assert_eq!(
512 verify_password_detailed("password", "not-a-phc-string"),
513 Err(PasswordHashError::InvalidHash)
514 );
515 assert_eq!(
516 verify_password("password", "not-a-phc-string").await,
517 Err(PasswordHashError::InvalidHash)
518 );
519 }
520
521 #[test]
522 fn hashes_and_verifies_backup_codes() {
523 let hash = hash_backup_code("CODE-ONE").expect("hashing should succeed");
524 assert!(verify_backup_code("CODE-ONE", &hash).expect("hash is valid"));
525 assert!(!verify_backup_code("CODE-TWO", &hash).expect("hash is valid"));
526 }
527
528 #[test]
529 fn random_codes_follow_the_callers_format() {
530 let spec = RandomCodeSpec::new(24, "ABC123").expect("format should be valid");
531 let code = generate_random_code(spec).expect("code should generate");
532
533 assert_eq!(code.len(), 24);
534 assert!(code.bytes().all(|byte| b"ABC123".contains(&byte)));
535 }
536
537 #[test]
538 fn random_code_formats_reject_ambiguous_alphabets() {
539 assert!(matches!(
540 RandomCodeSpec::new(8, "AABC"),
541 Err(RandomCodeSpecError::DuplicateAlphabetCharacter)
542 ));
543 assert!(matches!(
544 RandomCodeSpec::new(0, "ABC"),
545 Err(RandomCodeSpecError::EmptyCode)
546 ));
547 }
548}