From 4fd01b435096592883342f4266cdc87e83a55ef7 Mon Sep 17 00:00:00 2001 From: Enrico Scholz Date: Mon, 6 Jan 2025 10:38:08 +0100 Subject: [PATCH] serve: create Content-Security-Policy header with random nonce Signed-off-by: Enrico Scholz --- src/serve/mod.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/serve/mod.rs b/src/serve/mod.rs index c742f7cc..d9fdabbe 100644 --- a/src/serve/mod.rs +++ b/src/serve/mod.rs @@ -17,6 +17,7 @@ use axum::routing::{get, get_service, Router}; use axum_server::Handle; use futures_util::FutureExt; use hickory_resolver::TokioAsyncResolver; +use http::header::CONTENT_SECURITY_POLICY; use http::HeaderMap; use proxy::{ProxyBuilder, ProxyClientOptions}; use std::collections::{BTreeSet, HashMap, HashSet}; @@ -517,10 +518,25 @@ async fn html_address_middleware( // here we only replace the string value .replace("{{__TRUNK_WS_BASE__}}", &state.ws_base); + let mut csp = None; + if let Some((var, val)) = nonce { data_str = data_str.replace(var, &val); + csp = state + .cfg + .csp + .as_ref() + .map(|csp| csp.join(";").replace("{{NONCE}}", &val).parse()); } + match csp { + Some(Ok(csp)) => { + parts.headers.insert(CONTENT_SECURITY_POLICY, csp); + } + Some(Err(e)) => tracing::error!("failed to encode csp header: {e:?}"), + None => {} + }; + let bytes_vec = data_str.as_bytes().to_vec(); parts.headers.insert(CONTENT_LENGTH, bytes_vec.len().into()); bytes = Bytes::from(bytes_vec);