use crate::context::Context;
use crate::error::Result;
use crate::middleware::{InboundAction, InboundMiddleware};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct CsrfConfig {
pub exempt_routes: Vec<String>,
pub protected_methods: HashSet<String>,
pub enabled: bool,
pub error_message: String,
pub redirect_on_failure: Option<String>,
pub flash_error_key: String,
}
impl Default for CsrfConfig {
fn default() -> Self {
let mut protected_methods = HashSet::new();
protected_methods.insert("POST".to_string());
protected_methods.insert("PUT".to_string());
protected_methods.insert("PATCH".to_string());
protected_methods.insert("DELETE".to_string());
Self {
exempt_routes: vec![],
protected_methods,
enabled: true,
error_message: "CSRF token validation failed. Please try again.".to_string(),
redirect_on_failure: None,
flash_error_key: "error_msg".to_string(),
}
}
}
impl CsrfConfig {
pub fn new() -> Self {
Self::default()
}
pub fn exempt<S: Into<String>>(mut self, route: S) -> Self {
self.exempt_routes.push(route.into());
self
}
pub fn error_message<S: Into<String>>(mut self, message: S) -> Self {
self.error_message = message.into();
self
}
pub fn redirect_on_failure<S: Into<String>>(mut self, url: S) -> Self {
self.redirect_on_failure = Some(url.into());
self
}
pub fn disabled(mut self) -> Self {
self.enabled = false;
self
}
pub fn protect_method<S: Into<String>>(mut self, method: S) -> Self {
self.protected_methods.insert(method.into().to_uppercase());
self
}
pub fn exempt_method<S: Into<String>>(mut self, method: S) -> Self {
self.protected_methods.remove(&method.into().to_uppercase());
self
}
}
#[derive(Clone)]
pub struct CsrfMiddleware {
config: CsrfConfig,
}
impl CsrfMiddleware {
pub fn new() -> Self {
Self {
config: CsrfConfig::default(),
}
}
pub fn with_config(config: CsrfConfig) -> Self {
Self { config }
}
pub fn from_config() -> Self {
use crate::configuration::CONF;
let mut config = CsrfConfig::default();
if let Some(exempt_routes) = CONF::get::<Vec<String>>("middleware.csrf.exempt_routes") {
config.exempt_routes = exempt_routes;
}
if let Some(error_message) = CONF::get::<String>("middleware.csrf.error_message") {
config.error_message = error_message;
}
if let Some(redirect_url) = CONF::get::<String>("middleware.csrf.redirect_on_failure") {
config.redirect_on_failure = Some(redirect_url);
}
if let Some(enabled) = CONF::get("middleware.csrf.enabled") {
config.enabled = enabled;
}
if let Some(flash_key) = CONF::get::<String>("middleware.csrf.flash_error_key") {
config.flash_error_key = flash_key;
}
Self::with_config(config)
}
fn requires_protection(&self, method: &str) -> bool {
self.config
.protected_methods
.contains(&method.to_uppercase())
}
fn is_route_exempt(&self, path: &str) -> bool {
for exempt_pattern in &self.config.exempt_routes {
if self.matches_pattern(path, exempt_pattern) {
return true;
}
}
false
}
fn matches_pattern(&self, path: &str, pattern: &str) -> bool {
if let Some(prefix) = pattern.strip_suffix("/*") {
if let Some(remaining) = path.strip_prefix(prefix) {
remaining.starts_with('/') || remaining.is_empty()
} else {
false
}
} else if pattern.contains('*') {
false
} else {
path == pattern
}
}
fn handle_csrf_failure(&self, ctx: &mut Context) -> Result<InboundAction> {
let _ = ctx.flash(
&self.config.flash_error_key,
self.config.error_message.as_str(),
);
if let Some(redirect_url) = &self.config.redirect_on_failure {
ctx.redirect(redirect_url)?;
} else {
let is_api_request = ctx
.header("accept")
.map(|accept| accept.contains("application/json"))
.unwrap_or(false)
|| ctx
.header("content-type")
.map(|ct| ct.contains("application/json"))
.unwrap_or(false);
if is_api_request {
ctx.json(json!({
"error": "csrf_token_invalid",
"message": self.config.error_message
}))?;
} else {
ctx.throw403(Some(&self.config.error_message))?;
}
}
Ok(InboundAction::Stop)
}
}
impl Default for CsrfMiddleware {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InboundMiddleware for CsrfMiddleware {
async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
if !self.config.enabled {
return Ok(InboundAction::Continue);
}
if !self.requires_protection(&ctx.req.method) {
return Ok(InboundAction::Continue);
}
if self.is_route_exempt(ctx.path()) {
return Ok(InboundAction::Continue);
}
if !ctx.verify_csrf(None)? {
return self.handle_csrf_failure(ctx);
}
Ok(InboundAction::Continue)
}
fn name(&self) -> &'static str {
"csrf"
}
fn priority(&self) -> i32 {
-25 }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_csrf_config_default() {
let config = CsrfConfig::default();
assert!(config.enabled);
assert!(config.protected_methods.contains("POST"));
assert!(config.protected_methods.contains("PUT"));
assert!(config.protected_methods.contains("PATCH"));
assert!(config.protected_methods.contains("DELETE"));
assert!(!config.protected_methods.contains("GET"));
assert!(config.exempt_routes.is_empty());
}
#[test]
fn test_csrf_config_builder() {
let config = CsrfConfig::new()
.exempt("/webhook/*")
.exempt("/public/upload")
.error_message("Custom error")
.redirect_on_failure("/login")
.protect_method("CUSTOM")
.exempt_method("DELETE");
assert!(config.exempt_routes.contains(&"/webhook/*".to_string()));
assert!(config.exempt_routes.contains(&"/public/upload".to_string()));
assert_eq!(config.error_message, "Custom error");
assert_eq!(config.redirect_on_failure, Some("/login".to_string()));
assert!(config.protected_methods.contains("CUSTOM"));
assert!(!config.protected_methods.contains("DELETE"));
}
#[test]
fn test_pattern_matching() {
let middleware = CsrfMiddleware::new();
assert!(middleware.matches_pattern("/api/users", "/api/*"));
assert!(middleware.matches_pattern("/api/v1/posts", "/api/*"));
assert!(!middleware.matches_pattern("/public/api", "/api/*"));
assert!(middleware.matches_pattern("/webhook", "/webhook"));
assert!(!middleware.matches_pattern("/webhooks", "/webhook"));
}
#[test]
fn test_requires_protection() {
let middleware = CsrfMiddleware::new();
assert!(middleware.requires_protection("POST"));
assert!(middleware.requires_protection("put")); assert!(middleware.requires_protection("PATCH"));
assert!(middleware.requires_protection("DELETE"));
assert!(!middleware.requires_protection("GET"));
assert!(!middleware.requires_protection("HEAD"));
assert!(!middleware.requires_protection("OPTIONS"));
assert!(!middleware.requires_protection("TRACE"));
}
#[test]
fn test_route_exemption() {
let middleware = CsrfMiddleware::new();
assert!(!middleware.is_route_exempt("/api/users"));
assert!(!middleware.is_route_exempt("/api/v1/posts"));
assert!(!middleware.is_route_exempt("/app/api"));
assert!(!middleware.is_route_exempt("/users"));
}
#[test]
fn test_custom_exemptions() {
let config = CsrfConfig::new()
.exempt("/webhook/*")
.exempt("/public/upload");
let middleware = CsrfMiddleware::with_config(config);
assert!(middleware.is_route_exempt("/webhook/github"));
assert!(middleware.is_route_exempt("/public/upload"));
assert!(!middleware.is_route_exempt("/webhookx")); assert!(!middleware.is_route_exempt("/public/upload/file"));
assert!(!middleware.is_route_exempt("/api/test"));
}
}