rustbasic_core/middleware/
security_headers.rs1use 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 headers.insert(header::X_FRAME_OPTIONS, "DENY".parse().unwrap());
23
24 headers.insert(header::X_CONTENT_TYPE_OPTIONS, "nosniff".parse().unwrap());
26
27 headers.insert(header::X_XSS_PROTECTION, "1; mode=block".parse().unwrap());
29
30 let cfg = crate::Config::load();
32 let csp = if cfg.app_debug {
33 concat!(
34 "default-src 'self'; ",
35 "script-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:5173 http://127.0.0.1:5173 https:; ",
36 "style-src 'self' 'unsafe-inline' http://localhost:5173 http://127.0.0.1:5173 https:; ",
37 "font-src 'self' https: data:; ",
38 "img-src 'self' data: https:; ",
39 "connect-src 'self' ws://localhost:5173 ws://127.0.0.1:5173 http://localhost:5173 http://127.0.0.1:5173 https:;"
40 )
41 } else {
42 concat!(
43 "default-src 'self'; ",
44 "script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; ",
45 "style-src 'self' 'unsafe-inline' https:; ",
46 "font-src 'self' https: data:; ",
47 "img-src 'self' data: https:; ",
48 "connect-src 'self' https:;"
49 )
50 };
51 headers.insert(header::CONTENT_SECURITY_POLICY, csp.parse().unwrap());
52
53 response
54}