garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! HTTP 安全响应头中间件:注入 nosniff(防 MIME 嗅探)、DENY(防点击劫持)、
//! no-store/no-cache(防敏感响应缓存),TLS 构建附 HSTS;仅 `web-security-headers` feature 启用时编译。

use axum::http::header::HeaderName;
use axum::http::HeaderValue;
use axum::middleware::Next;
use axum::response::Response;

/// `X-Content-Type-Options: nosniff` — 阻止浏览器 MIME 类型嗅探。
const X_CONTENT_TYPE_OPTIONS: HeaderName = HeaderName::from_static("x-content-type-options");
const NOSNIFF: HeaderValue = HeaderValue::from_static("nosniff");

/// `X-Frame-Options: DENY` — 阻止页面被嵌入 iframe(防点击劫持)。
const X_FRAME_OPTIONS: HeaderName = HeaderName::from_static("x-frame-options");
const DENY: HeaderValue = HeaderValue::from_static("DENY");

/// `Cache-Control: no-store` — 禁止缓存敏感认证响应。
const CACHE_CONTROL: HeaderName = HeaderName::from_static("cache-control");
const NO_STORE: HeaderValue = HeaderValue::from_static("no-store");

/// `Pragma: no-cache` — HTTP/1.0 兼容缓存控制。
const PRAGMA: HeaderName = HeaderName::from_static("pragma");
const NO_CACHE: HeaderValue = HeaderValue::from_static("no-cache");

/// `Strict-Transport-Security` — HSTS 头名称(仅 `tls` feature 启用时使用)。
#[cfg(feature = "tls")]
const STRICT_TRANSPORT_SECURITY: HeaderName = HeaderName::from_static("strict-transport-security");

/// HSTS 值:1 年 + includeSubDomains(仅 `tls` feature 启用时使用)。
#[cfg(feature = "tls")]
const HSTS_MAX_AGE: HeaderValue = HeaderValue::from_static("max-age=31536000; includeSubDomains");

/// 安全响应头中间件 — 为所有响应注入标准安全头。
///
/// 静态资源等公开可缓存内容不应走本中间件(no-store 全响应注入会使浏览器/CDN 缓存失效);
/// 同路由混布时可改用 [`security_headers_middleware_with_config`] 关闭缓存头注入。
///
/// # 示例
///
/// ```ignore
/// use axum::middleware;
/// use garrison::web::security_headers::security_headers_middleware;
///
/// let app = Router::new()
/// .route("/api", get(handler))
/// .layer(middleware::from_fn(security_headers_middleware));
/// ```
pub async fn security_headers_middleware(req: axum::extract::Request, next: Next) -> Response {
    inject_security_headers(next.run(req).await, true)
}

/// 缓存头注入开关配置。
///
/// `no_store_cache == false` 时不注入 `Cache-Control: no-store` / `Pragma: no-cache`,
/// 供静态资源等公开可缓存路由复用其余安全头;默认 `true` 保持原行为。
#[derive(Debug, Clone)]
pub struct SecurityHeadersConfig {
    /// 是否注入 `Cache-Control: no-store` + `Pragma: no-cache`(默认 `true`)。
    pub no_store_cache: bool,
}

impl Default for SecurityHeadersConfig {
    fn default() -> Self {
        Self {
            no_store_cache: true,
        }
    }
}

/// 可配置版安全响应头中间件(通过 `from_fn_with_state` + `Arc<SecurityHeadersConfig>` 挂载)。
///
/// # 示例
///
/// ```ignore
/// use axum::middleware;
/// use garrison::web::security_headers::{security_headers_middleware_with_config, SecurityHeadersConfig};
/// use std::sync::Arc;
///
/// let config = Arc::new(SecurityHeadersConfig { no_store_cache: false });
/// let app = Router::new()
/// .route("/static", get(handler))
/// .layer(middleware::from_fn_with_state(config, security_headers_middleware_with_config));
/// ```
pub async fn security_headers_middleware_with_config(
    axum::extract::State(config): axum::extract::State<std::sync::Arc<SecurityHeadersConfig>>,
    req: axum::extract::Request,
    next: Next,
) -> Response {
    inject_security_headers(next.run(req).await, config.no_store_cache)
}

