wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
//! Nonce 重放防护中间件
//!
//! 设计目标:在 auth 之后运行(链中更靠内),利用 `CurrentUser` 将一次性令牌
//! 绑定到用户/会话,防止重放攻击与跨用户重放。
//!
//! 行为:
//! - 仅当请求携带 `X-Nonce` 头时才做一次性校验(向后兼容:老客户端未带 nonce
//!   不直接拒绝);
//! - 若开启 `require_for_write` 且当前为写方法(POST/PUT/PATCH/DELETE)却未携带
//!   `X-Nonce`,返回 400;
//! - nonce 与用户身份绑定(未登录时绑定客户端直连 IP),同一 nonce 仅可使用一次
//!   (缓存 `set_nx`);
//! - 重复使用同一 nonce 返回 409 Conflict。
//!
//! 存储不可用策略(`availability`):
//! - `required`:缓存不可用时返回 503,fail-closed,绝不放行;
//! - `best_effort`(默认):缓存不可用时放行,但输出高可见性告警
//!   (每个进程最多告警一次);
//! - `disabled`:不做一次性校验(仅强制头存在)。

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use axum::extract::{Request, State};
use axum::http::Method;
use axum::middleware::Next;
use axum::response::Response;

use wordval_cache::Cache;
use wordval_core::api::ApiError;

use super::CurrentUser;
use crate::resources::try_cache;

/// 存储不可用时的安全策略
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NonceAvailability {
    /// 缓存不可用返回 503,fail-closed
    Required,
    /// 缓存不可用放行,但输出高可见性告警
    BestEffort,
    /// 不做一次性校验
    Disabled,
}

impl NonceAvailability {
    /// 从配置字符串解析;无法识别时按 fail-open 处理并告警
    pub fn from_config(s: &str) -> Self {
        match s.trim().to_ascii_lowercase().as_str() {
            "required" => Self::Required,
            "disabled" => Self::Disabled,
            _ => Self::BestEffort,
        }
    }
}

/// Nonce 中间件所需的运行时状态(从配置拷贝,避免依赖整个 App)
pub struct NonceState {
    /// 存储不可用策略
    pub availability: NonceAvailability,
    /// 是否对写操作强制要求 X-Nonce
    pub require_for_write: bool,
    /// nonce 单次有效期限(秒)
    pub ttl_secs: u32,
    /// 缓存不可用告警(仅输出一次,避免刷屏)
    warn_once: AtomicBool,
}

impl NonceState {
    /// 从配置创建状态;`ttl_secs` 为 0 时按 300 秒兜底
    pub fn new(availability: NonceAvailability, require_for_write: bool, ttl_secs: u32) -> Self {
        Self {
            availability,
            require_for_write,
            ttl_secs: if ttl_secs == 0 { 300 } else { ttl_secs },
            warn_once: AtomicBool::new(false),
        }
    }
}

/// 判断是否为会改变状态的请求方法(需强制 nonce)
fn is_write_method(method: &Method) -> bool {
    matches!(
        *method,
        Method::POST | Method::PUT | Method::PATCH | Method::DELETE
    )
}

/// 一次性 nonce 值长度上限(超长值拒绝,防止缓存 key 膨胀)
const MAX_NONCE_LEN: usize = 128;

/// Nonce 重放防护中间件
pub async fn nonce(State(state): State<Arc<NonceState>>, req: Request, next: Next) -> Response {
    let cfg = state;

    // 写方法且强制要求时,缺失 nonce 直接拒绝
    if cfg.require_for_write
        && is_write_method(req.method())
        && req.headers().get("x-nonce").is_none()
    {
        return super::error_response(ApiError::bad_request("缺少一次性防重放令牌 X-Nonce"));
    }

    // 仅在携带 nonce 头时才做一次性校验
    if let Some(nonce_val) = req.headers().get("x-nonce") {
        let nonce = match nonce_val.to_str() {
            Ok(s) if !s.is_empty() && s.len() <= MAX_NONCE_LEN => s,
            _ => {
                return super::error_response(ApiError::bad_request("X-Nonce 不合法"));
            }
        };

        // 身份绑定:优先用户 id,未登录则绑定客户端直连 IP
        // (统一读取 ClientIdentity 层解析的可信 client IP,与日志/限流同一代理策略)
        let key = match req.extensions().get::<CurrentUser>() {
            Some(u) if u.id != 0 => format!("nonce:u{}:{}", u.id, nonce),
            _ => {
                let ip = req
                    .extensions()
                    .get::<super::client_identity::ClientIp>()
                    .map(|c| c.0.as_str())
                    .unwrap_or("0.0.0.0");
                format!("nonce:ip{}:{}", ip, nonce)
            }
        };

        match try_cache() {
            Some(c) => {
                // 单次有效:写入失败说明已使用过
                match c.set_nx(&key, &true, cfg.ttl_secs as u64).await {
                    Ok(true) => {}
                    Ok(false) => {
                        return super::error_response(ApiError::conflict(
                            "X-Nonce 已被使用,请勿重放请求",
                        ));
                    }
                    // 缓存异常:按 availability 策略决定放行或拒绝
                    Err(e) => match cfg.availability {
                        NonceAvailability::Required => {
                            tracing::error!("nonce 存储不可用,按 Required 策略拒绝请求: {}", e);
                            return super::error_response(ApiError::service_unavailable(
                                "防重放服务暂不可用,请稍后再试",
                            ));
                        }
                        NonceAvailability::Disabled => {}
                        NonceAvailability::BestEffort => {
                            if !cfg.warn_once.swap(true, Ordering::Relaxed) {
                                tracing::warn!(
                                    "nonce 存储不可用,按 BestEffort 策略放行(防重放失败,请尽快修复缓存): {}",
                                    e
                                );
                            }
                        }
                    },
                }
            }
            // 未配置缓存:按 availability 策略决定放行或拒绝
            None => {
                match cfg.availability {
                    NonceAvailability::Required => {
                        if !cfg.warn_once.swap(true, Ordering::Relaxed) {
                            tracing::error!("nonce 要求 Required 策略但缓存未初始化,拒绝所有携带 X-Nonce 的请求");
                        }
                        return super::error_response(ApiError::service_unavailable(
                            "防重放服务暂不可用,请稍后再试",
                        ));
                    }
                    NonceAvailability::Disabled => {}
                    NonceAvailability::BestEffort => {
                        if !cfg.warn_once.swap(true, Ordering::Relaxed) {
                            tracing::warn!("nonce 缓存未初始化,按 BestEffort 策略放行(防重放失败,请尽快修复缓存)");
                        }
                    }
                }
            }
        }
    }

    next.run(req).await
}