ch-auth 0.3.2

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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! CAPTCHA issuance and one-time verification policies.

use std::fmt;
use std::sync::{Arc, Mutex};

use base64::{Engine as _, engine::general_purpose::STANDARD};
use captcha::{Captcha, filters::Noise};
use ch_parsing::error::{ParseError, ParseErrorCode, ParseResult};
use ch_parsing::input::strings::{enforce_max_len, require_trimmed};
use dashmap::DashMap;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use time::{Duration, OffsetDateTime};
use uuid::Uuid;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::ratelimit::SecurityState;

const DEFAULT_CAPTCHA_LENGTH: u32 = 6;
const MAX_OUTSTANDING_CHALLENGES: usize = 10_000;
const MAX_CAPTCHA_TOKEN_CHARS: usize = 256;
const MAX_CAPTCHA_RESPONSE_CHARS: usize = 64;

/// Serializable CAPTCHA response returned to an HTTP adapter.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CaptchaChallengeView {
    /// Opaque one-time token submitted with the solution.
    pub token: String,
    /// PNG image encoded as a data URL.
    pub image_data_url: String,
    /// Number of characters expected in the solution.
    pub length: usize,
    /// Whether the explicitly configured debug bypass is active.
    pub bypass: bool,
}

/// Explicit CAPTCHA policy input owned by the consuming application.
#[derive(Clone, Debug)]
pub struct CaptchaConfig {
    /// Characters from which challenges may be generated.
    pub charset: String,
    /// Noise intensity applied to rendered challenge images.
    pub noise_level: f32,
    /// Lifetime of a one-time challenge.
    pub expires_after_secs: u64,
    /// Development-only bypass flag.
    pub bypass: bool,
}

/// Invalid CAPTCHA policy configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CaptchaConfigError {
    /// The configured character set cannot produce meaningful challenges.
    #[error("captcha charset must include at least two unique non-whitespace characters")]
    InsufficientCharset,
    /// Noise must be a finite value in the closed unit interval.
    #[error("captcha noise level must be finite and between zero and one")]
    InvalidNoiseLevel,
    /// The configured expiry cannot be represented by the time library.
    #[error("captcha expiry exceeds the supported duration")]
    ExpiryOutOfRange,
    /// Challenges must remain valid for a positive duration.
    #[error("captcha expiry must be greater than zero")]
    NonPositiveExpiry,
    /// The development bypass cannot be enabled in an optimized build.
    #[error("captcha bypass is unavailable in release builds")]
    BypassUnavailable,
    /// The operating system could not provide challenge-signing key material.
    #[error("captcha verification key generation failed")]
    VerificationKeyGeneration,
}

/// Validated CAPTCHA policy and its isolated one-time challenge store.
#[derive(Clone)]
pub struct CaptchaPolicy {
    charset: Vec<char>,
    noise_level: f32,
    expires_after: Duration,
    bypass: bool,
    nonces: CaptchaNonceStore,
    verification_key: Arc<Zeroizing<[u8; 32]>>,
}

impl fmt::Debug for CaptchaPolicy {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CaptchaPolicy")
            .field("charset_len", &self.charset.len())
            .field("noise_level", &self.noise_level)
            .field("expires_after", &self.expires_after)
            .field("bypass", &self.bypass)
            .field("outstanding_challenges", &self.nonces.len())
            .finish()
    }
}

impl CaptchaPolicy {
    /// Validates application-provided CAPTCHA configuration.
    ///
    /// # Errors
    ///
    /// Returns an error unless the character set contains at least two unique
    /// symbols, noise is in the closed unit interval, expiry is positive and
    /// supported, and bypass is disabled in release builds.
    pub fn from_config(config: &CaptchaConfig) -> Result<Self, CaptchaConfigError> {
        let mut charset = Vec::new();
        for character in config
            .charset
            .chars()
            .filter(|character| !character.is_whitespace())
        {
            if !charset.contains(&character) {
                charset.push(character);
            }
        }
        if charset.len() < 2 {
            return Err(CaptchaConfigError::InsufficientCharset);
        }
        if !config.noise_level.is_finite() || !(0.0..=1.0).contains(&config.noise_level) {
            return Err(CaptchaConfigError::InvalidNoiseLevel);
        }
        if config.bypass && !cfg!(debug_assertions) {
            return Err(CaptchaConfigError::BypassUnavailable);
        }

        let expires_after = Duration::seconds(
            i64::try_from(config.expires_after_secs)
                .map_err(|_| CaptchaConfigError::ExpiryOutOfRange)?,
        );
        if !expires_after.is_positive() {
            return Err(CaptchaConfigError::NonPositiveExpiry);
        }

        let mut verification_key = Zeroizing::new([0_u8; 32]);
        getrandom::fill(verification_key.as_mut())
            .map_err(|_| CaptchaConfigError::VerificationKeyGeneration)?;

        Ok(Self {
            charset,
            noise_level: config.noise_level,
            expires_after,
            bypass: config.bypass,
            nonces: CaptchaNonceStore::new(),
            verification_key: Arc::new(verification_key),
        })
    }

