wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
//! 安全响应头中间件
//!
//! 默认注入以下安全头:
//! - X-Content-Type-Options: nosniff
//! - X-Frame-Options: DENY
//! - Strict-Transport-Security: max-age=31536000; includeSubDomains
//! - Content-Security-Policy: default-src 'self'
//! - Referrer-Policy: strict-origin-when-cross-origin
//!
//! 通过 [SecurityHeadersConfig] 按需开关各个 header,
//! 或设置 `enabled = false` 关闭整个中间件。

use axum::http::{HeaderName, HeaderValue};
use axum::{body::Body, extract::Request, response::Response};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tower::{Layer, Service};
use wordval_config::SecurityHeadersConfig;

/// 安全头中间件 —— 注入 HTTP 安全响应头
///
/// 头值在构建时一次性解析并缓存(`HeaderValue` 克隆是廉价的引用计数),
/// 请求路径上不再做 `format!` / `from_str` 解析。
#[derive(Clone)]
pub struct SecurityHeadersLayer {
    headers: Arc<[(HeaderName, HeaderValue)]>,
}

impl SecurityHeadersLayer {
    /// 从配置创建安全头中间件(配置解析失败的头项跳过并告警)
    pub fn new(config: SecurityHeadersConfig) -> Self {
        let mut headers: Vec<(HeaderName, HeaderValue)> = Vec::new();

        if config.nosniff {
            headers.push((
                HeaderName::from_static("x-content-type-options"),
                HeaderValue::from_static("nosniff"),
            ));
        }

        if config.frame_options {
            headers.push((
                HeaderName::from_static("x-frame-options"),
                HeaderValue::from_static("DENY"),
            ));
        }

        if config.hsts {
            let mut hsts_val = format!("max-age={}", config.hsts_max_age_secs);
            if config.hsts_include_subdomains {
                hsts_val.push_str("; includeSubDomains");
            }
            match HeaderValue::from_str(&hsts_val) {
                Ok(val) => headers.push((
                    HeaderName::from_static("strict-transport-security"),
                    val,
                )),
                Err(e) => tracing::warn!("HSTS 头值非法,已跳过: {}", e),
            }
        }

        if config.csp {
            match HeaderValue::from_str(&config.csp_value) {
                Ok(val) => headers.push((
                    HeaderName::from_static("content-security-policy"),
                    val,
                )),
                Err(e) => tracing::warn!("CSP 头值非法,已跳过: {}", e),
            }
        }

        if config.referrer_policy {
            match HeaderValue::from_str(&config.referrer_policy_value) {
                Ok(val) => {
                    headers.push((HeaderName::from_static("referrer-policy"), val))
                }
                Err(e) => tracing::warn!("Referrer-Policy 头值非法,已跳过: {}", e),
            }
        }

        if config.permissions_policy {
            match HeaderValue::from_str(&config.permissions_policy_value) {
                Ok(val) => headers.push((
                    HeaderName::from_static("permissions-policy"),
                    val,
                )),
                Err(e) => tracing::warn!("Permissions-Policy 头值非法,已跳过: {}", e),
            }
        }

        Self {
            headers: Arc::from(headers),
        }
    }
}

impl<S> Layer<S> for SecurityHeadersLayer {
    type Service = SecurityHeadersService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        SecurityHeadersService {
            inner,
            headers: self.headers.clone(),
        }
    }
}

#[derive(Clone)]
/// 安全头服务——注入 HTTP 安全响应头
pub struct SecurityHeadersService<S> {
    /// 下游服务
    inner: S,
    /// 预构建的安全头(Arc 共享,克隆廉价)
    headers: Arc<[(HeaderName, HeaderValue)]>,
}

impl<S> Service<Request<Body>> for SecurityHeadersService<S>
where
    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let replacement = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, replacement);
        let headers = self.headers.clone();
        Box::pin(async move {
            let mut resp = inner.call(req).await?;
            let resp_headers = resp.headers_mut();
            for (name, value) in headers.iter() {
                resp_headers.insert(name.clone(), value.clone());
            }
            Ok(resp)
        })
    }
}