use axum::http::header::{
HeaderName, HeaderValue, CONTENT_SECURITY_POLICY, REFERRER_POLICY, STRICT_TRANSPORT_SECURITY,
X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
};
use axum::http::Method;
use axum::{extract::Request, middleware::Next, response::Response};
use tower_http::cors::{AllowOrigin, CorsLayer};
use crate::rate_limit::RateLimit;
static X_XSS_PROTECTION: HeaderName = HeaderName::from_static("x-xss-protection");
#[derive(Debug, Clone)]
pub struct HttpSecurity {
pub cors_allowed_origins: Vec<String>,
pub rate_limit: Option<RateLimit>,
pub trust_forwarded_for: bool,
pub expose_docs: bool,
}
impl Default for HttpSecurity {
fn default() -> Self {
Self {
cors_allowed_origins: Vec::new(),
rate_limit: Some(RateLimit::default()),
trust_forwarded_for: false,
expose_docs: true,
}
}
}
impl HttpSecurity {
#[must_use]
pub fn with_cors_origins<I, S>(origins: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
cors_allowed_origins: origins.into_iter().map(Into::into).collect(),
..Self::default()
}
}
}
fn set_if_absent(response: &mut Response, name: HeaderName, value: &'static str) {
let headers = response.headers_mut();
if !headers.contains_key(&name) {
headers.insert(name, HeaderValue::from_static(value));
}
}
pub async fn security_headers(request: Request, next: Next) -> Response {
let mut response = next.run(request).await;
set_if_absent(&mut response, X_CONTENT_TYPE_OPTIONS, "nosniff");
set_if_absent(&mut response, X_FRAME_OPTIONS, "DENY");
set_if_absent(
&mut response,
CONTENT_SECURITY_POLICY,
"default-src 'none'; frame-ancestors 'none'",
);
set_if_absent(&mut response, REFERRER_POLICY, "no-referrer");
set_if_absent(
&mut response,
STRICT_TRANSPORT_SECURITY,
"max-age=63072000; includeSubDomains",
);
set_if_absent(&mut response, X_XSS_PROTECTION.clone(), "0");
response
}
#[must_use]
pub fn cors_layer(security: &HttpSecurity) -> Option<CorsLayer> {
if security.cors_allowed_origins.is_empty() {
return None;
}
let origins: Vec<HeaderValue> = security
.cors_allowed_origins
.iter()
.filter_map(|o| HeaderValue::from_str(o).ok())
.collect();
if origins.is_empty() {
return None;
}
Some(
CorsLayer::new()
.allow_origin(AllowOrigin::list(origins))
.allow_methods([
Method::GET,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
Method::OPTIONS,
])
.allow_headers([
axum::http::header::CONTENT_TYPE,
axum::http::header::AUTHORIZATION,
]),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{router_with_security, Health};
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
fn ready_app(security: &HttpSecurity) -> axum::Router {
let health = Health::starting();
health.set_ready();
router_with_security(health, security)
}
#[tokio::test]
async fn security_headers_are_present_even_on_a_rate_limited_429() {
use crate::RateLimit;
use std::time::Duration;
let security = HttpSecurity {
rate_limit: Some(RateLimit {
max_requests: 1,
window: Duration::from_secs(60),
}),
..HttpSecurity::default()
};
let app = ready_app(&security);
let req = || {
Request::builder()
.uri("/openapi.json")
.body(Body::empty())
.unwrap()
};
let ok = app.clone().oneshot(req()).await.unwrap();
assert_eq!(ok.status(), StatusCode::OK);
let limited = app.oneshot(req()).await.unwrap();
assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
let headers = limited.headers();
assert_eq!(headers["x-content-type-options"], "nosniff");
assert_eq!(headers["x-frame-options"], "DENY");
assert!(headers.contains_key("content-security-policy"));
assert!(headers.contains_key("strict-transport-security"));
assert!(headers.contains_key(crate::REQUEST_ID_HEADER));
}
#[tokio::test]
async fn security_headers_are_present_on_every_response() {
let app = ready_app(&HttpSecurity::default());
let res = app
.oneshot(
Request::builder()
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let headers = res.headers();
assert_eq!(headers["x-content-type-options"], "nosniff");
assert_eq!(headers["x-frame-options"], "DENY");
assert!(headers["content-security-policy"]
.to_str()
.unwrap()
.contains("default-src 'none'"));
assert_eq!(headers["referrer-policy"], "no-referrer");
assert!(headers.contains_key("strict-transport-security"));
assert_eq!(headers["x-xss-protection"], "0");
}
#[tokio::test]
async fn default_posture_emits_no_cors_header() {
assert!(cors_layer(&HttpSecurity::default()).is_none());
let app = ready_app(&HttpSecurity::default());
let res = app
.oneshot(
Request::builder()
.uri("/health/ready")
.header("origin", "https://evil.example")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(!res.headers().contains_key("access-control-allow-origin"));
}
#[tokio::test]
async fn cors_reflects_an_allowlisted_origin_only() {
let security = HttpSecurity::with_cors_origins(["https://app.example.com"]);
let app = ready_app(&security);
let allowed = app
.clone()
.oneshot(
Request::builder()
.uri("/health/ready")
.header("origin", "https://app.example.com")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
allowed.headers()["access-control-allow-origin"],
"https://app.example.com"
);
let blocked = app
.oneshot(
Request::builder()
.uri("/health/ready")
.header("origin", "https://evil.example")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(!blocked
.headers()
.contains_key("access-control-allow-origin"));
}
}