Skip to main content

rustbasic_core/middleware/
security_headers.rs

1/* ---------------------------------------------------------
2 * 📑 LABEL: SECURITY HEADERS
3 * Menambahkan header keamanan standar industri.
4 * --------------------------------------------------------- */
5
6use axum::{
7    body::Body,
8    http::{Request, header},
9    middleware::Next,
10    response::Response,
11};
12
13pub async fn security_headers_middleware(
14    req: Request<Body>,
15    next: Next,
16) -> Response {
17    let mut response = next.run(req).await;
18    
19    let headers = response.headers_mut();
20    
21    // 1. Mencegah Clickjacking
22    headers.insert(header::X_FRAME_OPTIONS, "DENY".parse().unwrap());
23    
24    // 2. Mencegah MIME Sniffing
25    headers.insert(header::X_CONTENT_TYPE_OPTIONS, "nosniff".parse().unwrap());
26    
27    // 3. XSS Protection (untuk browser lama)
28    headers.insert(header::X_XSS_PROTECTION, "1; mode=block".parse().unwrap());
29    
30    // 4. Content Security Policy (Lengkap)
31    headers.insert(
32        header::CONTENT_SECURITY_POLICY,
33        concat!(
34            "default-src 'self'; ",
35            "script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; ",
36            "style-src 'self' 'unsafe-inline' https:; ",
37            "font-src 'self' https: data:; ",
38            "img-src 'self' data: https:; ",
39            "connect-src 'self' https:;"
40        ).parse().unwrap()
41    );
42    
43    response
44}