    /// Returns whether the development-only bypass is active.
    #[must_use]
    pub const fn bypass(&self) -> bool {
        self.bypass
    }

    /// Parses an opaque token according to this policy.
    pub fn parse_token(&self, raw: String) -> ParseResult<CaptchaToken> {
        if self.bypass && raw.trim().is_empty() {
            return Ok(CaptchaToken("debug-bypass".to_owned()));
        }
        CaptchaToken::parse(raw)
    }

    /// Parses a candidate solution according to this policy.
    pub fn parse_response(&self, raw: String) -> ParseResult<CaptchaResponse> {
        if self.bypass {
            enforce_max_len(&raw, MAX_CAPTCHA_RESPONSE_CHARS, "captcha")?;
            return Ok(CaptchaResponse(raw));
        }
        CaptchaResponse::parse(raw)
    }

    /// Consumes and verifies a one-time challenge.
    ///
    /// A token is removed on its first verification attempt, including an
    /// incorrect response, so it cannot be replayed or brute-forced.
    pub fn consume(
        &self,
        token: &CaptchaToken,
        response: CaptchaResponse,
        now: OffsetDateTime,
    ) -> ParseResult<()> {
        if self.bypass {
            return Ok(());
        }
        self.nonces
            .consume(token, response, now, &self.verification_key[..])
    }

    fn issue(
        &self,
        length: u32,
        now: OffsetDateTime,
    ) -> Result<CaptchaIssuedChallenge, CaptchaIssueError> {
        let mut captcha = Captcha::new();
        captcha.set_chars(&self.charset);
        captcha.add_chars(length);
        captcha.apply_filter(Noise::new(self.noise_level));

        let png = captcha.as_png().ok_or(CaptchaIssueError::Generation)?;
        let solution = Zeroizing::new(captcha.chars_as_string());
        let solution_length = solution.chars().count();
        let solution_tag = captcha_solution_tag(&self.verification_key[..], &solution)
            .ok_or(CaptchaIssueError::Generation)?;
        Ok(CaptchaIssuedChallenge {
            challenge: CaptchaChallenge {
                solution_tag,
                solution_length,
                expires_at: now + self.expires_after,
            },
            image_data_url: format!("data:image/png;base64,{}", STANDARD.encode(png)),
        })
    }
}

/// Stable failure categories for CAPTCHA issuance.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CaptchaIssueError {
    /// The client exceeded the configured issuance budget.
    #[error("captcha.rate_limited")]
    RateLimited,
    /// Too many unconsumed challenges are already retained.
    #[error("captcha.capacity_exceeded")]
    CapacityExceeded,
    /// The image generator could not produce a challenge.
    #[error("captcha.generation_failed")]
    Generation,
}

/// Parsed CAPTCHA response with redacted debug output.
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct CaptchaResponse(String);

impl CaptchaResponse {
    fn parse(raw: String) -> ParseResult<Self> {
        enforce_max_len(&raw, MAX_CAPTCHA_RESPONSE_CHARS, "captcha")?;
        require_trimmed(&raw, "captcha").map(Self)
    }

    fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Debug for CaptchaResponse {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("CaptchaResponse")
            .field(&"[REDACTED]")
            .finish()
    }
}

/// Parsed opaque challenge token with redacted debug output.
#[derive(Clone, PartialEq, Eq)]
pub struct CaptchaToken(String);

impl CaptchaToken {
    fn parse(raw: String) -> ParseResult<Self> {
        enforce_max_len(&raw, MAX_CAPTCHA_TOKEN_CHARS, "captcha_token")?;
        if raw.trim().is_empty() {
            return Err(ParseError::for_field(
                "captcha_token",
                ParseErrorCode::Required,
            ));
        }
        Ok(Self(raw))
    }

    /// Returns the token for transport to the nonce store.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Debug for CaptchaToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("CaptchaToken")
            .field(&"[REDACTED]")
            .finish()
    }
}

#[derive(Clone)]
struct CaptchaNonceStore {
    inner: Arc<DashMap<String, CaptchaChallenge>>,
    admission: Arc<Mutex<()>>,
}

impl CaptchaNonceStore {
    fn new() -> Self {
        Self {
            inner: Arc::new(DashMap::new()),
            admission: Arc::new(Mutex::new(())),
        }
    }

