glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Cross-site request forgery protection.
//!
//! `Csrf` rejects unsafe requests (POST, PUT, PATCH, DELETE) unless they
//! carry the session's token, either in the `x-csrf-token` header or the
//! `_csrf_token` form field. Render the field with
//! `glacier::html::csrf_field(&ctx.csrf_token())`.

use http::{Method, StatusCode};

use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;
use crate::session::Session;

pub const FORM_FIELD: &str = "_csrf_token";
pub const HEADER: &str = "x-csrf-token";
const SESSION_KEY: &str = "_csrf_token";

pub struct Csrf;

impl Middleware for Csrf {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            if is_safe(ctx.method()) {
                return next.run(ctx).await;
            }
            let expected: Option<String> = ctx.session().get(SESSION_KEY);
            let provided = ctx
                .header(HEADER)
                .map(str::to_owned)
                .or_else(|| ctx.form_field(FORM_FIELD));
            match (expected, provided) {
                (Some(expected), Some(provided))
                    if constant_time_eq(expected.as_bytes(), provided.as_bytes()) =>
                {
                    next.run(ctx).await
                }
                _ => Response::text("Invalid CSRF token").with_status(StatusCode::FORBIDDEN),
            }
        })
    }
}

/// The session's CSRF token, created on first use.
pub(crate) fn token_for(session: &Session) -> String {
    if let Some(token) = session.get::<String>(SESSION_KEY) {
        return token;
    }
    let token = crate::random::token();
    // Inserting a String into a JSON map cannot fail.
    let _ = session.insert(SESSION_KEY, &token);
    token
}

fn is_safe(method: &Method) -> bool {
    matches!(
        *method,
        Method::GET | Method::HEAD | Method::OPTIONS | Method::TRACE
    )
}

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::*;

    #[test]
    fn compares_in_constant_time() {
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"ab"));
    }
}