laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use laravel::time::ToSpan;
use laravel::validation::{Field, RuleError, ValidationRule};
use serde_json::{Map, Value};

use crate::manager::CaptchaManager;
use crate::result::VerificationResult;
use crate::support::{config, token_key};

/// Validation rule that checks a captcha token.
///
/// ```ignore
/// #[derive(serde::Deserialize, Validate)]
/// #[validate(anyone)]
/// struct SignUp {
///     #[serde(rename = "cf-turnstile-response")]
///     #[validate(required, Captcha::new())]
///     captcha: String,
/// }
/// ```
///
/// On top of asking the driver, the rule enforces single use: a token that has already passed is
/// refused for the next `reuse_ttl` minutes, so a token captured from one submission cannot be
/// replayed into another. Turn it off with `prevent_reuse` if your provider already does this.
///
/// The four failure messages are `messages` in the configuration. Which one the visitor sees is
/// deliberately coarse, since naming the exact reason would help whoever is probing the form. The
/// provider's own error codes can go to the log instead, where only you read them, but that is
/// **off unless `log_failures` turns it on**: a rule should decide, not leave records nobody asked
/// for.
///
/// The rule asks the provider, so it is async: Laravel Rust awaits a field's rules one at a time.
#[derive(Debug, Clone, Default)]
pub struct Captcha {
    driver: Option<String>,
    action: Option<String>,
}

impl Captcha {
    /// The rule for the default driver, with no action.
    pub fn new() -> Self {
        Self::default()
    }

    /// Named constructor, as PHP's `Captcha::make($driver, $action)`.
    ///
    /// A `None` driver means the configured default, which is what you want unless a specific form
    /// uses a different provider. The action must match the one the widget was rendered with, and
    /// only providers that stamp their tokens with it (Turnstile, reCAPTCHA v3) can act on it: for
    /// the others it is quietly ignored, since they have nothing to compare against.
    pub fn make(driver: Option<&str>, action: Option<&str>) -> Self {
        Self {
            driver: driver.map(str::to_owned),
            action: action.map(str::to_owned),
        }
    }

    /// Leave the provider's reason for refusing in the log, when asked to.
    fn report(driver: &str, result: &VerificationResult, ip: Option<&str>) {
        let settings = config();

        if !settings.log_failures {
            return;
        }

        tracing::warn!(
            target: "laracaptcha",
            context = %failure_context(driver, result, ip),
            "Captcha verification failed"
        );
    }
}

/// What the log line carries: the driver, the provider's codes (or `none-reported`), the score,
/// the IP and the hostname the token was solved on. Absent values are left out.
pub fn failure_context(driver: &str, result: &VerificationResult, ip: Option<&str>) -> Value {
    let mut context = Map::new();

    context.insert("driver".to_owned(), Value::from(driver));
    context.insert(
        "errors".to_owned(),
        if result.error_codes.is_empty() {
            Value::from(vec!["none-reported"])
        } else {
            Value::from(result.error_codes.clone())
        },
    );

    if let Some(score) = result.score {
        context.insert("score".to_owned(), Value::from(score));
    }

    if let Some(ip) = ip {
        context.insert("ip".to_owned(), Value::from(ip));
    }

    if let Some(hostname) = result.raw.get("hostname").filter(|hostname| !hostname.is_null()) {
        context.insert("hostname".to_owned(), hostname.clone());
    }

    Value::Object(context)
}

impl ValidationRule for Captcha {
    /// Five ways to fail, in order: the field is empty, the token was already spent, the token was
    /// minted for a different action, the provider refused it, or the provider could not be reached
    /// (which the driver reports as a refusal). Only on success is the token recorded as spent, so a
    /// provider outage does not burn valid tokens.
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        let settings = config();

        let Some(token) = field
            .value
            .and_then(|value| value.as_str())
            .filter(|token| !token.trim().is_empty())
        else {
            return Err(field.reject(settings.messages.required));
        };

        let key = token_key(token);
        let ip = field
            .request("laracaptcha")
            .ok()
            .map(|request| request.ip().to_string());

        if settings.prevent_reuse && laravel::cache::has(&key).await? {
            Self::report(
                self.driver.as_deref().unwrap_or(&settings.default),
                &VerificationResult::failure("already-used"),
                ip.as_deref(),
            );

            return Err(field.reject(settings.messages.used));
        }

        let manager = laravel::resolve::<CaptchaManager>().await?;
        let mut driver = manager.driver(self.driver.as_deref())?;

        if let Some(action) = self.action.as_deref()
            && let Some(bound) = driver.expecting_action(Some(action))
        {
            driver = bound;
        }

        let result = driver.verify(token, ip.as_deref()).await;

        if result.failed() {
            Self::report(driver.name(), &result, ip.as_deref());

            // An outage is worth saying out loud: "try again in a moment" is true and actionable,
            // while "verification failed" sends the visitor looking for a mistake they did not make.
            return Err(field.reject(if result.has_error("unreachable") {
                settings.messages.unreachable
            } else {
                settings.messages.invalid
            }));
        }

        if settings.prevent_reuse {
            laravel::cache::put(&key, true, (settings.reuse_ttl as i64).minutes()).await?;
        }

        Ok(())
    }
}