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
//! Default hardening layers: security headers, body limit, timeout, panic catching, request ids.
use axum::{
    Router,
    extract::{DefaultBodyLimit, Request, State},
    http::{HeaderName, HeaderValue, StatusCode},
    middleware::{Next, from_fn_with_state},
    response::Response,
};
use std::time::Duration;
use tower_http::{
    catch_panic::CatchPanicLayer,
    limit::RequestBodyLimitLayer,
    request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer},
    timeout::TimeoutLayer,
    trace::TraceLayer,
};

/// Knobs behind `App::hsts`, `csp`, `body_limit`, `timeout`.
#[derive(Clone)]
pub(crate) struct Hardening {
    pub hsts: bool,
    pub csp: Option<HeaderValue>,
    pub body_limit: usize,
    pub timeout: Duration,
}

impl Default for Hardening {
    fn default() -> Self {
        Hardening {
            hsts: true,
            csp: None,
            body_limit: 1024 * 1024,
            timeout: Duration::from_secs(30),
        }
    }
}

/// True when `APP_ENV=production`.
pub(crate) fn is_production() -> bool {
    std::env::var("APP_ENV").is_ok_and(|v| v == "production")
}

#[derive(Clone)]
struct Headers(Vec<(HeaderName, HeaderValue)>);

async fn set_headers(State(h): State<Headers>, req: Request, next: Next) -> Response {
    let mut res = next.run(req).await;
    for (k, v) in &h.0 {
        // a handler's own value wins
        res.headers_mut().entry(k).or_insert_with(|| v.clone());
    }
    res
}

/// Wraps `router`, outermost first: request id, tracing span carrying it, headers, panic catch, timeout, body limit.
pub(crate) fn harden(router: Router, h: &Hardening, production: bool) -> Router {
    let mut hs = vec![
        ("x-content-type-options", "nosniff"),
        ("x-frame-options", "DENY"),
        ("referrer-policy", "strict-origin-when-cross-origin"),
        (
            "permissions-policy",
            "camera=(), microphone=(), geolocation=()",
        ),
        ("cross-origin-opener-policy", "same-origin"),
    ];
    if production && h.hsts {
        hs.push((
            "strict-transport-security",
            "max-age=31536000; includeSubDomains",
        ));
    }
    let mut hs: Vec<_> = hs
        .into_iter()
        .map(|(k, v)| (HeaderName::from_static(k), HeaderValue::from_static(v)))
        .collect();
    if let Some(csp) = &h.csp {
        hs.push((
            HeaderName::from_static("content-security-policy"),
            csp.clone(),
        ));
    }
    router
        // axum extractors (Bytes, Form, Multipart) carry their own 2 MiB default; without this a larger
        // `body_limit` would still be cut at 2 MiB inside the handler.
        .layer(DefaultBodyLimit::max(h.body_limit))
        .layer(RequestBodyLimitLayer::new(h.body_limit))
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            h.timeout,
        ))
        .layer(CatchPanicLayer::new())
        .layer(from_fn_with_state(Headers(hs), set_headers))
        .layer(TraceLayer::new_for_http().make_span_with(|r: &Request| {
            let id = r
                .headers()
                .get("x-request-id")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("-");
            tracing::info_span!("request", method = %r.method(), path = %loggable_path(r.uri().path()), request_id = %id)
        }))
        .layer(PropagateRequestIdLayer::x_request_id())
        .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
}

/// Path for the tracing span: the segment after `/verify-email/` and `/reset-password/` is a secret
/// token, and the query string (OAuth `?code=`) is never logged.
pub(crate) fn loggable_path(path: &str) -> String {
    let mut prev = "";
    path.split('/')
        .map(|seg| {
            let out = if matches!(prev, "verify-email" | "reset-password") {
                "[redacted]"
            } else {
                seg
            };
            prev = seg;
            out
        })
        .collect::<Vec<_>>()
        .join("/")
}

#[cfg(test)]
mod tests {
    use super::loggable_path as p;

    #[test]
    fn span_path_hides_tokens() {
        assert_eq!(p("/verify-email/abc123"), "/verify-email/[redacted]");
        assert_eq!(p("/reset-password/abc123"), "/reset-password/[redacted]");
        assert_eq!(p("/reset-password"), "/reset-password");
        assert_eq!(p("/posts/1"), "/posts/1");
        assert_eq!(p("/"), "/");
    }
}