laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};

use serde::Serialize;

use crate::contracts::CaptchaDriver;
use crate::drivers::{RecaptchaV2Driver, RecaptchaV3Driver, TurnstileDriver};
use crate::result::VerificationResult;
use crate::support::config;
use crate::testing::FakeDriver;

type Creator = Arc<dyn Fn() -> Arc<dyn CaptchaDriver> + Send + Sync>;

#[derive(Default)]
struct State {
    drivers: Mutex<HashMap<String, Arc<dyn CaptchaDriver>>>,
    creators: Mutex<HashMap<String, Creator>>,
}

/// What the React, Vue and Svelte components need to draw the widget, for a front end that is not
/// MiniJinja. Pass it to the page (an Inertia prop, for example) and spread it on the component:
/// the same values the `laracaptcha_widget()` function works out for itself.
///
/// It serializes with the keys the components expect: `provider`, `siteKey`, `script`, `field`
/// and `action`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Props {
    /// The driver name, such as `turnstile`.
    pub provider: String,
    /// The public site key.
    pub site_key: String,
    /// The provider's script, with the site key reCAPTCHA v3 needs in its address. Empty for the
    /// fake, which is how the widgets know to draw nothing.
    pub script: String,
    /// The name of the field carrying the token.
    pub field: String,
    /// The action to tag the token with.
    pub action: Option<String>,
}

/// Resolves and caches the configured captcha drivers.
///
/// `laracaptcha::driver(None)` gives the default from `default` in the configuration,
/// `laracaptcha::driver(Some("recaptcha_v2"))` gives a named one, and each driver is built once and
/// reused. It is a container singleton, so a handler can take an `Inject<CaptchaManager>`, and the
/// free functions of the crate root resolve it for you.
#[derive(Clone, Default)]
pub struct CaptchaManager {
    state: Arc<State>,
}

impl CaptchaManager {
    /// A manager with the three drivers that ship with the package.
    pub fn new() -> Self {
        Self::default()
    }

    /// Driver used when none is named, from `default` in the configuration.
    pub fn default_driver(&self) -> String {
        config().default
    }

