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;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CaptchaChallengeView {
pub token: String,
pub image_data_url: String,
pub length: usize,
pub bypass: bool,
}
#[derive(Clone, Debug)]
pub struct CaptchaConfig {
pub charset: String,
pub noise_level: f32,
pub expires_after_secs: u64,
pub bypass: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CaptchaConfigError {
#[error("captcha charset must include at least two unique non-whitespace characters")]
InsufficientCharset,
#[error("captcha noise level must be finite and between zero and one")]
InvalidNoiseLevel,
#[error("captcha expiry exceeds the supported duration")]
ExpiryOutOfRange,
#[error("captcha expiry must be greater than zero")]
NonPositiveExpiry,
#[error("captcha bypass is unavailable in release builds")]
BypassUnavailable,
#[error("captcha verification key generation failed")]
VerificationKeyGeneration,
}
#[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 {
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),
})
}
#[must_use]
pub const fn bypass(&self) -> bool {
self.bypass
}
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)
}
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)
}
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)),
})
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CaptchaIssueError {
#[error("captcha.rate_limited")]
RateLimited,
#[error("captcha.capacity_exceeded")]
CapacityExceeded,
#[error("captcha.generation_failed")]
Generation,
}
#[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()
}
}
#[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))
}
#[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());
}
}
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);
}
}