    fn len(&self) -> usize {
        self.inner.len()
    }

    fn remember(
        &self,
        token: CaptchaToken,
        challenge: CaptchaChallenge,
        now: OffsetDateTime,
    ) -> Result<(), CaptchaIssueError> {
        let _admission = self
            .admission
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.inner.retain(|_, stored| stored.expires_at > now);
        if self.inner.len() >= MAX_OUTSTANDING_CHALLENGES {
            return Err(CaptchaIssueError::CapacityExceeded);
        }
        self.inner.insert(token.0, challenge);
        Ok(())
    }

    fn consume(
        &self,
        token: &CaptchaToken,
        response: CaptchaResponse,
        now: OffsetDateTime,
        verification_key: &[u8],
    ) -> ParseResult<()> {
        let (_, challenge) = self.inner.remove(token.as_str()).ok_or_else(|| {
            tracing::warn!("captcha token was missing or already consumed");
            ParseError::for_field("captcha_token", ParseErrorCode::InvalidValue)
                .with_parameter("reason", "missing_or_consumed")
        })?;

        match challenge.verify(&response, now, verification_key) {
            CaptchaVerification::Accepted => Ok(()),
            CaptchaVerification::Expired => {
                tracing::warn!("captcha token expired during verification");
                Err(
                    ParseError::for_field("captcha_token", ParseErrorCode::InvalidValue)
                        .with_parameter("reason", "expired"),
                )
            }
            CaptchaVerification::Rejected => {
                tracing::warn!("captcha response was rejected");
                Err(
                    ParseError::for_field("captcha", ParseErrorCode::InvalidValue)
                        .with_parameter("reason", "mismatch"),
                )
            }
        }
    }
}

struct CaptchaIssuedChallenge {
    challenge: CaptchaChallenge,
    image_data_url: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CaptchaVerification {
    Accepted,
    Expired,
    Rejected,
}

struct CaptchaChallenge {
    solution_tag: [u8; 32],
    solution_length: usize,
    expires_at: OffsetDateTime,
}

impl CaptchaChallenge {
    fn solution_length(&self) -> usize {
        self.solution_length
    }

    fn verify(
        &self,
        response: &CaptchaResponse,
        now: OffsetDateTime,
        verification_key: &[u8],
    ) -> CaptchaVerification {
        if now > self.expires_at {
            return CaptchaVerification::Expired;
        }
        let Ok(mut verifier) = Hmac::<Sha256>::new_from_slice(verification_key) else {
            return CaptchaVerification::Rejected;
        };
        update_captcha_solution(&mut verifier, response.as_str());
        if verifier.verify_slice(&self.solution_tag).is_ok() {
            return CaptchaVerification::Accepted;
        }
        CaptchaVerification::Rejected
    }
}

fn captcha_solution_tag(key: &[u8], solution: &str) -> Option<[u8; 32]> {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).ok()?;
    update_captcha_solution(&mut mac, solution);
    Some(mac.finalize().into_bytes().into())
}

fn update_captcha_solution(mac: &mut Hmac<Sha256>, solution: &str) {
    for character in solution.trim().chars().flat_map(char::to_lowercase) {
        let mut bytes = [0_u8; 4];
        mac.update(character.encode_utf8(&mut bytes).as_bytes());
    }
}

