ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! CSRF protection, compatible with axios / Inertia (they echo the `XSRF-TOKEN` cookie as `X-XSRF-TOKEN`).
//!
//! `App` enables this by default (`App::csrf_except`, `App::without_csrf`). The middleware must sit
//! inside the session layer. Forms that are not axios-driven send the token in an `X-CSRF-TOKEN` header.
//!
//! ```
//! use axum::{Router, middleware::from_fn_with_state, routing::post};
//! let router: Router = Router::new()
//!     .route("/hook", post(|| async { "ok" }))
//!     .layer(from_fn_with_state(ryuk::csrf::Csrf::new(&["/hook"]), ryuk::csrf::middleware))
//!     .layer(ryuk::session::session_layer());
//! ```
use axum::{
    extract::{Request, State},
    http::{HeaderMap, HeaderValue, Method, StatusCode, header},
    middleware::Next,
    response::{IntoResponse, Response},
};
use std::sync::Arc;
use subtle::ConstantTimeEq;
use tower_sessions::{
    Session,
    cookie::{Cookie, SameSite},
};

const KEY: &str = "csrf_token";

/// Middleware state: paths exempt from the check (exact, or prefix when ending in `*`).
#[derive(Clone, Debug, Default)]
pub struct Csrf {
    except: Arc<[String]>,
}

impl Csrf {
    /// Exempt `patterns`, e.g. `Csrf::new(&["/webhooks/*", "/ping"])`.
    pub fn new(patterns: &[&str]) -> Self {
        Csrf {
            except: patterns.iter().map(|p| p.to_string()).collect(),
        }
    }

    fn exempt(&self, path: &str) -> bool {
        self.except.iter().any(|p| match p.strip_suffix('*') {
            Some(prefix) => path.starts_with(prefix),
            None => p == path,
        })
    }
}

/// 32 random bytes as unpadded base64url.
fn new_token() -> String {
    const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let bytes: [u8; 32] = rand::random();
    let mut out = String::with_capacity(43);
    for c in bytes.chunks(3) {
        let n = c
            .iter()
            .enumerate()
            .fold(0u32, |n, (i, b)| n | (*b as u32) << (16 - 8 * i));
        for i in 0..=c.len() {
            out.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
        }
    }
    out
}

