glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Keeping bots off public forms, such as signing up, without a puzzle for
//! people: `{{ spam_trap() }}` in the form adds a field people never see
//! (bots fill in every field) and the time the form was shown, signed;
//! `glacier::spam::check(&params)?` in the action refuses the form with
//! `422` when the hidden field has text, the time is missing or forged, or
//! the form came back sooner than a person could fill it in.
//!
//! In tests, which post forms without loading them, only the hidden field
//! is checked.

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use hmac::{Hmac, Mac};
use sha2::Sha256;

use crate::config::Env;
use crate::context::Params;
use crate::{Error, Result};

/// The field people never see, named as a bot would want to fill it.
pub const HONEYPOT: &str = "website";
/// When the form was shown, and its signature.
pub const SHOWN_AT: &str = "_shown_at";
/// How soon after it's shown a form may come back.
const MIN_SECONDS: i64 = 2;
/// How long after it's shown a form may still come back.
const MAX_SECONDS: i64 = 24 * 60 * 60;

/// The hidden fields for a form: `{{ spam_trap() }}`.
pub fn trap_html() -> String {
    let shown = crate::time::now().timestamp().to_string();
    format!(
        r#"<div style="position:absolute;left:-10000px" aria-hidden="true"><label>Leave this empty <input type="text" name="{HONEYPOT}" value="" tabindex="-1" autocomplete="off"></label></div><input type="hidden" name="{SHOWN_AT}" value="{shown}.{}">"#,
        signature(&shown)
    )
}

/// Refuses a form a bot sent: see the module docs.
///
/// # Errors
///
/// `422 Unprocessable Entity` for spam.
pub fn check(params: &Params) -> Result<()> {
    check_at(
        params,
        crate::time::now().timestamp(),
        // The app's environment (its tests load the test config), else the
        // process's.
        !matches!(
            crate::Config::current().map_or_else(|_| Env::current(), |config| config.env()),
            Env::Test
        ),
    )
}

fn check_at(params: &Params, now: i64, timed: bool) -> Result<()> {
    let refuse =
        || Error::unprocessable("That looked automated. Please wait a moment and try again.");
    if params.get(HONEYPOT).is_some_and(|v| !v.trim().is_empty()) {
        return Err(refuse());
    }
    if !timed {
        return Ok(());
    }
    let shown = params
        .get(SHOWN_AT)
        .and_then(|value| value.split_once('.'))
        .filter(|(shown, signed)| constant_time_eq(signature(shown).as_bytes(), signed.as_bytes()))
        .and_then(|(shown, _)| shown.parse::<i64>().ok())
        .ok_or_else(refuse)?;
    let age = now - shown;
    if !(MIN_SECONDS..=MAX_SECONDS).contains(&age) {
        return Err(refuse());
    }
    Ok(())
}

fn signature(shown: &str) -> String {
    let key = crate::request::signing_key();
    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key.signing()).expect("HMAC takes any key");
    mac.update(b"glacier spam trap|");
    mac.update(shown.as_bytes());
    URL_SAFE_NO_PAD.encode(&mac.finalize().into_bytes()[..16])
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

#[cfg(test)]
mod tests {
    use super::*;

    fn params(fields: &[(&str, &str)]) -> Params {
        fields.iter().copied().collect()
    }

    fn shown_field(html: &str) -> String {
        let start =
            html.find(&format!("name=\"{SHOWN_AT}\" value=\"")).unwrap() + SHOWN_AT.len() + 15;
        html[start..start + html[start..].find('"').unwrap()].to_owned()
    }

    #[test]
    fn refuses_bots_and_lets_people_through() {
        let now = crate::time::now().timestamp();
        let shown = shown_field(&trap_html());

        // A person, a few seconds later.
        let person = params(&[(SHOWN_AT, &shown), (HONEYPOT, "")]);
        assert!(check_at(&person, now + 5, true).is_ok());
        // Too quick, or a day too late.
        assert!(check_at(&person, now, true).is_err());
        assert!(check_at(&person, now + MAX_SECONDS + 1, true).is_err());
        // The hidden field filled in, as bots fill every field.
        let filled = params(&[(SHOWN_AT, &shown), (HONEYPOT, "http://spam.example")]);
        assert!(check_at(&filled, now + 5, true).is_err());
        assert!(check_at(&filled, now + 5, false).is_err(), "even in tests");
        // No time, or a forged one.
        assert!(check_at(&params(&[]), now + 5, true).is_err());
        assert!(
            check_at(&params(&[]), now + 5, false).is_ok(),
            "tests post directly"
        );
        let forged = format!("{}.{}", now - 60, shown.split_once('.').unwrap().1);
        assert!(check_at(&params(&[(SHOWN_AT, &forged)]), now, true).is_err());
    }
}