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 {
Required,
BestEffort,
Disabled,
}
impl NonceAvailability {
pub fn from_config(s: &str) -> Self {
match s.trim().to_ascii_lowercase().as_str() {
"required" => Self::Required,
"disabled" => Self::Disabled,
_ => Self::BestEffort,
}
}
}
pub struct NonceState {
pub availability: NonceAvailability,
pub require_for_write: bool,
pub ttl_secs: u32,
warn_once: AtomicBool,
}
impl NonceState {
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),
}
}
}
fn is_write_method(method: &Method) -> bool {
matches!(
*method,
Method::POST | Method::PUT | Method::PATCH | Method::DELETE
)
}
const MAX_NONCE_LEN: usize = 128;
pub async fn nonce(State(state): State<Arc<NonceState>>, req: Request, next: Next) -> Response {
let cfg = state;
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"));
}
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 不合法"));
}
};
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 已被使用,请勿重放请求",
));
}
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
);
}
}
},
}
}
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
}