Skip to main content

aster_forge_middleware/actix/
security_headers.rs

1//! Default security response headers for Actix Web services.
2//!
3//! These headers are intentionally limited to generic browser hardening. HSTS
4//! is not set here because Aster services usually sit behind an HTTPS reverse
5//! proxy, and that proxy should own HTTPS termination policy.
6
7use actix_web::middleware::DefaultHeaders;
8
9pub use crate::shared::security_headers::{
10    REFERRER_POLICY_VALUE, X_CONTENT_TYPE_OPTIONS_VALUE, X_FRAME_OPTIONS_VALUE,
11};
12
13/// Builds the default security headers middleware.
14#[must_use]
15pub fn default_headers() -> DefaultHeaders {
16    DefaultHeaders::new()
17        .add(("X-Frame-Options", X_FRAME_OPTIONS_VALUE))
18        .add(("Referrer-Policy", REFERRER_POLICY_VALUE))
19        .add(("X-Content-Type-Options", X_CONTENT_TYPE_OPTIONS_VALUE))
20}
21
22#[cfg(test)]
23mod tests {
24    use super::{
25        REFERRER_POLICY_VALUE, X_CONTENT_TYPE_OPTIONS_VALUE, X_FRAME_OPTIONS_VALUE, default_headers,
26    };
27    use actix_web::{HttpResponse, http::header, test, web};
28
29    #[actix_web::test]
30    async fn default_headers_adds_security_headers() {
31        let app = test::init_service(
32            actix_web::App::new()
33                .wrap(default_headers())
34                .route("/", web::get().to(HttpResponse::Ok)),
35        )
36        .await;
37
38        let request = test::TestRequest::get().uri("/").to_request();
39        let response = test::call_service(&app, request).await;
40
41        assert_eq!(
42            response.headers().get("x-frame-options"),
43            Some(&header::HeaderValue::from_static(X_FRAME_OPTIONS_VALUE))
44        );
45        assert_eq!(
46            response.headers().get("referrer-policy"),
47            Some(&header::HeaderValue::from_static(REFERRER_POLICY_VALUE))
48        );
49        assert_eq!(
50            response.headers().get("x-content-type-options"),
51            Some(&header::HeaderValue::from_static(
52                X_CONTENT_TYPE_OPTIONS_VALUE
53            ))
54        );
55    }
56}