/// 实际注入逻辑(`no_store == false` 时跳过 Cache-Control / Pragma)。
fn inject_security_headers(mut response: Response, no_store: bool) -> Response {
    let headers = response.headers_mut();

    headers.insert(X_CONTENT_TYPE_OPTIONS, NOSNIFF);
    headers.insert(X_FRAME_OPTIONS, DENY);
    if no_store {
        headers.insert(CACHE_CONTROL, NO_STORE);
        headers.insert(PRAGMA, NO_CACHE);
    }

    // HSTS 仅在 TLS 终止模式下设置(明文传输 HSTS 无意义且可能被降级攻击)
    #[cfg(feature = "tls")]
    headers.insert(STRICT_TRANSPORT_SECURITY, HSTS_MAX_AGE);

    response
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::routing::get;
    use axum::Router;
    use std::sync::Arc;
    use tower::ServiceExt;

    /// 创建包含安全头中间件的测试 Router。
    fn app_with_security_headers() -> Router {
        Router::new()
            .route("/ping", get(|| async { "ok" }))
            .layer(axum::middleware::from_fn(security_headers_middleware))
    }

    /// 验证所有基础安全头存在于响应中且值正确。
    #[tokio::test]
    async fn security_headers_present_in_response() {
        let app = app_with_security_headers();
        let resp = app
            .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let headers = resp.headers();

        assert_eq!(
            headers.get("x-content-type-options").unwrap(),
            "nosniff",
            "X-Content-Type-Options 应为 nosniff"
        );
        assert_eq!(
            headers.get("x-frame-options").unwrap(),
            "DENY",
            "X-Frame-Options 应为 DENY"
        );
        assert_eq!(
            headers.get("cache-control").unwrap(),
            "no-store",
            "Cache-Control 应为 no-store"
        );
        assert_eq!(
            headers.get("pragma").unwrap(),
            "no-cache",
            "Pragma 应为 no-cache"
        );
    }

    /// 非 TLS 构建时响应不应包含 HSTS 头(cfg 保证仅在非 TLS 构建下运行)。
    #[cfg(not(feature = "tls"))]
    #[tokio::test]
    async fn no_hsts_without_tls_feature() {
        let app = app_with_security_headers();
        let resp = app
            .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert!(
            resp.headers().get("strict-transport-security").is_none(),
            "tls feature 未启用时不应设置 HSTS 头"
        );
    }

    /// TLS 构建时响应应包含 HSTS 头。
    #[cfg(feature = "tls")]
    #[tokio::test]
    async fn hsts_present_with_tls_feature() {
        let app = app_with_security_headers();
        let resp = app
            .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(
            resp.headers().get("strict-transport-security").unwrap(),
            "max-age=31536000; includeSubDomains",
            "tls feature 启用时应设置 HSTS 头"
        );
    }

    /// 错误响应(如 404)也应包含安全头。
    #[tokio::test]
    async fn security_headers_on_error_responses() {
        let app = app_with_security_headers();
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/nonexistent")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            resp.headers().get("x-content-type-options").unwrap(),
            "nosniff",
            "错误响应也应包含安全头"
        );
        assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
    }

    /// 可配置中间件:no_store_cache=false 时跳过缓存头,其余安全头保留。
    #[tokio::test]
    async fn config_middleware_can_disable_no_store() {
        let config = Arc::new(SecurityHeadersConfig {
            no_store_cache: false,
        });
        let app = Router::new().route("/ping", get(|| async { "ok" })).layer(
            axum::middleware::from_fn_with_state(config, security_headers_middleware_with_config),
        );
        let resp = app
            .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        assert!(
            resp.headers().get("cache-control").is_none(),
            "no_store_cache=false 时不应注入 Cache-Control"
        );
        assert!(resp.headers().get("pragma").is_none());
        assert_eq!(
            resp.headers().get("x-content-type-options").unwrap(),
            "nosniff"
        );
        assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
    }

    /// 可配置中间件:默认配置(no_store_cache=true)行为与原中间件一致。
    #[tokio::test]
    async fn config_middleware_default_keeps_no_store() {
        let config = Arc::new(SecurityHeadersConfig::default());
        let app = Router::new().route("/ping", get(|| async { "ok" })).layer(
            axum::middleware::from_fn_with_state(config, security_headers_middleware_with_config),
        );
        let resp = app
            .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.headers().get("cache-control").unwrap(), "no-store");
        assert_eq!(resp.headers().get("pragma").unwrap(), "no-cache");
    }
}