use std::{fmt, num::NonZeroUsize};
static PASSWORD_VERIFICATION: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::{Algorithm, Argon2, Params, Version};
use getrandom::fill as fill_random;
use zeroize::Zeroizing;
#[derive(Clone, PartialEq, Eq)]
pub struct BootstrapAccount {
email: String,
full_name: String,
password: Zeroizing<String>,
}
impl BootstrapAccount {
pub fn required_from_env() -> Result<Self, BootstrapAccountError> {
Self::from_required_values(
read_bootstrap_value("BOOTSTRAP_EMAIL")?,
read_bootstrap_value("BOOTSTRAP_PASSWORD")?,
read_bootstrap_value("BOOTSTRAP_FULL_NAME")?,
)
}
pub fn optional_from_env() -> Result<Option<Self>, BootstrapAccountError> {
Self::from_optional_values(
read_bootstrap_value("BOOTSTRAP_EMAIL")?,
read_bootstrap_value("BOOTSTRAP_PASSWORD")?,
read_bootstrap_value("BOOTSTRAP_FULL_NAME")?,
)
}
pub fn from_required_values(
email: Option<String>,
password: Option<String>,
full_name: Option<String>,
) -> Result<Self, BootstrapAccountError> {
Self::from_optional_values(email, password, full_name)?
.ok_or(BootstrapAccountError::Missing)
}
pub fn from_optional_values(
email: Option<String>,
password: Option<String>,
full_name: Option<String>,
) -> Result<Option<Self>, BootstrapAccountError> {
let email = normalize_bootstrap_value(email);
let password = normalize_bootstrap_value(password);
let full_name = normalize_bootstrap_value(full_name);
match (email, password, full_name) {
(None, None, None) => Ok(None),
(Some(email), Some(password), Some(full_name)) => Ok(Some(Self {
email,
full_name,
password: Zeroizing::new(password),
})),
_ => Err(BootstrapAccountError::Incomplete),
}
}
#[must_use]
pub fn email(&self) -> &str {
self.email.as_str()
}
#[must_use]
pub fn full_name(&self) -> &str {
self.full_name.as_str()
}
#[must_use]
pub fn password(&self) -> &str {
self.password.as_str()
}
}
impl fmt::Debug for BootstrapAccount {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("BootstrapAccount")
.field("email", &self.email)
.field("full_name", &self.full_name)
.field("password", &"[REDACTED]")
.finish()
}
}
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum BootstrapAccountError {
#[error("BOOTSTRAP_EMAIL, BOOTSTRAP_FULL_NAME and BOOTSTRAP_PASSWORD must all be set")]
Missing,
#[error(
"BOOTSTRAP_EMAIL, BOOTSTRAP_FULL_NAME and BOOTSTRAP_PASSWORD must either all be set or all be omitted"
)]
Incomplete,
#[error("bootstrap environment variable {key} contains invalid Unicode")]
InvalidUnicode {
key: &'static str,
},
}
fn read_bootstrap_value(key: &'static str) -> Result<Option<String>, BootstrapAccountError> {
ch_config::environment::var_os(key)
.map(|value| {
value
.into_string()
.map_err(|_| BootstrapAccountError::InvalidUnicode { key })
})
.transpose()
}
fn normalize_bootstrap_value(value: Option<String>) -> Option<String> {
value
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
pub const ARGON2_MEMORY_COST_KIB: u32 = 19_456;
pub const ARGON2_TIME_COST: u32 = 2;
pub const ARGON2_PARALLELISM: u32 = 1;
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum PasswordHashError {
#[error("invalid Argon2 password policy")]
InvalidPolicy,
#[error("failed to hash password")]
Hashing,
#[error("stored password hash is invalid")]
InvalidHash,
#[error("password verification task failed")]
Execution,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PasswordVerification {
pub verified: bool,
pub needs_rehash: bool,
}
pub fn hash_password(password: &str) -> Result<String, PasswordHashError> {
let salt = SaltString::generate(&mut OsRng);
password_hasher()?
.hash_password(password.as_bytes(), &salt)
.map(|hash| hash.to_string())
.map_err(|_| PasswordHashError::Hashing)
}
pub fn validate_password_hash(stored_hash: &str) -> Result<(), PasswordHashError> {
let parsed = PasswordHash::new(stored_hash).map_err(|_| PasswordHashError::InvalidHash)?;
if !uses_current_policy(&parsed)
|| parsed.salt.is_none()
|| parsed.hash.is_none_or(|value| value.len() != 32)
{
return Err(PasswordHashError::InvalidHash);
}
Ok(())
}
pub fn verify_password_detailed(
password: &str,
stored_hash: &str,
) -> Result<PasswordVerification, PasswordHashError> {
let parsed = PasswordHash::new(stored_hash).map_err(|_| PasswordHashError::InvalidHash)?;
let verified = password_hasher()?
.verify_password(password.as_bytes(), &parsed)
.is_ok();
Ok(PasswordVerification {
verified,
needs_rehash: verified && !uses_current_policy(&parsed),
})
}
pub async fn verify_password(password: &str, stored_hash: &str) -> Result<bool, PasswordHashError> {
let password = Zeroizing::new(password.to_owned());
let stored_hash = stored_hash.to_owned();
let permit = PASSWORD_VERIFICATION
.acquire()
.await
.expect("the private password semaphore is never closed");
tokio::task::spawn_blocking(move || {
let _permit = permit;
verify_password_detailed(&password, &stored_hash).map(|result| result.verified)
})
.await
.map_err(|_| PasswordHashError::Execution)?
}
pub fn hash_backup_code(code: &str) -> Result<String, PasswordHashError> {
hash_password(code)
}
pub fn verify_backup_code(code: &str, hash: &str) -> Result<bool, PasswordHashError> {
verify_password_detailed(code, hash).map(|result| result.verified)
}
#[derive(Clone, Copy, Debug)]
pub struct RandomCodeSpec<'a> {
length: NonZeroUsize,
alphabet: &'a str,
}
impl<'a> RandomCodeSpec<'a> {
pub fn new(length: usize, alphabet: &'a str) -> Result<Self, RandomCodeSpecError> {
let length = NonZeroUsize::new(length).ok_or(RandomCodeSpecError::EmptyCode)?;
let alphabet_bytes = alphabet.as_bytes();
if alphabet_bytes.is_empty() {
return Err(RandomCodeSpecError::EmptyAlphabet);
}
if alphabet_bytes.len() > usize::from(u8::MAX) + 1 {
return Err(RandomCodeSpecError::AlphabetTooLarge);
}
if !alphabet_bytes.is_ascii() {
return Err(RandomCodeSpecError::NonAsciiAlphabet);
}
if alphabet_bytes
.iter()
.enumerate()
.any(|(index, byte)| alphabet_bytes[..index].contains(byte))
{
return Err(RandomCodeSpecError::DuplicateAlphabetCharacter);
}
Ok(Self { length, alphabet })
}
#[must_use]
pub const fn length(self) -> NonZeroUsize {
self.length
}
#[must_use]
pub fn alphabet(self) -> &'a str {
self.alphabet
}
}
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum RandomCodeSpecError {
#[error("random code length must be greater than zero")]
EmptyCode,
#[error("random code alphabet must not be empty")]
EmptyAlphabet,
#[error("random code alphabet must contain at most 256 characters")]
AlphabetTooLarge,
#[error("random code alphabet must contain ASCII characters only")]
NonAsciiAlphabet,
#[error("random code alphabet must not contain duplicate characters")]
DuplicateAlphabetCharacter,
}
#[derive(Debug, thiserror::Error)]
#[error("failed to generate a random code")]
pub struct RandomCodeGenerationError(#[source] getrandom::Error);
pub fn generate_random_code(spec: RandomCodeSpec<'_>) -> Result<String, RandomCodeGenerationError> {
let mut code = String::with_capacity(spec.length.get());
let mut random = [0_u8; 64];
let alphabet = spec.alphabet.as_bytes();
let acceptance_bound = (usize::from(u8::MAX) + 1) / alphabet.len() * alphabet.len();
while code.len() < spec.length.get() {
fill_random(&mut random).map_err(RandomCodeGenerationError)?;
for byte in random {
if usize::from(byte) >= acceptance_bound {
continue;
}
code.push(char::from(alphabet[usize::from(byte) % alphabet.len()]));
if code.len() == spec.length.get() {
break;
}
}
}
Ok(code)
}
fn password_hasher() -> Result<Argon2<'static>, PasswordHashError> {
let params = Params::new(
ARGON2_MEMORY_COST_KIB,
ARGON2_TIME_COST,
ARGON2_PARALLELISM,
None,
)
.map_err(|_| PasswordHashError::InvalidPolicy)?;
Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
}
fn uses_current_policy(hash: &PasswordHash<'_>) -> bool {
hash.algorithm.as_str() == "argon2id"
&& hash.version == Some(Version::V0x13 as u32)
&& hash.params.get_decimal("m") == Some(ARGON2_MEMORY_COST_KIB)
&& hash.params.get_decimal("t") == Some(ARGON2_TIME_COST)
&& hash.params.get_decimal("p") == Some(ARGON2_PARALLELISM)
}
#[cfg(test)]
mod tests {
use super::{
BootstrapAccount, BootstrapAccountError, PasswordHashError, RandomCodeSpec,
RandomCodeSpecError, generate_random_code, hash_backup_code, hash_password,
validate_password_hash, verify_backup_code, verify_password, verify_password_detailed,
};
#[tokio::test(flavor = "current_thread")]
async fn password_checks_yield_and_keep_typed_failures() {
let hash = super::hash_password("correct password").expect("fixture hash");
let progressed = std::sync::atomic::AtomicBool::new(false);
tokio::join!(
async {
assert!(
super::verify_password("correct password", &hash)
.await
.expect("valid hash")
);
assert!(
progressed.load(std::sync::atomic::Ordering::SeqCst),
"executor must progress during password verification"
);
},
async {
tokio::task::yield_now().await;
progressed.store(true, std::sync::atomic::Ordering::SeqCst);
},
);
assert!(
!super::verify_password("wrong password", &hash)
.await
.expect("valid hash")
);
let error = super::verify_password("private-password", "private-broken-hash")
.await
.expect_err("malformed hash");
assert!(!format!("{error:?} {error}").contains("private-"));
}
#[test]
fn bootstrap_account_normalizes_complete_values() {
let account = BootstrapAccount::from_required_values(
Some(" admin@example.com ".to_owned()),
Some(" correct horse battery staple ".to_owned()),
Some(" Administrator ".to_owned()),
)
.expect("complete bootstrap values should be accepted");
assert_eq!(account.email(), "admin@example.com");
assert_eq!(account.full_name(), "Administrator");
assert_eq!(account.password(), "correct horse battery staple");
assert!(!format!("{account:?}").contains("correct horse"));
}
#[test]
fn required_bootstrap_account_rejects_absent_values() {
assert_eq!(
BootstrapAccount::from_required_values(None, None, None),
Err(BootstrapAccountError::Missing),
);
}
#[test]
fn optional_bootstrap_account_accepts_absence_and_rejects_partial_values() {
assert_eq!(
BootstrapAccount::from_optional_values(None, None, None),
Ok(None),
);
assert_eq!(
BootstrapAccount::from_optional_values(
Some("admin@example.com".to_owned()),
None,
Some("Administrator".to_owned()),
),
Err(BootstrapAccountError::Incomplete),
);
}
#[test]
fn bootstrap_errors_are_safe_for_application_boundaries() {
fn assert_error<E: std::error::Error + Send + Sync + 'static>() {}
assert_error::<BootstrapAccountError>();
let error = BootstrapAccountError::InvalidUnicode {
key: "BOOTSTRAP_PASSWORD",
};
assert_eq!(
error.to_string(),
"bootstrap environment variable BOOTSTRAP_PASSWORD contains invalid Unicode"
);
}
#[test]
fn received_password_hashes_require_complete_bounded_argon2id_policy() {
let hash = hash_password("device-password").unwrap();
assert_eq!(validate_password_hash(&hash), Ok(()));
for invalid in [
"",
"5f4dcc3b5aa765d61d8327deb882cf99",
"$argon2id$v=19$m=19456,t=2,p=1",
&hash.replace("m=19456", "m=2147483647"),
&hash.replace("argon2id", "argon2i"),
&hash.replace("t=2", "t=999999"),
&hash.replace("v=19", "v=16"),
] {
assert_eq!(
validate_password_hash(invalid),
Err(PasswordHashError::InvalidHash)
);
}
}
#[tokio::test]
async fn hashes_and_verifies_passwords() {
let hash = hash_password("correct-horse").expect("hash should succeed");
assert!(
verify_password("correct-horse", &hash)
.await
.expect("valid hash")
);
assert!(
!verify_password("wrong-battery", &hash)
.await
.expect("valid hash")
);
let result =
verify_password_detailed("correct-horse", &hash).expect("generated hash should parse");
assert!(result.verified);
assert!(!result.needs_rehash);
}
#[tokio::test]
async fn malformed_hashes_return_a_typed_error() {
assert_eq!(
verify_password_detailed("password", "not-a-phc-string"),
Err(PasswordHashError::InvalidHash)
);
assert_eq!(
verify_password("password", "not-a-phc-string").await,
Err(PasswordHashError::InvalidHash)
);
}
#[test]
fn hashes_and_verifies_backup_codes() {
let hash = hash_backup_code("CODE-ONE").expect("hashing should succeed");
assert!(verify_backup_code("CODE-ONE", &hash).expect("hash is valid"));
assert!(!verify_backup_code("CODE-TWO", &hash).expect("hash is valid"));
}
#[test]
fn random_codes_follow_the_callers_format() {
let spec = RandomCodeSpec::new(24, "ABC123").expect("format should be valid");
let code = generate_random_code(spec).expect("code should generate");
assert_eq!(code.len(), 24);
assert!(code.bytes().all(|byte| b"ABC123".contains(&byte)));
}
#[test]
fn random_code_formats_reject_ambiguous_alphabets() {
assert!(matches!(
RandomCodeSpec::new(8, "AABC"),
Err(RandomCodeSpecError::DuplicateAlphabetCharacter)
));
assert!(matches!(
RandomCodeSpec::new(0, "ABC"),
Err(RandomCodeSpecError::EmptyCode)
));
}
}