Skip to main content

ch_auth/captcha/
mod.rs

1//! CAPTCHA issuance and one-time verification policies.
2
3use std::fmt;
4use std::sync::{Arc, Mutex};
5
6use base64::{Engine as _, engine::general_purpose::STANDARD};
7use captcha::{Captcha, filters::Noise};
8use ch_parsing::error::{ParseError, ParseErrorCode, ParseResult};
9use ch_parsing::input::strings::{enforce_max_len, require_trimmed};
10use dashmap::DashMap;
11use hmac::{Hmac, KeyInit, Mac};
12use sha2::Sha256;
13use time::{Duration, OffsetDateTime};
14use uuid::Uuid;
15use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
16
17use crate::ratelimit::SecurityState;
18
19const DEFAULT_CAPTCHA_LENGTH: u32 = 6;
20const MAX_OUTSTANDING_CHALLENGES: usize = 10_000;
21const MAX_CAPTCHA_TOKEN_CHARS: usize = 256;
22const MAX_CAPTCHA_RESPONSE_CHARS: usize = 64;
23
24/// Serializable CAPTCHA response returned to an HTTP adapter.
25#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
26pub struct CaptchaChallengeView {
27    /// Opaque one-time token submitted with the solution.
28    pub token: String,
29    /// PNG image encoded as a data URL.
30    pub image_data_url: String,
31    /// Number of characters expected in the solution.
32    pub length: usize,
33    /// Whether the explicitly configured debug bypass is active.
34    pub bypass: bool,
35}
36
37/// Explicit CAPTCHA policy input owned by the consuming application.
38#[derive(Clone, Debug)]
39pub struct CaptchaConfig {
40    /// Characters from which challenges may be generated.
41    pub charset: String,
42    /// Noise intensity applied to rendered challenge images.
43    pub noise_level: f32,
44    /// Lifetime of a one-time challenge.
45    pub expires_after_secs: u64,
46    /// Development-only bypass flag.
47    pub bypass: bool,
48}
49
50/// Invalid CAPTCHA policy configuration.
51#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
52#[non_exhaustive]
53pub enum CaptchaConfigError {
54    /// The configured character set cannot produce meaningful challenges.
55    #[error("captcha charset must include at least two unique non-whitespace characters")]
56    InsufficientCharset,
57    /// Noise must be a finite value in the closed unit interval.
58    #[error("captcha noise level must be finite and between zero and one")]
59    InvalidNoiseLevel,
60    /// The configured expiry cannot be represented by the time library.
61    #[error("captcha expiry exceeds the supported duration")]
62    ExpiryOutOfRange,
63    /// Challenges must remain valid for a positive duration.
64    #[error("captcha expiry must be greater than zero")]
65    NonPositiveExpiry,
66    /// The development bypass cannot be enabled in an optimized build.
67    #[error("captcha bypass is unavailable in release builds")]
68    BypassUnavailable,
69    /// The operating system could not provide challenge-signing key material.
70    #[error("captcha verification key generation failed")]
71    VerificationKeyGeneration,
72}
73
74/// Validated CAPTCHA policy and its isolated one-time challenge store.
75#[derive(Clone)]
76pub struct CaptchaPolicy {
77    charset: Vec<char>,
78    noise_level: f32,
79    expires_after: Duration,
80    bypass: bool,
81    nonces: CaptchaNonceStore,
82    verification_key: Arc<Zeroizing<[u8; 32]>>,
83}
84
85impl fmt::Debug for CaptchaPolicy {
86    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
87        formatter
88            .debug_struct("CaptchaPolicy")
89            .field("charset_len", &self.charset.len())
90            .field("noise_level", &self.noise_level)
91            .field("expires_after", &self.expires_after)
92            .field("bypass", &self.bypass)
93            .field("outstanding_challenges", &self.nonces.len())
94            .finish()
95    }
96}
97
98impl CaptchaPolicy {
99    /// Validates application-provided CAPTCHA configuration.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error unless the character set contains at least two unique
104    /// symbols, noise is in the closed unit interval, expiry is positive and
105    /// supported, and bypass is disabled in release builds.
106    pub fn from_config(config: &CaptchaConfig) -> Result<Self, CaptchaConfigError> {
107        let mut charset = Vec::new();
108        for character in config
109            .charset
110            .chars()
111            .filter(|character| !character.is_whitespace())
112        {
113            if !charset.contains(&character) {
114                charset.push(character);
115            }
116        }
117        if charset.len() < 2 {
118            return Err(CaptchaConfigError::InsufficientCharset);
119        }
120        if !config.noise_level.is_finite() || !(0.0..=1.0).contains(&config.noise_level) {
121            return Err(CaptchaConfigError::InvalidNoiseLevel);
122        }
123        if config.bypass && !cfg!(debug_assertions) {
124            return Err(CaptchaConfigError::BypassUnavailable);
125        }
126
127        let expires_after = Duration::seconds(
128            i64::try_from(config.expires_after_secs)
129                .map_err(|_| CaptchaConfigError::ExpiryOutOfRange)?,
130        );
131        if !expires_after.is_positive() {
132            return Err(CaptchaConfigError::NonPositiveExpiry);
133        }
134
135        let mut verification_key = Zeroizing::new([0_u8; 32]);
136        getrandom::fill(verification_key.as_mut())
137            .map_err(|_| CaptchaConfigError::VerificationKeyGeneration)?;
138
139        Ok(Self {
140            charset,
141            noise_level: config.noise_level,
142            expires_after,
143            bypass: config.bypass,
144            nonces: CaptchaNonceStore::new(),
145            verification_key: Arc::new(verification_key),
146        })
147    }
148
149    /// Returns whether the development-only bypass is active.
150    #[must_use]
151    pub const fn bypass(&self) -> bool {
152        self.bypass
153    }
154
155    /// Parses an opaque token according to this policy.
156    pub fn parse_token(&self, raw: String) -> ParseResult<CaptchaToken> {
157        if self.bypass && raw.trim().is_empty() {
158            return Ok(CaptchaToken("debug-bypass".to_owned()));
159        }
160        CaptchaToken::parse(raw)
161    }
162
163    /// Parses a candidate solution according to this policy.
164    pub fn parse_response(&self, raw: String) -> ParseResult<CaptchaResponse> {
165        if self.bypass {
166            enforce_max_len(&raw, MAX_CAPTCHA_RESPONSE_CHARS, "captcha")?;
167            return Ok(CaptchaResponse(raw));
168        }
169        CaptchaResponse::parse(raw)
170    }
171
172    /// Consumes and verifies a one-time challenge.
173    ///
174    /// A token is removed on its first verification attempt, including an
175    /// incorrect response, so it cannot be replayed or brute-forced.
176    pub fn consume(
177        &self,
178        token: &CaptchaToken,
179        response: CaptchaResponse,
180        now: OffsetDateTime,
181    ) -> ParseResult<()> {
182        if self.bypass {
183            return Ok(());
184        }
185        self.nonces
186            .consume(token, response, now, &self.verification_key[..])
187    }
188
189    fn issue(
190        &self,
191        length: u32,
192        now: OffsetDateTime,
193    ) -> Result<CaptchaIssuedChallenge, CaptchaIssueError> {
194        let mut captcha = Captcha::new();
195        captcha.set_chars(&self.charset);
196        captcha.add_chars(length);
197        captcha.apply_filter(Noise::new(self.noise_level));
198
199        let png = captcha.as_png().ok_or(CaptchaIssueError::Generation)?;
200        let solution = Zeroizing::new(captcha.chars_as_string());
201        let solution_length = solution.chars().count();
202        let solution_tag = captcha_solution_tag(&self.verification_key[..], &solution)
203            .ok_or(CaptchaIssueError::Generation)?;
204        Ok(CaptchaIssuedChallenge {
205            challenge: CaptchaChallenge {
206                solution_tag,
207                solution_length,
208                expires_at: now + self.expires_after,
209            },
210            image_data_url: format!("data:image/png;base64,{}", STANDARD.encode(png)),
211        })
212    }
213}
214
215/// Stable failure categories for CAPTCHA issuance.
216#[derive(Debug, thiserror::Error)]
217#[non_exhaustive]
218pub enum CaptchaIssueError {
219    /// The client exceeded the configured issuance budget.
220    #[error("captcha.rate_limited")]
221    RateLimited,
222    /// Too many unconsumed challenges are already retained.
223    #[error("captcha.capacity_exceeded")]
224    CapacityExceeded,
225    /// The image generator could not produce a challenge.
226    #[error("captcha.generation_failed")]
227    Generation,
228}
229
230/// Parsed CAPTCHA response with redacted debug output.
231#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
232pub struct CaptchaResponse(String);
233
234impl CaptchaResponse {
235    fn parse(raw: String) -> ParseResult<Self> {
236        enforce_max_len(&raw, MAX_CAPTCHA_RESPONSE_CHARS, "captcha")?;
237        require_trimmed(&raw, "captcha").map(Self)
238    }
239
240    fn as_str(&self) -> &str {
241        self.0.as_str()
242    }
243}
244
245impl fmt::Debug for CaptchaResponse {
246    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
247        formatter
248            .debug_tuple("CaptchaResponse")
249            .field(&"[REDACTED]")
250            .finish()
251    }
252}
253
254/// Parsed opaque challenge token with redacted debug output.
255#[derive(Clone, PartialEq, Eq)]
256pub struct CaptchaToken(String);
257
258impl CaptchaToken {
259    fn parse(raw: String) -> ParseResult<Self> {
260        enforce_max_len(&raw, MAX_CAPTCHA_TOKEN_CHARS, "captcha_token")?;
261        if raw.trim().is_empty() {
262            return Err(ParseError::for_field(
263                "captcha_token",
264                ParseErrorCode::Required,
265            ));
266        }
267        Ok(Self(raw))
268    }
269
270    /// Returns the token for transport to the nonce store.
271    #[must_use]
272    pub fn as_str(&self) -> &str {
273        self.0.as_str()
274    }
275}
276
277impl fmt::Debug for CaptchaToken {
278    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
279        formatter
280            .debug_tuple("CaptchaToken")
281            .field(&"[REDACTED]")
282            .finish()
283    }
284}
285
286#[derive(Clone)]
287struct CaptchaNonceStore {
288    inner: Arc<DashMap<String, CaptchaChallenge>>,
289    admission: Arc<Mutex<()>>,
290}
291
292impl CaptchaNonceStore {
293    fn new() -> Self {
294        Self {
295            inner: Arc::new(DashMap::new()),
296            admission: Arc::new(Mutex::new(())),
297        }
298    }
299
300    fn len(&self) -> usize {
301        self.inner.len()
302    }
303
304    fn remember(
305        &self,
306        token: CaptchaToken,
307        challenge: CaptchaChallenge,
308        now: OffsetDateTime,
309    ) -> Result<(), CaptchaIssueError> {
310        let _admission = self
311            .admission
312            .lock()
313            .unwrap_or_else(std::sync::PoisonError::into_inner);
314        self.inner.retain(|_, stored| stored.expires_at > now);
315        if self.inner.len() >= MAX_OUTSTANDING_CHALLENGES {
316            return Err(CaptchaIssueError::CapacityExceeded);
317        }
318        self.inner.insert(token.0, challenge);
319        Ok(())
320    }
321
322    fn consume(
323        &self,
324        token: &CaptchaToken,
325        response: CaptchaResponse,
326        now: OffsetDateTime,
327        verification_key: &[u8],
328    ) -> ParseResult<()> {
329        let (_, challenge) = self.inner.remove(token.as_str()).ok_or_else(|| {
330            tracing::warn!("captcha token was missing or already consumed");
331            ParseError::for_field("captcha_token", ParseErrorCode::InvalidValue)
332                .with_parameter("reason", "missing_or_consumed")
333        })?;
334
335        match challenge.verify(&response, now, verification_key) {
336            CaptchaVerification::Accepted => Ok(()),
337            CaptchaVerification::Expired => {
338                tracing::warn!("captcha token expired during verification");
339                Err(
340                    ParseError::for_field("captcha_token", ParseErrorCode::InvalidValue)
341                        .with_parameter("reason", "expired"),
342                )
343            }
344            CaptchaVerification::Rejected => {
345                tracing::warn!("captcha response was rejected");
346                Err(
347                    ParseError::for_field("captcha", ParseErrorCode::InvalidValue)
348                        .with_parameter("reason", "mismatch"),
349                )
350            }
351        }
352    }
353}
354
355struct CaptchaIssuedChallenge {
356    challenge: CaptchaChallenge,
357    image_data_url: String,
358}
359
360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
361enum CaptchaVerification {
362    Accepted,
363    Expired,
364    Rejected,
365}
366
367struct CaptchaChallenge {
368    solution_tag: [u8; 32],
369    solution_length: usize,
370    expires_at: OffsetDateTime,
371}
372
373impl CaptchaChallenge {
374    fn solution_length(&self) -> usize {
375        self.solution_length
376    }
377
378    fn verify(
379        &self,
380        response: &CaptchaResponse,
381        now: OffsetDateTime,
382        verification_key: &[u8],
383    ) -> CaptchaVerification {
384        if now > self.expires_at {
385            return CaptchaVerification::Expired;
386        }
387        let Ok(mut verifier) = Hmac::<Sha256>::new_from_slice(verification_key) else {
388            return CaptchaVerification::Rejected;
389        };
390        update_captcha_solution(&mut verifier, response.as_str());
391        if verifier.verify_slice(&self.solution_tag).is_ok() {
392            return CaptchaVerification::Accepted;
393        }
394        CaptchaVerification::Rejected
395    }
396}
397
398fn captcha_solution_tag(key: &[u8], solution: &str) -> Option<[u8; 32]> {
399    let mut mac = Hmac::<Sha256>::new_from_slice(key).ok()?;
400    update_captcha_solution(&mut mac, solution);
401    Some(mac.finalize().into_bytes().into())
402}
403
404fn update_captcha_solution(mac: &mut Hmac<Sha256>, solution: &str) {
405    for character in solution.trim().chars().flat_map(char::to_lowercase) {
406        let mut bytes = [0_u8; 4];
407        mac.update(character.encode_utf8(&mut bytes).as_bytes());
408    }
409}
410
411/// Issues a rate-limited one-time challenge using an explicit policy.
412pub fn issue_captcha_challenge(
413    policy: &CaptchaPolicy,
414    security: &SecurityState,
415    client_key: impl Into<String>,
416    now: OffsetDateTime,
417) -> Result<CaptchaChallengeView, CaptchaIssueError> {
418    if policy.bypass {
419        return Ok(CaptchaChallengeView {
420            token: "debug-bypass".to_owned(),
421            image_data_url: String::new(),
422            length: DEFAULT_CAPTCHA_LENGTH as usize,
423            bypass: true,
424        });
425    }
426
427    let outcome = security
428        .captcha_issuance
429        .check(format!("captcha:issue:{}", client_key.into()));
430    if !outcome.allowed {
431        return Err(CaptchaIssueError::RateLimited);
432    }
433
434    let issued = policy.issue(DEFAULT_CAPTCHA_LENGTH, now)?;
435    let token = CaptchaToken::parse(Uuid::new_v4().to_string()).map_err(|error| {
436        tracing::error!(%error, "generated CAPTCHA token was rejected");
437        CaptchaIssueError::Generation
438    })?;
439    let length = issued.challenge.solution_length();
440    let image_data_url = issued.image_data_url;
441    policy
442        .nonces
443        .remember(token.clone(), issued.challenge, now)?;
444
445    Ok(CaptchaChallengeView {
446        token: token.0,
447        image_data_url,
448        length,
449        bypass: false,
450    })
451}
452
453#[cfg(test)]
454mod tests {
455    use std::num::NonZeroU32;
456
457    use ch_parsing::error::ParseErrorCode;
458    use time::{Duration, OffsetDateTime};
459
460    use super::{CaptchaConfig, CaptchaIssueError, CaptchaPolicy, issue_captcha_challenge};
461    use crate::ratelimit::SecurityState;
462
463    fn policy(bypass: bool) -> CaptchaPolicy {
464        CaptchaPolicy::from_config(&CaptchaConfig {
465            charset: "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".to_owned(),
466            noise_level: 0.1,
467            expires_after_secs: 60,
468            bypass,
469        })
470        .expect("test policy should build")
471    }
472
473    #[test]
474    fn issue_and_consume_are_policy_owned() {
475        let policy = policy(false);
476        let now = OffsetDateTime::now_utc();
477        let challenge = super::CaptchaChallenge {
478            solution_tag: super::captcha_solution_tag(&policy.verification_key[..], "ABCD")
479                .expect("valid verification key"),
480            solution_length: 4,
481            expires_at: now + Duration::seconds(60),
482        };
483        let token = policy.parse_token("opaque-token".to_owned()).unwrap();
484        policy
485            .nonces
486            .remember(token.clone(), challenge, now)
487            .unwrap();
488        let response = policy.parse_response("ABCD".to_owned()).unwrap();
489        policy.consume(&token, response, now).unwrap();
490
491        let replay = policy
492            .consume(
493                &token,
494                policy.parse_response("ABCD".to_owned()).unwrap(),
495                now,
496            )
497            .unwrap_err();
498        assert_eq!(replay.code(), ParseErrorCode::InvalidValue);
499        assert_eq!(replay.parameter("reason"), Some("missing_or_consumed"));
500    }
501
502    #[test]
503    fn issued_challenge_contains_png_data_url() {
504        let policy = policy(false);
505        let security = SecurityState::new(NonZeroU32::new(4).unwrap());
506        let challenge =
507            issue_captcha_challenge(&policy, &security, "client-1", OffsetDateTime::now_utc())
508                .unwrap();
509        assert!(
510            challenge
511                .image_data_url
512                .starts_with("data:image/png;base64,")
513        );
514        assert!(!challenge.token.is_empty());
515        assert!(!challenge.bypass);
516    }
517
518    #[test]
519    fn debug_bypass_is_explicit_and_redacted() {
520        let policy = policy(true);
521        let security = SecurityState::new(NonZeroU32::new(1).unwrap());
522        let challenge =
523            issue_captcha_challenge(&policy, &security, "client-1", OffsetDateTime::now_utc())
524                .unwrap();
525        assert!(challenge.bypass);
526        assert_eq!(challenge.token, "debug-bypass");
527        assert!(
528            issue_captcha_challenge(&policy, &security, "client-1", OffsetDateTime::now_utc())
529                .unwrap()
530                .bypass
531        );
532
533        let token = policy.parse_token(String::new()).unwrap();
534        let response = policy.parse_response(String::new()).unwrap();
535        assert!(format!("{token:?}").contains("REDACTED"));
536        assert!(format!("{response:?}").contains("REDACTED"));
537    }
538
539    #[test]
540    fn issuance_budget_is_enforced() {
541        let policy = policy(false);
542        let security = SecurityState::new(NonZeroU32::new(1).unwrap());
543        let now = OffsetDateTime::now_utc();
544        issue_captcha_challenge(&policy, &security, "client-1", now).unwrap();
545        assert!(matches!(
546            issue_captcha_challenge(&policy, &security, "client-1", now),
547            Err(CaptchaIssueError::RateLimited)
548        ));
549    }
550
551    #[test]
552    fn rejects_unsafe_generation_configuration() {
553        for charset in ["", "A", "AAAA", " A A "] {
554            let error = CaptchaPolicy::from_config(&CaptchaConfig {
555                charset: charset.to_owned(),
556                noise_level: 0.1,
557                expires_after_secs: 60,
558                bypass: false,
559            })
560            .expect_err("charset must contain at least two unique characters");
561            assert!(error.to_string().contains("two unique"));
562        }
563
564        for noise_level in [-0.1, 1.1, f32::INFINITY, f32::NAN] {
565            let error = CaptchaPolicy::from_config(&CaptchaConfig {
566                charset: "AB".to_owned(),
567                noise_level,
568                expires_after_secs: 60,
569                bypass: false,
570            })
571            .expect_err("noise outside the closed unit interval must fail");
572            assert!(error.to_string().contains("between zero and one"));
573        }
574    }
575
576    #[test]
577    fn token_and_response_limits_are_enforced() {
578        let policy = policy(false);
579        let token_error = policy
580            .parse_token("x".repeat(super::MAX_CAPTCHA_TOKEN_CHARS + 1))
581            .expect_err("oversized tokens must fail");
582        assert_eq!(token_error.code(), ParseErrorCode::TooLong);
583
584        let response_error = policy
585            .parse_response("x".repeat(super::MAX_CAPTCHA_RESPONSE_CHARS + 1))
586            .expect_err("oversized responses must fail");
587        assert_eq!(response_error.code(), ParseErrorCode::TooLong);
588    }
589}