    /// Register a driver of your own under a name. It replaces a driver with the same name, shipped
    /// or not, and the closure decides where its credentials come from.
    pub fn extend<D: CaptchaDriver + 'static>(
        &self,
        name: impl Into<String>,
        creator: impl Fn() -> D + Send + Sync + 'static,
    ) {
        let name = name.into();

        self.state
            .drivers
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&name);

        self.state
            .creators
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(name, Arc::new(move || Arc::new(creator()) as Arc<dyn CaptchaDriver>));
    }

    /// The named driver, or the default one when `None`.
    ///
    /// # Errors
    ///
    /// Fails when no driver is registered or shipped under that name.
    pub fn driver(&self, name: Option<&str>) -> laravel::Result<Arc<dyn CaptchaDriver>> {
        let name = name.map_or_else(|| self.default_driver(), str::to_owned);

        if let Some(driver) = self
            .state
            .drivers
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&name)
        {
            return Ok(Arc::clone(driver));
        }

        let creator = self
            .state
            .creators
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&name)
            .cloned();

        let driver = match creator {
            Some(creator) => creator(),
            None => Self::create(&name)?,
        };

        self.state
            .drivers
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(name, Arc::clone(&driver));

        Ok(driver)
    }

    fn create(name: &str) -> laravel::Result<Arc<dyn CaptchaDriver>> {
        let drivers = config().drivers;

        Ok(match name {
            "turnstile" => Arc::new(TurnstileDriver::new(drivers.turnstile)),
            "recaptcha_v2" => Arc::new(RecaptchaV2Driver::new(drivers.recaptcha_v2)),
            "recaptcha_v3" => Arc::new(RecaptchaV3Driver::new(drivers.recaptcha_v3)),
            other => return Err(laravel::Error::msg(format!("Driver [{other}] not supported."))),
        })
    }

    /// Verify a token with the default driver.
    ///
    /// # Errors
    ///
    /// Fails when the configured default driver does not exist. A refused token is not an error:
    /// it is a failed [`VerificationResult`].
    pub async fn verify(&self, token: &str, ip: Option<&str>) -> laravel::Result<VerificationResult> {
        Ok(self.driver(None)?.verify(token, ip).await)
    }

    /// The public site key of the default driver.
    ///
    /// # Errors
    ///
    /// Fails when the configured default driver does not exist.
    pub fn site_key(&self) -> laravel::Result<String> {
        Ok(self.driver(None)?.site_key())
    }

    /// The script url of the default driver.
    ///
    /// # Errors
    ///
    /// Fails when the configured default driver does not exist.
    pub fn script_url(&self) -> laravel::Result<String> {
        Ok(self.driver(None)?.script_url())
    }

    /// The name of the field carrying the token, for the default driver.
    ///
    /// # Errors
    ///
    /// Fails when the configured default driver does not exist.
    pub fn response_field(&self) -> laravel::Result<String> {
        Ok(self.driver(None)?.response_field())
    }

    /// What the front end components need to draw the widget.
    ///
    /// `action` is the action to tag the token with; reCAPTCHA v3 defaults to `submit`.
    ///
    /// # Errors
    ///
    /// Fails when the driver does not exist.
    pub fn props(&self, driver: Option<&str>, action: Option<&str>) -> laravel::Result<Props> {
        let captcha = self.driver(driver)?;

        Ok(Props {
            provider: captcha.name().to_owned(),
            site_key: captcha.site_key(),
            script: Self::script(captcha.as_ref()),
            field: captcha.response_field(),
            action: Self::action(captcha.as_ref(), action),
        })
    }

    /// The action a widget tags its token with: reCAPTCHA v3 defaults to `submit`, and the other
    /// drivers only have one when it is given.
    pub(crate) fn action(captcha: &dyn CaptchaDriver, action: Option<&str>) -> Option<String> {
        if captcha.name() == "recaptcha_v3" {
            Some(action.unwrap_or("submit").to_owned())
        } else {
            action.map(str::to_owned)
        }
    }

    /// The provider's script, with the site key reCAPTCHA v3 needs in its address. Empty for the
    /// fake, which is how the widgets know to draw nothing.
    pub fn script(captcha: &dyn CaptchaDriver) -> String {
        let url = captcha.script_url();

        if url.is_empty() || captcha.name() != "recaptcha_v3" {
            return url;
        }

        format!("{url}?render={}", urlencode(&captcha.site_key()))
    }

    /// Replace every driver with a fake for testing. No HTTP calls are made; verifications succeed
    /// (or fail) as configured and attempts are recorded.
    ///
    /// Every shipped driver name, every name registered with [`extend`](Self::extend) and the
    /// default one is pointed at the SAME fake, so a test that fakes once covers code that asks for
    /// a driver by name. The returned instance is the one to assert against.
    pub fn fake(&self, success: bool, score: Option<f64>) -> FakeDriver {
        let fake = FakeDriver::new(success, score);
        let driver: Arc<dyn CaptchaDriver> = Arc::new(fake.clone());

        let mut names = vec![
            "turnstile".to_owned(),
            "recaptcha_v2".to_owned(),
            "recaptcha_v3".to_owned(),
        ];

        names.extend(
            self.state
                .creators
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .keys()
                .cloned(),
        );
        names.push(self.default_driver());

        let mut drivers = self.state.drivers.lock().unwrap_or_else(PoisonError::into_inner);

        for name in names {
            drivers.insert(name, Arc::clone(&driver));
        }

        fake
    }
}

/// PHP's `urlencode`: everything but letters, digits, `-`, `_` and `.` is percent-encoded, and a
/// space is a `+`.
fn urlencode(text: &str) -> String {
    let mut encoded = String::with_capacity(text.len());

    for byte in text.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => encoded.push(char::from(byte)),
            b' ' => encoded.push('+'),
            other => encoded.push_str(&format!("%{other:02X}")),
        }
    }

    encoded
}