/// Issues a rate-limited one-time challenge using an explicit policy.
pub fn issue_captcha_challenge(
    policy: &CaptchaPolicy,
    security: &SecurityState,
    client_key: impl Into<String>,
    now: OffsetDateTime,
) -> Result<CaptchaChallengeView, CaptchaIssueError> {
    if policy.bypass {
        return Ok(CaptchaChallengeView {
            token: "debug-bypass".to_owned(),
            image_data_url: String::new(),
            length: DEFAULT_CAPTCHA_LENGTH as usize,
            bypass: true,
        });
    }

    let outcome = security
        .captcha_issuance
        .check(format!("captcha:issue:{}", client_key.into()));
    if !outcome.allowed {
        return Err(CaptchaIssueError::RateLimited);
    }

    let issued = policy.issue(DEFAULT_CAPTCHA_LENGTH, now)?;
    let token = CaptchaToken::parse(Uuid::new_v4().to_string()).map_err(|error| {
        tracing::error!(%error, "generated CAPTCHA token was rejected");
        CaptchaIssueError::Generation
    })?;
    let length = issued.challenge.solution_length();
    let image_data_url = issued.image_data_url;
    policy
        .nonces
        .remember(token.clone(), issued.challenge, now)?;

    Ok(CaptchaChallengeView {
        token: token.0,
        image_data_url,
        length,
        bypass: false,
    })
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroU32;

    use ch_parsing::error::ParseErrorCode;
    use time::{Duration, OffsetDateTime};

    use super::{CaptchaConfig, CaptchaIssueError, CaptchaPolicy, issue_captcha_challenge};
    use crate::ratelimit::SecurityState;

    fn policy(bypass: bool) -> CaptchaPolicy {
        CaptchaPolicy::from_config(&CaptchaConfig {
            charset: "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".to_owned(),
            noise_level: 0.1,
            expires_after_secs: 60,
            bypass,
        })
        .expect("test policy should build")
    }

    #[test]
    fn issue_and_consume_are_policy_owned() {
        let policy = policy(false);
        let now = OffsetDateTime::now_utc();
        let challenge = super::CaptchaChallenge {
            solution_tag: super::captcha_solution_tag(&policy.verification_key[..], "ABCD")
                .expect("valid verification key"),
            solution_length: 4,
            expires_at: now + Duration::seconds(60),
        };
        let token = policy.parse_token("opaque-token".to_owned()).unwrap();
        policy
            .nonces
            .remember(token.clone(), challenge, now)
            .unwrap();
        let response = policy.parse_response("ABCD".to_owned()).unwrap();
        policy.consume(&token, response, now).unwrap();

        let replay = policy
            .consume(
                &token,
                policy.parse_response("ABCD".to_owned()).unwrap(),
                now,
            )
            .unwrap_err();
        assert_eq!(replay.code(), ParseErrorCode::InvalidValue);
        assert_eq!(replay.parameter("reason"), Some("missing_or_consumed"));
    }

    #[test]
    fn issued_challenge_contains_png_data_url() {
        let policy = policy(false);
        let security = SecurityState::new(NonZeroU32::new(4).unwrap());
        let challenge =
            issue_captcha_challenge(&policy, &security, "client-1", OffsetDateTime::now_utc())
                .unwrap();
        assert!(
            challenge
                .image_data_url
                .starts_with("data:image/png;base64,")
        );
        assert!(!challenge.token.is_empty());
        assert!(!challenge.bypass);
    }

    #[test]
    fn debug_bypass_is_explicit_and_redacted() {
        let policy = policy(true);
        let security = SecurityState::new(NonZeroU32::new(1).unwrap());
        let challenge =
            issue_captcha_challenge(&policy, &security, "client-1", OffsetDateTime::now_utc())
                .unwrap();
        assert!(challenge.bypass);
        assert_eq!(challenge.token, "debug-bypass");
        assert!(
            issue_captcha_challenge(&policy, &security, "client-1", OffsetDateTime::now_utc())
                .unwrap()
                .bypass
        );

        let token = policy.parse_token(String::new()).unwrap();
        let response = policy.parse_response(String::new()).unwrap();
        assert!(format!("{token:?}").contains("REDACTED"));
        assert!(format!("{response:?}").contains("REDACTED"));
    }

    #[test]
    fn issuance_budget_is_enforced() {
        let policy = policy(false);
        let security = SecurityState::new(NonZeroU32::new(1).unwrap());
        let now = OffsetDateTime::now_utc();
        issue_captcha_challenge(&policy, &security, "client-1", now).unwrap();
        assert!(matches!(
            issue_captcha_challenge(&policy, &security, "client-1", now),
            Err(CaptchaIssueError::RateLimited)
        ));
    }

    #[test]
    fn rejects_unsafe_generation_configuration() {
        for charset in ["", "A", "AAAA", " A A "] {
            let error = CaptchaPolicy::from_config(&CaptchaConfig {
                charset: charset.to_owned(),
                noise_level: 0.1,
                expires_after_secs: 60,
                bypass: false,
            })
            .expect_err("charset must contain at least two unique characters");
            assert!(error.to_string().contains("two unique"));
        }

        for noise_level in [-0.1, 1.1, f32::INFINITY, f32::NAN] {
            let error = CaptchaPolicy::from_config(&CaptchaConfig {
                charset: "AB".to_owned(),
                noise_level,
                expires_after_secs: 60,
                bypass: false,
            })
            .expect_err("noise outside the closed unit interval must fail");
            assert!(error.to_string().contains("between zero and one"));
        }
    }

    #[test]
    fn token_and_response_limits_are_enforced() {
        let policy = policy(false);
        let token_error = policy
            .parse_token("x".repeat(super::MAX_CAPTCHA_TOKEN_CHARS + 1))
            .expect_err("oversized tokens must fail");
        assert_eq!(token_error.code(), ParseErrorCode::TooLong);

        let response_error = policy
            .parse_response("x".repeat(super::MAX_CAPTCHA_RESPONSE_CHARS + 1))
            .expect_err("oversized responses must fail");
        assert_eq!(response_error.code(), ParseErrorCode::TooLong);
    }
}