From c13e53404c773c3880487e653472c69e789a257d Mon Sep 17 00:00:00 2001 From: Niccolo Borgioli Date: Fri, 17 Jan 2025 18:48:28 +0100 Subject: [PATCH] add csp draft --- packages/backend/src/csp.rs | 16 ++++++++++++++++ packages/backend/src/main.rs | 7 +++++++ 2 files changed, 23 insertions(+) create mode 100644 packages/backend/src/csp.rs diff --git a/packages/backend/src/csp.rs b/packages/backend/src/csp.rs new file mode 100644 index 0000000..e21ad69 --- /dev/null +++ b/packages/backend/src/csp.rs @@ -0,0 +1,16 @@ +use axum::{body::Body, extract::Request, http::HeaderValue, middleware::Next, response::Response}; + +const CUSTOM_HEADER_NAME: &str = "Content-Security-Policy"; +const CUSTOM_HEADER_VALUE: &str = "default-src 'self'; script-src 'report-sample' 'self'; style-src 'report-sample' 'self'; object-src 'none'; base-uri 'self'; connect-src 'self' data:; font-src 'self'; frame-src 'self'; img-src 'self'; manifest-src 'self'; media-src 'self'; worker-src 'none';"; + +lazy_static! { + static ref HEADER_VALUE: HeaderValue = HeaderValue::from_static(CUSTOM_HEADER_VALUE); +} + +pub async fn add_csp_header(request: Request, next: Next) -> Response { + let mut response = next.run(request).await; + response + .headers_mut() + .append(CUSTOM_HEADER_NAME, HEADER_VALUE.clone()); + response +} diff --git a/packages/backend/src/main.rs b/packages/backend/src/main.rs index 9591b60..a7044ad 100644 --- a/packages/backend/src/main.rs +++ b/packages/backend/src/main.rs @@ -1,7 +1,11 @@ use std::{collections::HashMap, sync::Arc}; use axum::{ + body::Body, extract::{DefaultBodyLimit, Request}, + http::HeaderValue, + middleware::{self, Next}, + response::Response, routing::{delete, get, post}, Router, ServiceExt, }; @@ -19,6 +23,7 @@ use tower_http::{ extern crate lazy_static; mod config; +mod csp; mod health; mod lock; mod note; @@ -55,6 +60,8 @@ async fn main() { let app = Router::new() .nest("/api", api_routes) .fallback_service(serve_dir) + // Disabled for now, as svelte inlines scripts + // .layer(middleware::from_fn(csp::add_csp_header)) .layer(DefaultBodyLimit::max(*config::LIMIT)) .layer( CompressionLayer::new()