ch-auth 0.1.0

Authentication and session primitives with explicit security policies
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Bootstrap credentials, passwords, recovery codes, and random-code primitives.

use std::{env, fmt, num::NonZeroUsize};

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;

/// Credentials used to create an application's first account.
#[derive(Clone, PartialEq, Eq)]
pub struct BootstrapAccount {
    email: String,
    full_name: String,
    password: Zeroizing<String>,
}

impl BootstrapAccount {
    /// Loads a required bootstrap account from the standard environment keys.
    ///
    /// # Errors
    ///
    /// Returns [`BootstrapAccountError`] when values are missing, incomplete,
    /// or not valid Unicode.
    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")?,
        )
    }

    /// Loads an optional bootstrap account from the standard environment keys.
    ///
    /// A completely absent configuration returns `None`; partially configured
    /// credentials are rejected.
    ///
    /// # Errors
    ///
    /// Returns [`BootstrapAccountError`] when values are incomplete or not
    /// valid Unicode.
    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")?,
        )
    }

    /// Builds a required bootstrap account from caller-provided values.
    ///
    /// # Errors
    ///
    /// Returns [`BootstrapAccountError::Missing`] when every value is absent,
    /// or [`BootstrapAccountError::Incomplete`] when only some are present.
    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)
    }

    /// Builds an optional bootstrap account from caller-provided values.
    ///
    /// # Errors
    ///
    /// Returns [`BootstrapAccountError::Incomplete`] when only some values are
    /// present.
    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),
        }
    }

    /// Returns the bootstrap account email address.
    #[must_use]
    pub fn email(&self) -> &str {
        self.email.as_str()
    }

    /// Returns the bootstrap account display name.
    #[must_use]
    pub fn full_name(&self) -> &str {
        self.full_name.as_str()
    }

    /// Exposes the password only to the account creation boundary.
    #[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()
    }
}

/// Invalid or incomplete bootstrap account configuration.
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum BootstrapAccountError {
    /// No values were supplied for a required bootstrap account.
    #[error("BOOTSTRAP_EMAIL, BOOTSTRAP_FULL_NAME and BOOTSTRAP_PASSWORD must all be set")]
    Missing,
    /// Only part of the required credential set was supplied.
    #[error(
        "BOOTSTRAP_EMAIL, BOOTSTRAP_FULL_NAME and BOOTSTRAP_PASSWORD must either all be set or all be omitted"
    )]
    Incomplete,
    /// An environment value cannot be represented as Unicode.
    #[error("bootstrap environment variable {key} contains invalid Unicode")]
    InvalidUnicode {
        /// Name of the invalid environment variable. Its value is never retained.
        key: &'static str,
    },
}

fn read_bootstrap_value(key: &'static str) -> Result<Option<String>, BootstrapAccountError> {
    match env::var(key) {
        Ok(value) => Ok(Some(value)),
        Err(env::VarError::NotPresent) => Ok(None),
        Err(env::VarError::NotUnicode(_)) => Err(BootstrapAccountError::InvalidUnicode { key }),
    }
}

fn normalize_bootstrap_value(value: Option<String>) -> Option<String> {
    value
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// Memory cost in KiB for the default Argon2id policy.
pub const ARGON2_MEMORY_COST_KIB: u32 = 19_456;
/// Number of passes used by the default Argon2id policy.
pub const ARGON2_TIME_COST: u32 = 2;
/// Parallelism used by the default Argon2id policy.
pub const ARGON2_PARALLELISM: u32 = 1;

/// Password-hashing failure without secret-bearing diagnostics.
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum PasswordHashError {
    /// The configured Argon2 policy is not supported.
    #[error("invalid Argon2 password policy")]
    InvalidPolicy,
    /// Argon2 could not create the encoded password hash.
    #[error("failed to hash password")]
    Hashing,
    /// The stored PHC string is malformed or unsupported.
    #[error("stored password hash is invalid")]
    InvalidHash,
}

/// Successful password verification and its upgrade status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PasswordVerification {
    /// Whether the submitted password matches the stored hash.
    pub verified: bool,
    /// Whether a successful match should be rehashed with the current policy.
    pub needs_rehash: bool,
}

/// Computes an Argon2id password hash using the crate's current policy.
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)
}

/// Verifies a password and reports whether its hash should be upgraded.
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),
    })
}

/// Verifies a password against a stored Argon2 hash.
///
/// Malformed hashes are rejected without exposing parser details. Use
/// [`verify_password_detailed`] when hash-upgrade information matters.
#[must_use]
pub fn verify_password(password: &str, stored_hash: &str) -> bool {
    verify_password_detailed(password, stored_hash)
        .map(|result| result.verified)
        .unwrap_or(false)
}

/// Generates an Argon2id hash for a one-time recovery code.
pub fn hash_backup_code(code: &str) -> Result<String, PasswordHashError> {
    hash_password(code)
}

/// Verifies a one-time recovery code against its stored hash.
pub fn verify_backup_code(code: &str, hash: &str) -> Result<bool, PasswordHashError> {
    verify_password_detailed(code, hash).map(|result| result.verified)
}

/// Validated format used to generate a cryptographically random code.
#[derive(Clone, Copy, Debug)]
pub struct RandomCodeSpec<'a> {
    length: NonZeroUsize,
    alphabet: &'a str,
}

impl<'a> RandomCodeSpec<'a> {
    /// Validates a code length and an ASCII alphabet.
    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 })
    }

    /// Returns the generated code length.
    #[must_use]
    pub const fn length(self) -> NonZeroUsize {
        self.length
    }

    /// Returns the validated ASCII alphabet.
    #[must_use]
    pub fn alphabet(self) -> &'a str {
        self.alphabet
    }
}

/// Validation error for [`RandomCodeSpec`].
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum RandomCodeSpecError {
    /// Generated codes must contain at least one character.
    #[error("random code length must be greater than zero")]
    EmptyCode,
    /// The alphabet must contain at least one character.
    #[error("random code alphabet must not be empty")]
    EmptyAlphabet,
    /// Rejection sampling supports at most 256 distinct symbols.
    #[error("random code alphabet must contain at most 256 characters")]
    AlphabetTooLarge,
    /// Byte-oriented code generation requires an ASCII alphabet.
    #[error("random code alphabet must contain ASCII characters only")]
    NonAsciiAlphabet,
    /// Duplicate characters would unintentionally weight the alphabet.
    #[error("random code alphabet must not contain duplicate characters")]
    DuplicateAlphabetCharacter,
}

/// Failure returned when secure random bytes cannot be obtained.
#[derive(Debug, thiserror::Error)]
#[error("failed to generate a random code")]
pub struct RandomCodeGenerationError(#[source] getrandom::Error);

/// Generates a random code without modulo bias from a validated format.
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,
        verify_backup_code, verify_password, verify_password_detailed,
    };

    #[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 hashes_and_verifies_passwords() {
        let hash = hash_password("correct-horse").expect("hash should succeed");
        assert!(verify_password("correct-horse", &hash));
        assert!(!verify_password("wrong-battery", &hash));

        let result =
            verify_password_detailed("correct-horse", &hash).expect("generated hash should parse");
        assert!(result.verified);
        assert!(!result.needs_rehash);
    }

    #[test]
    fn malformed_hashes_return_a_typed_error() {
        assert_eq!(
            verify_password_detailed("password", "not-a-phc-string"),
            Err(PasswordHashError::InvalidHash)
        );
        assert!(!verify_password("password", "not-a-phc-string"));
    }

    #[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)
        ));
    }
}