use axum::http::header::HeaderName;
use axum::http::HeaderValue;
use axum::middleware::Next;
use axum::response::Response;
const X_CONTENT_TYPE_OPTIONS: HeaderName = HeaderName::from_static("x-content-type-options");
const NOSNIFF: HeaderValue = HeaderValue::from_static("nosniff");
const X_FRAME_OPTIONS: HeaderName = HeaderName::from_static("x-frame-options");
const DENY: HeaderValue = HeaderValue::from_static("DENY");
const CACHE_CONTROL: HeaderName = HeaderName::from_static("cache-control");
const NO_STORE: HeaderValue = HeaderValue::from_static("no-store");
const PRAGMA: HeaderName = HeaderName::from_static("pragma");
const NO_CACHE: HeaderValue = HeaderValue::from_static("no-cache");
#[cfg(feature = "tls")]
const STRICT_TRANSPORT_SECURITY: HeaderName = HeaderName::from_static("strict-transport-security");
#[cfg(feature = "tls")]
const HSTS_MAX_AGE: HeaderValue = HeaderValue::from_static("max-age=31536000; includeSubDomains");
pub async fn security_headers_middleware(req: axum::extract::Request, next: Next) -> Response {
inject_security_headers(next.run(req).await, true)
}
#[derive(Debug, Clone)]
pub struct SecurityHeadersConfig {
pub no_store_cache: bool,
}
impl Default for SecurityHeadersConfig {
fn default() -> Self {
Self {
no_store_cache: true,
}
}
}
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)
}
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);
}
#[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;
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"
);
}
#[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 头"
);
}
#[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 头"
);
}
#[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");
}
#[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");
}
#[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");
}
}