fn percent_decode(s: &str) -> String {
    let b = s.as_bytes();
    let (mut out, mut i) = (Vec::with_capacity(b.len()), 0);
    while i < b.len() {
        let hex = (b[i] == b'%' && i + 2 < b.len())
            .then(|| {
                std::str::from_utf8(&b[i + 1..i + 3])
                    .ok()
                    .and_then(|h| u8::from_str_radix(h, 16).ok())
            })
            .flatten();
        match hex {
            Some(v) => {
                out.push(v);
                i += 3;
            }
            None => {
                out.push(b[i]);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn wants_json(h: &HeaderMap) -> bool {
    h.contains_key("x-inertia")
        || h.get(header::ACCEPT)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.contains("json"))
}

fn presented(h: &HeaderMap) -> Option<String> {
    let get = |k| h.get(k).and_then(|v| v.to_str().ok());
    get("x-csrf-token")
        .map(str::to_owned)
        .or_else(|| get("x-xsrf-token").map(percent_decode))
}

/// The CSRF middleware; use with `axum::middleware::from_fn_with_state(Csrf::new(..), csrf::middleware)`.
pub async fn middleware(
    State(csrf): State<Csrf>,
    session: Session,
    req: Request,
    next: Next,
) -> Response {
    let token = match session.get::<String>(KEY).await {
        Ok(Some(t)) => t,
        Ok(None) => {
            let t = new_token();
            if session.insert(KEY, &t).await.is_err() {
                return StatusCode::INTERNAL_SERVER_ERROR.into_response();
            }
            t
        }
        Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    };
    let unsafe_method = !matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS);
    let ok = !unsafe_method
        || csrf.exempt(req.uri().path())
        || presented(req.headers()).is_some_and(|p| p.as_bytes().ct_eq(token.as_bytes()).into());
    let mut res = if ok {
        next.run(req).await
    } else if wants_json(req.headers()) {
        (
            StatusCode::from_u16(419).unwrap(),
            axum::Json(serde_json::json!({"message": "CSRF token mismatch."})),
        )
            .into_response()
    } else {
        (StatusCode::from_u16(419).unwrap(), "CSRF token mismatch.").into_response()
    };
    // A handler may rotate the token (login removes it): hand the client the CURRENT one on this very
    // response, or its next POST would carry the stale cookie and get a 419.
    let token = match session.get::<String>(KEY).await {
        Ok(Some(t)) => t,
        Ok(None) => {
            let t = new_token();
            let _ = session.insert(KEY, &t).await;
            t
        }
        Err(_) => token,
    };
    // Not HttpOnly on purpose: axios/Inertia read it from JS.
    let cookie = Cookie::build(("XSRF-TOKEN", token))
        .path("/")
        .same_site(SameSite::Lax)
        .secure(std::env::var("APP_ENV").is_ok_and(|v| v == "production"))
        .build();
    if let Ok(v) = HeaderValue::from_str(&cookie.to_string()) {
        res.headers_mut().append(header::SET_COOKIE, v);
    }
    res
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        Router,
        body::Body,
        http::Request,
        middleware::from_fn_with_state,
        routing::{get, post},
    };
    use tower::ServiceExt;

    fn app() -> Router {
        Router::new()
            .route("/", get(|| async { "hi" }).post(|| async { "posted" }))
            .route("/hook/x", post(|| async { "hook" }))
            .layer(from_fn_with_state(Csrf::new(&["/hook/*"]), middleware))
            .layer(crate::session::session_layer())
    }

    #[tokio::test]
    async fn a_token_rotated_by_a_handler_reaches_the_client_on_the_same_response() {
        use tower_sessions::Session;
        let app = Router::new()
            .route("/", get(|| async { "hi" }).post(|| async { "posted" }))
            // What `auth::login` does: drop the token so a fresh one is minted.
            .route(
                "/login",
                post(|s: Session| async move {
                    s.remove::<String>(KEY).await.unwrap();
                    "in"
                }),
            )
            .layer(from_fn_with_state(Csrf::new(&[]), middleware))
            .layer(crate::session::session_layer());
        let (sess, old) = bootstrap(&app).await;
        let post_with = |uri: &'static str, token: String, sess: String| {
            let app = app.clone();
            async move {
                app.oneshot(
                    Request::post(uri)
                        .header(header::COOKIE, sess)
                        .header("x-xsrf-token", token)
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap()
            }
        };
        let res = post_with("/login", old.clone(), sess.clone()).await;
        assert_eq!(res.status(), 200);
        let new = res
            .headers()
            .get_all(header::SET_COOKIE)
            .iter()
            .filter_map(|v| Cookie::parse(v.to_str().unwrap().to_owned()).ok())
            .find(|c| c.name() == "XSRF-TOKEN")
            .map(|c| c.value().to_owned())
            .expect("the login response must carry the rotated token");
        assert_ne!(new, old);
        // The very next POST with the cookie from that response works; the old token is dead.
        assert_eq!(post_with("/", new, sess.clone()).await.status(), 200);
        assert_eq!(post_with("/", old, sess).await.status(), 419);
    }

    /// (session cookie, xsrf token) from a GET.
    async fn bootstrap(app: &Router) -> (String, String) {
        let res = app
            .clone()
            .oneshot(Request::get("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(res.status(), 200);
        let mut sess = String::new();
        let mut xsrf = String::new();
        for v in res.headers().get_all(header::SET_COOKIE) {
            let c = Cookie::parse(v.to_str().unwrap().to_owned()).unwrap();
            if c.name() == "XSRF-TOKEN" {
                assert_eq!(c.http_only(), None, "must be readable from JS");
                assert_eq!(c.path(), Some("/"));
                xsrf = c.value().to_owned();
            } else {
                sess = format!("{}={}", c.name(), c.value());
            }
        }
        assert_eq!(xsrf.len(), 43);
        (sess, xsrf)
    }

    async fn post_with(
        app: &Router,
        uri: &str,
        sess: &str,
        hdr: Option<(&str, &str)>,
    ) -> StatusCode {
        let mut r = Request::post(uri).header(header::COOKIE, sess);
        if let Some((k, v)) = hdr {
            r = r.header(k, v);
        }
        app.clone()
            .oneshot(r.body(Body::empty()).unwrap())
            .await
            .unwrap()
            .status()
    }

    #[tokio::test]
    async fn token_checks() {
        let app = app();
        let (sess, xsrf) = bootstrap(&app).await;
        assert_eq!(post_with(&app, "/", &sess, None).await, 419);
        assert_eq!(
            post_with(&app, "/", &sess, Some(("x-xsrf-token", "wrong"))).await,
            419
        );
        assert_eq!(
            post_with(&app, "/", &sess, Some(("x-xsrf-token", &xsrf))).await,
            200
        );
        assert_eq!(
            post_with(&app, "/", &sess, Some(("x-csrf-token", &xsrf))).await,
            200
        );
        // exempt prefix needs no token; a different path under another prefix still does
        assert_eq!(post_with(&app, "/hook/x", &sess, None).await, 200);
        // a token from another session is rejected
        let (_, other) = bootstrap(&app).await;
        assert_eq!(
            post_with(&app, "/", &sess, Some(("x-xsrf-token", &other))).await,
            419
        );
    }

    #[tokio::test]
    async fn json_body_for_inertia() {
        let app = app();
        let (sess, _) = bootstrap(&app).await;
        let res = app
            .oneshot(
                Request::post("/")
                    .header(header::COOKIE, &sess)
                    .header("x-inertia", "true")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), 419);
        let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
        assert_eq!(&body[..], br#"{"message":"CSRF token mismatch."}"#);
    }

    #[test]
    fn helpers() {
        assert_eq!(percent_decode("a%2Bb%3D"), "a+b=");
        assert_eq!(percent_decode("100%"), "100%");
        assert_ne!(new_token(), new_token());
        assert!(
            new_token()
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        );
        let c = Csrf::new(&["/a", "/w/*"]);
        assert!(c.exempt("/a") && c.exempt("/w/x") && !c.exempt("/ab") && !c.exempt("/b"));
    }
}