style: cargo fmt --all

This commit is contained in:
Dionisio
2026-03-03 01:49:18 +01:00
parent 1df52fd702
commit efcf88c4d7
29 changed files with 2754 additions and 2732 deletions
+5 -9
View File
@@ -205,10 +205,7 @@ pub async fn auth_middleware(
}
Err(e) => {
tracing::warn!("Bearer token validation failed: {}", e);
return Err(AuthError::InvalidToken(format!(
"Invalid token: {}",
e
)));
return Err(AuthError::InvalidToken(format!("Invalid token: {}", e)));
}
}
}
@@ -273,7 +270,9 @@ pub async fn auth_middleware(
{
use crate::interfaces::api::cookie_auth;
if let Some(token_str) = cookie_auth::extract_cookie_value(&headers, cookie_auth::ACCESS_COOKIE) {
if let Some(token_str) =
cookie_auth::extract_cookie_value(&headers, cookie_auth::ACCESS_COOKIE)
{
if !token_str.is_empty() {
tracing::debug!("Processing cookie-based authentication");
@@ -281,10 +280,7 @@ pub async fn auth_middleware(
let token_service = &auth_service.token_service;
match token_service.validate_token(&token_str) {
Ok(claims) => {
tracing::debug!(
"Cookie token validated for user: {}",
claims.username
);
tracing::debug!("Cookie token validated for user: {}", claims.username);
let current_user = CurrentUser {
id: claims.sub,
username: claims.username,
+73 -75
View File
@@ -1,75 +1,73 @@
//! CSRF double-submit cookie middleware.
//!
//! State-changing requests (`POST`, `PUT`, `DELETE`, `PATCH`) that were
//! authenticated via an HttpOnly cookie (i.e. browser sessions) **must**
//! include an `X-CSRF-Token` header whose value matches the `oxicloud_csrf`
//! cookie. Requests authenticated via `Bearer` or `Basic` headers are
//! exempt because they are not vulnerable to CSRF — the browser never
//! attaches those automatically.
//!
//! Safe methods (`GET`, `HEAD`, `OPTIONS`) are always allowed through.
use axum::{
extract::Request,
http::{Method, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
};
use crate::interfaces::api::cookie_auth;
use crate::interfaces::middleware::auth::CookieAuthenticated;
/// Methods considered safe (no side-effects) — CSRF check is skipped.
const SAFE_METHODS: [Method; 3] = [Method::GET, Method::HEAD, Method::OPTIONS];
/// Middleware that enforces CSRF protection for cookie-authenticated browser
/// sessions using the **double-submit cookie** pattern.
///
/// Must be applied **after** `auth_middleware` so that the
/// `CookieAuthenticated` marker is available in extensions.
pub async fn csrf_middleware(request: Request, next: Next) -> Result<Response, Response> {
// Safe methods never need CSRF validation.
if SAFE_METHODS.contains(request.method()) {
return Ok(next.run(request).await);
}
// Only enforce for cookie-authenticated sessions.
let is_cookie_auth = request.extensions().get::<CookieAuthenticated>().is_some();
if !is_cookie_auth {
return Ok(next.run(request).await);
}
// Extract the CSRF token from the cookie.
let cookie_token = cookie_auth::extract_cookie_value(
request.headers(),
cookie_auth::CSRF_COOKIE,
);
// Extract the CSRF token from the request header.
let header_token = request
.headers()
.get(cookie_auth::CSRF_HEADER)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
match (cookie_token, header_token) {
(Some(c), Some(h)) if !c.is_empty() && c == h => {
// Tokens match — allow the request through.
Ok(next.run(request).await)
}
_ => {
tracing::warn!(
method = %request.method(),
uri = %request.uri(),
"CSRF validation failed: missing or mismatched token"
);
Err((
StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({
"error": "CSRF token missing or invalid"
})),
)
.into_response())
}
}
}
//! CSRF double-submit cookie middleware.
//!
//! State-changing requests (`POST`, `PUT`, `DELETE`, `PATCH`) that were
//! authenticated via an HttpOnly cookie (i.e. browser sessions) **must**
//! include an `X-CSRF-Token` header whose value matches the `oxicloud_csrf`
//! cookie. Requests authenticated via `Bearer` or `Basic` headers are
//! exempt because they are not vulnerable to CSRF — the browser never
//! attaches those automatically.
//!
//! Safe methods (`GET`, `HEAD`, `OPTIONS`) are always allowed through.
use axum::{
extract::Request,
http::{Method, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
};
use crate::interfaces::api::cookie_auth;
use crate::interfaces::middleware::auth::CookieAuthenticated;
/// Methods considered safe (no side-effects) — CSRF check is skipped.
const SAFE_METHODS: [Method; 3] = [Method::GET, Method::HEAD, Method::OPTIONS];
/// Middleware that enforces CSRF protection for cookie-authenticated browser
/// sessions using the **double-submit cookie** pattern.
///
/// Must be applied **after** `auth_middleware` so that the
/// `CookieAuthenticated` marker is available in extensions.
pub async fn csrf_middleware(request: Request, next: Next) -> Result<Response, Response> {
// Safe methods never need CSRF validation.
if SAFE_METHODS.contains(request.method()) {
return Ok(next.run(request).await);
}
// Only enforce for cookie-authenticated sessions.
let is_cookie_auth = request.extensions().get::<CookieAuthenticated>().is_some();
if !is_cookie_auth {
return Ok(next.run(request).await);
}
// Extract the CSRF token from the cookie.
let cookie_token =
cookie_auth::extract_cookie_value(request.headers(), cookie_auth::CSRF_COOKIE);
// Extract the CSRF token from the request header.
let header_token = request
.headers()
.get(cookie_auth::CSRF_HEADER)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
match (cookie_token, header_token) {
(Some(c), Some(h)) if !c.is_empty() && c == h => {
// Tokens match — allow the request through.
Ok(next.run(request).await)
}
_ => {
tracing::warn!(
method = %request.method(),
uri = %request.uri(),
"CSRF validation failed: missing or mismatched token"
);
Err((
StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({
"error": "CSRF token missing or invalid"
})),
)
.into_response())
}
}
}
+196 -202
View File
@@ -1,202 +1,196 @@
//! IP-based rate limiting middleware for authentication endpoints.
//!
//! Uses `moka` TTL caches (already a project dependency) to track request
//! counts per client IP. Each protected endpoint group gets its own
//! [`RateLimiter`] instance with independently tuneable limits.
//!
//! The middleware extracts the client IP from (in order):
//! 1. `X-Forwarded-For` header (first entry — set by reverse proxies)
//! 2. `X-Real-Ip` header
//! 3. The TCP peer address from the connection info
//!
//! When the limit is exceeded a `429 Too Many Requests` response is returned
//! with a `Retry-After` header indicating how many seconds to wait.
use axum::{
extract::ConnectInfo,
http::{HeaderValue, Request, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
};
use moka::sync::Cache;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
/// A simple sliding-window counter keyed by IP address.
///
/// Each key lives for `window` seconds; every request increments the counter.
/// Once the counter reaches `max_requests` the request is rejected.
#[derive(Clone)]
pub struct RateLimiter {
/// Maps `IP -> request_count` with automatic TTL expiration.
cache: Cache<String, u32>,
/// Maximum requests allowed within the window.
max_requests: u32,
/// Window duration in seconds (also used for `Retry-After`).
window_secs: u64,
}
impl RateLimiter {
/// Create a new rate limiter.
///
/// * `max_requests` — ceiling per IP within the window
/// * `window_secs` — sliding window duration
/// * `max_entries` — upper bound on tracked IPs (evicts LRU when exceeded)
pub fn new(max_requests: u32, window_secs: u64, max_entries: u64) -> Self {
let cache = Cache::builder()
.time_to_live(Duration::from_secs(window_secs))
.max_capacity(max_entries)
.build();
Self {
cache,
max_requests,
window_secs,
}
}
/// Check whether the IP is allowed. Returns `Ok(current_count)` or
/// `Err(StatusCode::TOO_MANY_REQUESTS)`.
pub fn check_and_increment(&self, ip: &str) -> Result<u32, ()> {
let key = ip.to_string();
// moka's entry API lets us atomically read-modify-write.
// On first access the entry is inserted with count = 1 and the TTL
// starts. Subsequent accesses within the window increment the count.
let count = self
.cache
.entry(key)
.or_insert_with(|| 0)
.into_value()
+ 1;
// Write back the incremented value. Because `or_insert_with` returns
// the *existing* value when the key was already present, we must always
// re-insert so the counter actually advances. The TTL of the **first**
// insert still governs eviction because moka uses insert-time TTL.
// However, on re-insert moka resets the TTL — for rate limiting this
// is fine because it means the window "slides" forward on activity.
self.cache
.insert(ip.to_string(), count);
if count > self.max_requests {
Err(())
} else {
Ok(count)
}
}
/// Seconds the client should wait before retrying.
pub fn retry_after(&self) -> u64 {
self.window_secs
}
}
// ─── Axum middleware factories ──────────────────────────────────────────────
/// Extract the most-likely real client IP from headers / connection info.
pub fn extract_client_ip<B>(req: &Request<B>) -> String {
let headers = req.headers();
// 1. X-Forwarded-For (first entry — closest to the client)
if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
if let Some(first) = xff.split(',').next() {
let ip = first.trim();
if !ip.is_empty() {
return ip.to_string();
}
}
}
// 2. X-Real-Ip
if let Some(xri) = headers.get("x-real-ip").and_then(|v| v.to_str().ok()) {
let ip = xri.trim();
if !ip.is_empty() {
return ip.to_string();
}
}
// 3. TCP peer (ConnectInfo extension set by axum::serve)
if let Some(addr) = req.extensions().get::<ConnectInfo<SocketAddr>>() {
return addr.0.ip().to_string();
}
// Fallback — should never happen behind axum::serve
"unknown".to_string()
}
/// Build a rate-limit response with the standard `Retry-After` header.
fn too_many_requests(retry_after: u64) -> Response {
let body = serde_json::json!({
"error": "Too many requests",
"retry_after_secs": retry_after,
});
let mut resp = (StatusCode::TOO_MANY_REQUESTS, axum::Json(body)).into_response();
if let Ok(val) = HeaderValue::from_str(&retry_after.to_string()) {
resp.headers_mut().insert("retry-after", val);
}
resp
}
/// Axum middleware: rate-limit login attempts.
///
/// Inject via:
/// ```ignore
/// .layer(axum::middleware::from_fn_with_state(limiter, rate_limit_login))
/// ```
pub async fn rate_limit_login(
State(limiter): axum::extract::State<Arc<RateLimiter>>,
req: Request<axum::body::Body>,
next: Next,
) -> Response {
let ip = extract_client_ip(&req);
match limiter.check_and_increment(&ip) {
Ok(_) => next.run(req).await,
Err(()) => {
tracing::warn!(
ip = %ip,
"Rate limit exceeded on login endpoint"
);
too_many_requests(limiter.retry_after())
}
}
}
/// Axum middleware: rate-limit registration attempts.
pub async fn rate_limit_register(
State(limiter): axum::extract::State<Arc<RateLimiter>>,
req: Request<axum::body::Body>,
next: Next,
) -> Response {
let ip = extract_client_ip(&req);
match limiter.check_and_increment(&ip) {
Ok(_) => next.run(req).await,
Err(()) => {
tracing::warn!(
ip = %ip,
"Rate limit exceeded on register endpoint"
);
too_many_requests(limiter.retry_after())
}
}
}
/// Axum middleware: rate-limit token refresh attempts.
pub async fn rate_limit_refresh(
State(limiter): axum::extract::State<Arc<RateLimiter>>,
req: Request<axum::body::Body>,
next: Next,
) -> Response {
let ip = extract_client_ip(&req);
match limiter.check_and_increment(&ip) {
Ok(_) => next.run(req).await,
Err(()) => {
tracing::warn!(
ip = %ip,
"Rate limit exceeded on refresh endpoint"
);
too_many_requests(limiter.retry_after())
}
}
}
use axum::extract::State;
//! IP-based rate limiting middleware for authentication endpoints.
//!
//! Uses `moka` TTL caches (already a project dependency) to track request
//! counts per client IP. Each protected endpoint group gets its own
//! [`RateLimiter`] instance with independently tuneable limits.
//!
//! The middleware extracts the client IP from (in order):
//! 1. `X-Forwarded-For` header (first entry — set by reverse proxies)
//! 2. `X-Real-Ip` header
//! 3. The TCP peer address from the connection info
//!
//! When the limit is exceeded a `429 Too Many Requests` response is returned
//! with a `Retry-After` header indicating how many seconds to wait.
use axum::{
extract::ConnectInfo,
http::{HeaderValue, Request, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
};
use moka::sync::Cache;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
/// A simple sliding-window counter keyed by IP address.
///
/// Each key lives for `window` seconds; every request increments the counter.
/// Once the counter reaches `max_requests` the request is rejected.
#[derive(Clone)]
pub struct RateLimiter {
/// Maps `IP -> request_count` with automatic TTL expiration.
cache: Cache<String, u32>,
/// Maximum requests allowed within the window.
max_requests: u32,
/// Window duration in seconds (also used for `Retry-After`).
window_secs: u64,
}
impl RateLimiter {
/// Create a new rate limiter.
///
/// * `max_requests` — ceiling per IP within the window
/// * `window_secs` — sliding window duration
/// * `max_entries` — upper bound on tracked IPs (evicts LRU when exceeded)
pub fn new(max_requests: u32, window_secs: u64, max_entries: u64) -> Self {
let cache = Cache::builder()
.time_to_live(Duration::from_secs(window_secs))
.max_capacity(max_entries)
.build();
Self {
cache,
max_requests,
window_secs,
}
}
/// Check whether the IP is allowed. Returns `Ok(current_count)` or
/// `Err(StatusCode::TOO_MANY_REQUESTS)`.
pub fn check_and_increment(&self, ip: &str) -> Result<u32, ()> {
let key = ip.to_string();
// moka's entry API lets us atomically read-modify-write.
// On first access the entry is inserted with count = 1 and the TTL
// starts. Subsequent accesses within the window increment the count.
let count = self.cache.entry(key).or_insert_with(|| 0).into_value() + 1;
// Write back the incremented value. Because `or_insert_with` returns
// the *existing* value when the key was already present, we must always
// re-insert so the counter actually advances. The TTL of the **first**
// insert still governs eviction because moka uses insert-time TTL.
// However, on re-insert moka resets the TTL — for rate limiting this
// is fine because it means the window "slides" forward on activity.
self.cache.insert(ip.to_string(), count);
if count > self.max_requests {
Err(())
} else {
Ok(count)
}
}
/// Seconds the client should wait before retrying.
pub fn retry_after(&self) -> u64 {
self.window_secs
}
}
// ─── Axum middleware factories ──────────────────────────────────────────────
/// Extract the most-likely real client IP from headers / connection info.
pub fn extract_client_ip<B>(req: &Request<B>) -> String {
let headers = req.headers();
// 1. X-Forwarded-For (first entry — closest to the client)
if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
if let Some(first) = xff.split(',').next() {
let ip = first.trim();
if !ip.is_empty() {
return ip.to_string();
}
}
}
// 2. X-Real-Ip
if let Some(xri) = headers.get("x-real-ip").and_then(|v| v.to_str().ok()) {
let ip = xri.trim();
if !ip.is_empty() {
return ip.to_string();
}
}
// 3. TCP peer (ConnectInfo extension set by axum::serve)
if let Some(addr) = req.extensions().get::<ConnectInfo<SocketAddr>>() {
return addr.0.ip().to_string();
}
// Fallback — should never happen behind axum::serve
"unknown".to_string()
}
/// Build a rate-limit response with the standard `Retry-After` header.
fn too_many_requests(retry_after: u64) -> Response {
let body = serde_json::json!({
"error": "Too many requests",
"retry_after_secs": retry_after,
});
let mut resp = (StatusCode::TOO_MANY_REQUESTS, axum::Json(body)).into_response();
if let Ok(val) = HeaderValue::from_str(&retry_after.to_string()) {
resp.headers_mut().insert("retry-after", val);
}
resp
}
/// Axum middleware: rate-limit login attempts.
///
/// Inject via:
/// ```ignore
/// .layer(axum::middleware::from_fn_with_state(limiter, rate_limit_login))
/// ```
pub async fn rate_limit_login(
State(limiter): axum::extract::State<Arc<RateLimiter>>,
req: Request<axum::body::Body>,
next: Next,
) -> Response {
let ip = extract_client_ip(&req);
match limiter.check_and_increment(&ip) {
Ok(_) => next.run(req).await,
Err(()) => {
tracing::warn!(
ip = %ip,
"Rate limit exceeded on login endpoint"
);
too_many_requests(limiter.retry_after())
}
}
}
/// Axum middleware: rate-limit registration attempts.
pub async fn rate_limit_register(
State(limiter): axum::extract::State<Arc<RateLimiter>>,
req: Request<axum::body::Body>,
next: Next,
) -> Response {
let ip = extract_client_ip(&req);
match limiter.check_and_increment(&ip) {
Ok(_) => next.run(req).await,
Err(()) => {
tracing::warn!(
ip = %ip,
"Rate limit exceeded on register endpoint"
);
too_many_requests(limiter.retry_after())
}
}
}
/// Axum middleware: rate-limit token refresh attempts.
pub async fn rate_limit_refresh(
State(limiter): axum::extract::State<Arc<RateLimiter>>,
req: Request<axum::body::Body>,
next: Next,
) -> Response {
let ip = extract_client_ip(&req);
match limiter.check_and_increment(&ip) {
Ok(_) => next.run(req).await,
Err(()) => {
tracing::warn!(
ip = %ip,
"Rate limit exceeded on refresh endpoint"
);
too_many_requests(limiter.retry_after())
}
}
}
use axum::extract::State;