Skip to content

Commit 7939aca

Browse files
committed
csp: add a config option to set the CSP in report-only mode
1 parent b2dce51 commit 7939aca

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/config.rs

+5
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ pub struct Config {
4747
// For unit-tests the number has to be higher.
4848
pub(crate) random_crate_search_view_size: u32,
4949

50+
// Content Security Policy
51+
pub(crate) csp_report_only: bool,
52+
5053
// Build params
5154
pub(crate) build_attempts: u16,
5255
pub(crate) rustwide_workspace: PathBuf,
@@ -96,6 +99,8 @@ impl Config {
9699

97100
random_crate_search_view_size: env("DOCSRS_RANDOM_CRATE_SEARCH_VIEW_SIZE", 500)?,
98101

102+
csp_report_only: env("DOCSRS_CSP_REPORT_ONLY", false)?,
103+
99104
rustwide_workspace: env("CRATESFYI_RUSTWIDE_WORKSPACE", PathBuf::from(".workspace"))?,
100105
inside_docker: env("DOCS_RS_DOCKER", false)?,
101106
local_docker_image: maybe_env("DOCS_RS_LOCAL_DOCKER_IMAGE")?,

src/web/csp.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::config::Config;
12
use iron::{AfterMiddleware, BeforeMiddleware, IronResult, Request, Response};
23

34
pub(super) struct Csp {
@@ -94,6 +95,11 @@ impl BeforeMiddleware for CspMiddleware {
9495

9596
impl AfterMiddleware for CspMiddleware {
9697
fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response> {
98+
let config = req
99+
.extensions
100+
.get::<Config>()
101+
.expect("missing Config")
102+
.clone();
97103
let csp = req.extensions.get_mut::<Csp>().expect("missing CSP");
98104

99105
let content_type = res
@@ -110,7 +116,14 @@ impl AfterMiddleware for CspMiddleware {
110116

111117
if let Some(rendered) = csp.render(preset) {
112118
res.headers.set_raw(
113-
"Content-Security-Policy",
119+
// The Report-Only header tells the browser to just log CSP failures instead of
120+
// actually enforcing them. This is useful to check if the CSP works without
121+
// impacting production traffic.
122+
if config.csp_report_only {
123+
"Content-Security-Policy-Report-Only"
124+
} else {
125+
"Content-Security-Policy"
126+
},
114127
vec![rendered.as_bytes().to_vec()],
115128
);
116129
}

0 commit comments

Comments
 (0)