axum_tower_sessions_csrf/lib.rs
1/*
2 * Copyright (C) 2025 Grant DeFayette
3 *
4 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
5 *
6 * This file is part of axum-tower-sessions-csrf.
7 *
8 * Licensed under either of:
9 * - GNU Lesser General Public License v3.0 or later (LICENSE-LGPL3)
10 * - MIT license (LICENSE-MIT)
11 * at your option.
12 */
13
14//! # axum-tower-sessions-csrf
15//!
16//! CSRF protection for Axum using tower-sessions, implementing the
17//! [Synchronizer Token Pattern](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
18//! as recommended by OWASP.
19//!
20//! ## Features
21//!
22//! - đ Cryptographically secure token generation
23//! - đĻ Session-based token storage (no cookies needed)
24//! - ⥠Constant-time token validation (prevents timing attacks)
25//! - đ¯ Automatic validation on POST/PUT/DELETE/PATCH requests
26//! - đ§ Simple integration with existing Axum applications
27//! - đĒļ Lightweight with minimal dependencies
28//!
29//! ## Quick Start
30//!
31//! ```rust,no_run
32//! use axum::{routing::get, Router};
33//! use axum::middleware::from_fn;
34//! use tower_sessions::{MemoryStore, SessionManagerLayer};
35//! use axum_tower_sessions_csrf::CsrfMiddleware;
36//!
37//! #[tokio::main]
38//! async fn main() {
39//! let session_store = MemoryStore::default();
40//! let session_layer = SessionManagerLayer::new(session_store);
41//!
42//! let app = Router::new()
43//! .route("/", get(|| async { "Hello!" }))
44//! .layer(from_fn(CsrfMiddleware::middleware))
45//! .layer(session_layer);
46//!
47//! // Run your app...
48//! }
49//! ```
50//!
51//! ## Usage
52//!
53//! 1. Add the middleware to your router (must be after `SessionManagerLayer`)
54//! 2. Clients fetch CSRF token via [`get_or_create_token`]
55//! 3. Include token in `x-csrf-token` header for state-changing requests
56//!
57//! See the [examples](https://github.com/yourusername/axum-tower-sessions-csrf/tree/main/examples)
58//! for complete working code.
59
60#![warn(missing_docs)]
61#![warn(clippy::all)]
62#![warn(clippy::pedantic)]
63#![allow(clippy::module_name_repetitions)]
64
65mod token;
66mod validation;
67
68pub use token::{generate_token, get_or_create_token};
69pub use validation::CsrfMiddleware;
70
71/// CSRF token session key (used internally by the middleware)
72pub const TOKEN_KEY: &str = "csrf_token";
73
74/// CSRF token HTTP header name
75pub const TOKEN_HEADER: &str = "x-csrf-token";