use axum::{
Router,
extract::{DefaultBodyLimit, Request, State},
http::{HeaderName, HeaderValue, StatusCode},
middleware::{Next, from_fn_with_state},
response::Response,
};
use std::time::Duration;
use tower_http::{
catch_panic::CatchPanicLayer,
limit::RequestBodyLimitLayer,
request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer},
timeout::TimeoutLayer,
trace::TraceLayer,
};
#[derive(Clone)]
pub(crate) struct Hardening {
pub hsts: bool,
pub csp: Option<HeaderValue>,
pub body_limit: usize,
pub timeout: Duration,
}
impl Default for Hardening {
fn default() -> Self {
Hardening {
hsts: true,
csp: None,
body_limit: 1024 * 1024,
timeout: Duration::from_secs(30),
}
}
}
pub(crate) fn is_production() -> bool {
std::env::var("APP_ENV").is_ok_and(|v| v == "production")
}
#[derive(Clone)]
struct Headers(Vec<(HeaderName, HeaderValue)>);
async fn set_headers(State(h): State<Headers>, req: Request, next: Next) -> Response {
let mut res = next.run(req).await;
for (k, v) in &h.0 {
res.headers_mut().entry(k).or_insert_with(|| v.clone());
}
res
}
pub(crate) fn harden(router: Router, h: &Hardening, production: bool) -> Router {
let mut hs = vec![
("x-content-type-options", "nosniff"),
("x-frame-options", "DENY"),
("referrer-policy", "strict-origin-when-cross-origin"),
(
"permissions-policy",
"camera=(), microphone=(), geolocation=()",
),
("cross-origin-opener-policy", "same-origin"),
];
if production && h.hsts {
hs.push((
"strict-transport-security",
"max-age=31536000; includeSubDomains",
));
}
let mut hs: Vec<_> = hs
.into_iter()
.map(|(k, v)| (HeaderName::from_static(k), HeaderValue::from_static(v)))
.collect();
if let Some(csp) = &h.csp {
hs.push((
HeaderName::from_static("content-security-policy"),
csp.clone(),
));
}
router
.layer(DefaultBodyLimit::max(h.body_limit))
.layer(RequestBodyLimitLayer::new(h.body_limit))
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
h.timeout,
))
.layer(CatchPanicLayer::new())
.layer(from_fn_with_state(Headers(hs), set_headers))
.layer(TraceLayer::new_for_http().make_span_with(|r: &Request| {
let id = r
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.unwrap_or("-");
tracing::info_span!("request", method = %r.method(), path = %loggable_path(r.uri().path()), request_id = %id)
}))
.layer(PropagateRequestIdLayer::x_request_id())
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
}
pub(crate) fn loggable_path(path: &str) -> String {
let mut prev = "";
path.split('/')
.map(|seg| {
let out = if matches!(prev, "verify-email" | "reset-password") {
"[redacted]"
} else {
seg
};
prev = seg;
out
})
.collect::<Vec<_>>()
.join("/")
}
#[cfg(test)]
mod tests {
use super::loggable_path as p;
#[test]
fn span_path_hides_tokens() {
assert_eq!(p("/verify-email/abc123"), "/verify-email/[redacted]");
assert_eq!(p("/reset-password/abc123"), "/reset-password/[redacted]");
assert_eq!(p("/reset-password"), "/reset-password");
assert_eq!(p("/posts/1"), "/posts/1");
assert_eq!(p("/"), "/");
}
}