Files
rustyip/src/middleware.rs
T
NetworkCats 77410593f2 refactor: consolidate DB lookup boilerplate, UA detection, and polish error/module docs
Phase 1 (DRY):
- db.rs: extract with_reader() helper to eliminate repeated load-guard-lookup
  boilerplate across 6 lookup functions; use From<MmdbProxy> for ProxyInfo
- ua_detect.rs: extract matches_any_prefix() shared by both prefix-matching fns

Phase 4 (Quality polish):
- error.rs: implement Debug, Display, and std::error::Error on AppError
- Add module-level //! docs to all source modules
2026-03-22 17:33:09 +08:00

55 lines
1.9 KiB
Rust

//! Axum middleware for applying security headers to responses.
use axum::extract::Request;
use axum::http::header::{self, HeaderValue};
use axum::middleware::Next;
use axum::response::Response;
pub async fn security_headers(request: Request, next: Next) -> Response {
let mut response = next.run(request).await;
apply_common_security_headers(response.headers_mut());
response.headers_mut().insert(
header::HeaderName::from_static("cross-origin-opener-policy"),
HeaderValue::from_static("same-origin"),
);
response.headers_mut().insert(
header::HeaderName::from_static("cross-origin-resource-policy"),
HeaderValue::from_static("same-origin"),
);
response
}
pub async fn ipv4_domain_security_headers(request: Request, next: Next) -> Response {
let mut response = next.run(request).await;
apply_common_security_headers(response.headers_mut());
response.headers_mut().insert(
header::HeaderName::from_static("cross-origin-resource-policy"),
HeaderValue::from_static("cross-origin"),
);
response
}
fn apply_common_security_headers(headers: &mut axum::http::HeaderMap) {
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
headers.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("strict-origin-when-cross-origin"),
);
headers.insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=63072000; includeSubDomains; preload"),
);
headers.insert(
header::HeaderName::from_static("x-permitted-cross-domain-policies"),
HeaderValue::from_static("none"),
);
headers.insert(
header::HeaderName::from_static("permissions-policy"),
HeaderValue::from_static("camera=(), microphone=(), geolocation=(), interest-cohort=()"),
);
}