Skip to content

Commit

Permalink
serve: create Content-Security-Policy header with random nonce
Browse files Browse the repository at this point in the history
Signed-off-by: Enrico Scholz <[email protected]>
  • Loading branch information
ensc committed Jan 11, 2025
1 parent 5dd3331 commit 2ce5535
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/serve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 2ce5535

Please sign in to comment.