From b4e4bad62df52227d27dbac4c34dc9e4d5842ebc Mon Sep 17 00:00:00 2001 From: ldm0 Date: Tue, 15 Sep 2026 19:45:02 +0800 Subject: [PATCH] fix(csp): block importScripts redirects before network contact Carry owned worker policies and the importer location into per-request redirect checks, including cached redirect responses. Queue an event for each violated policy while preserving the original request URL and synchronous NetworkError behavior. Verify server contact counts, current-policy checks on cached redirects, multiple enforced/report-only policies, and asynchronous report fields. --- .../global_scope/content_security_policy.rs | 2 +- .../src/worker/global_scope/import_scripts.rs | 164 +++++++++------ .../worker/thread/tests/imported_scripts.rs | 186 +++++++++++++++++- 3 files changed, 277 insertions(+), 75 deletions(-) diff --git a/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs b/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs index 5edcc772265..28d350e9e2f 100644 --- a/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs +++ b/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs @@ -49,7 +49,7 @@ fn worker_policy_url<'a>(state: &'a WorkerGlobalState, protected_url: &'a Url) - .unwrap_or(protected_url) } -fn worker_policy_violation( +pub(super) fn worker_policy_violation( protected_url: &Url, report_uri_enabled: bool, mut violation: ContentSecurityPolicyUrlViolation, diff --git a/moli-renderer-v8/src/worker/global_scope/import_scripts.rs b/moli-renderer-v8/src/worker/global_scope/import_scripts.rs index a5ffac5069b..3fde95868f6 100644 --- a/moli-renderer-v8/src/worker/global_scope/import_scripts.rs +++ b/moli-renderer-v8/src/worker/global_scope/import_scripts.rs @@ -1,13 +1,15 @@ use super::*; use crate::content_security_policy::{ - ContentSecurityPolicyRedirectStatus, ContentSecurityPolicyResourceKind, + ContentSecurityPolicyDisposition, ContentSecurityPolicyRedirectStatus, + ContentSecurityPolicyResourceKind, ContentSecurityPolicySourceLocation, + InheritedContentSecurityPolicy, + content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints, }; pub(super) struct WorkerImportScriptSource { pub(super) final_url: Url, pub(super) source: String, pub(super) muted_errors: bool, - redirect_urls: Vec, resource: Option, } @@ -45,13 +47,11 @@ fn materialize_worker_import_source( state: &Rc>, script_url: &Url, ) -> Result { - check_import_script_csp( - scope, - state, - script_url, - script_url, - ContentSecurityPolicyRedirectStatus::NoRedirect, - )?; + let csp = WorkerImportScriptCsp::capture(scope, state, script_url); + if let Some(csp) = &csp { + csp.check_url(script_url, ContentSecurityPolicyRedirectStatus::NoRedirect) + .map_err(WorkerImportScriptError::network)?; + } match script_url.scheme() { "data" => { let source = @@ -68,7 +68,6 @@ fn materialize_worker_import_source( final_url: script_url.clone(), source, muted_errors: false, - redirect_urls: Vec::new(), resource: None, }) } @@ -85,7 +84,6 @@ fn materialize_worker_import_source( final_url: script_url.clone(), source: body, muted_errors: false, - redirect_urls: Vec::new(), resource: None, }) } @@ -109,17 +107,16 @@ fn materialize_worker_import_source( referrer_policy, network_partition_key, policy_context, + csp.map(|csp| { + moli_fetch::RequestRedirectCheck::new(move |checked_url| { + csp.check_url( + checked_url, + ContentSecurityPolicyRedirectStatus::FollowedRedirect, + ) + }) + }), ) .map_err(WorkerImportScriptError::network)?; - for checked_url in &source.redirect_urls { - check_import_script_csp( - scope, - state, - script_url, - checked_url, - ContentSecurityPolicyRedirectStatus::FollowedRedirect, - )?; - } if let Some(resource) = source.resource.clone() { report_service_worker_imported_script_loaded(state, resource); } @@ -131,50 +128,88 @@ fn materialize_worker_import_source( } } -fn check_import_script_csp( - scope: &mut v8::PinScope<'_, '_>, - state: &Rc>, - request_url: &Url, - checked_url: &Url, - redirect_status: ContentSecurityPolicyRedirectStatus, -) -> Result<(), WorkerImportScriptError> { - let (wake_tx, mut report, mut enforce) = { - let state = state.borrow(); - let Some(protected_url) = state.current_script_url.as_ref() else { - return Ok(()); +// Redirect checks run on the network thread. Keep the caller's location and +// an owned policy snapshot, and send violations back to the Worker's task queue. +struct WorkerImportScriptCsp { + policy: InheritedContentSecurityPolicy, + protected_url: Url, + request_url: Url, + location: ContentSecurityPolicySourceLocation, + wake_tx: tokio::sync::mpsc::UnboundedSender, +} + +impl WorkerImportScriptCsp { + fn capture( + scope: &mut v8::PinScope<'_, '_>, + state: &Rc>, + request_url: &Url, + ) -> Option { + let (policy, protected_url, wake_tx) = { + let state = state.borrow(); + ( + content_security_policy::worker_policy_snapshot(&state), + state.current_script_url.clone()?, + state.worker_wake_tx.clone(), + ) }; - ( - state.worker_wake_tx.clone(), - worker_content_security_policy_report_only_violation_for_checked_url_with_redirect_status( - &state, protected_url, checked_url, request_url, ContentSecurityPolicyResourceKind::WorkerScript, redirect_status, - ), - worker_content_security_policy_violation_for_checked_url_with_redirect_status( - &state, protected_url, checked_url, request_url, ContentSecurityPolicyResourceKind::WorkerScript, redirect_status, - ), - ) - }; - // importScripts throws synchronously, but CSP events run in a later task. - // Capture the caller now, before its stack is lost or imported code runs. - if report.is_some() || enforce.is_some() { - let location = - crate::content_security_policy::ContentSecurityPolicySourceLocation::capture(scope); - for violation in [&mut report, &mut enforce].into_iter().flatten() { - location.apply_to(violation); + if policy.header_policies.is_empty() + && policy.meta_policies.is_empty() + && policy.report_only_policies.is_empty() + { + return None; } + Some(Self { + policy, + protected_url, + request_url: request_url.clone(), + location: ContentSecurityPolicySourceLocation::capture(scope), + wake_tx, + }) } - if let Some(violation) = report { - let _ = wake_tx.send(WorkerMessage::DispatchContentSecurityPolicyViolation( - Box::new(violation), - )); + + fn check_url( + &self, + checked_url: &Url, + redirect_status: ContentSecurityPolicyRedirectStatus, + ) -> Result<(), String> { + let mut failure = None; + for disposition in [ + ContentSecurityPolicyDisposition::Report, + ContentSecurityPolicyDisposition::Enforce, + ] { + for (policy, report_uri_enabled) in self.policy.policies(disposition) { + let Some(violation) = content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints( + std::slice::from_ref(policy), + self.policy.self_url.as_ref().unwrap_or(&self.protected_url), + checked_url, + &self.request_url, + ContentSecurityPolicyResourceKind::WorkerScript, + redirect_status, + disposition, + &self.policy.reporting_endpoints, + ) else { + continue; + }; + let mut violation = content_security_policy::worker_policy_violation( + &self.protected_url, + report_uri_enabled, + violation, + ); + self.location.apply_to(&mut violation); + if disposition == ContentSecurityPolicyDisposition::Enforce { + failure.get_or_insert_with(|| { + worker_content_security_policy_error_message(&violation, "importScripts") + }); + } + let _ = self + .wake_tx + .send(WorkerMessage::DispatchContentSecurityPolicyViolation( + Box::new(violation), + )); + } + } + failure.map_or(Ok(()), Err) } - if let Some(violation) = enforce { - let message = worker_content_security_policy_error_message(&violation, "importScripts"); - let _ = wake_tx.send(WorkerMessage::DispatchContentSecurityPolicyViolation( - Box::new(violation), - )); - return Err(WorkerImportScriptError::network(message)); - } - Ok(()) } fn ensure_worker_import_script_mime_acceptable( @@ -199,6 +234,7 @@ pub(super) fn fetch_worker_import_source_blocking( referrer_policy: Option, network_partition_key: Option, policy_context: crate::types::SubresourcePolicyContext, + redirect_check: Option, ) -> Result { let request_url = script_url.clone(); let mut request = moli_fetch::Request::new("GET", script_url.as_str(), None, vec![]) @@ -211,6 +247,9 @@ pub(super) fn fetch_worker_import_source_blocking( ..moli_fetch::ScriptFetchRequestMetadata::default() }) .with_network_partition_key(network_partition_key); + if let Some(redirect_check) = redirect_check { + request = request.with_redirect_check(redirect_check); + } let request_initiator_url = initiator_url.clone(); if let Some(ref initiator_url) = request_initiator_url { request = request @@ -285,11 +324,6 @@ pub(super) fn fetch_worker_import_source_blocking( final_url: head.final_url, source: body, muted_errors, - redirect_urls: head - .redirect_chain - .into_iter() - .map(|redirect| redirect.to_url) - .collect(), resource: Some(resource), }) } diff --git a/moli-renderer-v8/src/worker/thread/tests/imported_scripts.rs b/moli-renderer-v8/src/worker/thread/tests/imported_scripts.rs index 7c24be7cf4d..379ad6648b6 100644 --- a/moli-renderer-v8/src/worker/thread/tests/imported_scripts.rs +++ b/moli-renderer-v8/src/worker/thread/tests/imported_scripts.rs @@ -1,5 +1,39 @@ use super::*; +struct ImportScriptHttpServer { + url: String, + requests: Arc>>, + task: JoinHandle<()>, +} + +impl ImportScriptHttpServer { + async fn spawn(response: String) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let requests = Arc::new(parking_lot::Mutex::new(Vec::new())); + let observed = requests.clone(); + let task = tokio::spawn(async move { + loop { + let (mut stream, _) = listener.accept().await.unwrap(); + let request = read_http_request_head(&mut stream).await.unwrap(); + observed.lock().push(request); + stream.write_all(response.as_bytes()).await.unwrap(); + } + }); + Self { + url, + requests, + task, + } + } +} + +impl Drop for ImportScriptHttpServer { + fn drop(&mut self) { + self.task.abort(); + } +} + #[tokio::test] async fn worker_importscripts_trusted_types_reports_keep_script_and_document_locations_separate() { ensure_v8(); @@ -165,14 +199,12 @@ async fn worker_importscripts_redirects_check_csp_and_ignore_redirected_paths() (true, false, r#"["ok",true,["report"],true]"#), (false, true, r#"["ok",true,[],true]"#), ] { - let (foreign_url, foreign_server) = spawn_path_response_http_server(vec![( - "/redirect-target/foreign.js", - "HTTP/1.1 200 OK", - "text/javascript", - "self.loaded = true;".into(), - Duration::ZERO, - )]) - .await; + let body = "self.loaded = true;"; + let foreign = ImportScriptHttpServer::spawn(format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + )).await; + let foreign_url = &foreign.url; let response = format!( "HTTP/1.1 302 Found\r\nLocation: {foreign_url}/redirect-target/foreign.js\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ); @@ -226,10 +258,146 @@ async fn worker_importscripts_redirects_check_csp_and_ignore_redirected_paths() "report={report_only}, allow={allow_foreign}" ); server.await.unwrap(); - foreign_server.await.unwrap(); + assert_eq!( + foreign.requests.lock().len(), + usize::from(report_only || allow_foreign), + "an enforced CSP violation must stop before contacting the redirect target", + ); } } +#[tokio::test] +async fn worker_importscripts_csp_reports_all_policies_before_and_after_redirects() { + ensure_v8(); + for redirected in [false, true] { + let foreign = ImportScriptHttpServer::spawn( + "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(), + ).await; + let target = format!("{}/private/script.js?secret=1", foreign.url); + let source = ImportScriptHttpServer::spawn(format!( + "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + )).await; + let request = if redirected { + format!("{}/redirect.js", source.url) + } else { + target + }; + let script = r#" + let name; + try { + importScripts(REQUEST); + } catch (error) { name = error.name; } + let microtaskRan = false; + queueMicrotask(() => microtaskRan = true); + const events = []; + addEventListener('securitypolicyviolation', event => { + events.push([ + event.originalPolicy, event.disposition, event.effectiveDirective, + event.blockedURI, event.sourceFile, event.lineNumber, + event.columnNumber, microtaskRan + ]); + if (events.length === 4) { postMessage({name, events}); close(); } + }); + "# + .replace("REQUEST", &serde_json::to_string(&request).unwrap()); + let mut handle = spawn_test_worker_with_options( + WorkerSpawnOptions::new(script, format!("{}/worker.js?caller=1", source.url)) + .with_content_security_policies(vec![ + "script-src 'self'".into(), + "script-src-elem 'self'".into(), + ]) + .with_content_security_report_only_policies(vec![ + "default-src 'self'".into(), + "script-src 'self'; script-src-elem 'self'".into(), + ]), + ); + let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap(); + let actual: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap(); + let location = format!("{}/worker.js", source.url); + assert_eq!( + actual, + serde_json::json!({ + "name": "NetworkError", + "events": [ + ["default-src 'self'", "report", "script-src-elem", request, location, 4, 17, true], + ["script-src 'self'; script-src-elem 'self'", "report", "script-src-elem", request, location, 4, 17, true], + ["script-src 'self'", "enforce", "script-src-elem", request, location, 4, 17, true], + ["script-src-elem 'self'", "enforce", "script-src-elem", request, location, 4, 17, true], + ], + }) + ); + assert_eq!(source.requests.lock().len(), usize::from(redirected)); + assert!(foreign.requests.lock().is_empty()); + } +} + +#[tokio::test] +async fn worker_importscripts_cached_redirects_use_the_current_worker_policy() { + ensure_v8(); + let body = "self.loaded = true;"; + let foreign = ImportScriptHttpServer::spawn(format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + )).await; + let source = ImportScriptHttpServer::spawn(format!( + "HTTP/1.1 302 Found\r\nLocation: {}/imported.js\r\nCache-Control: max-age=600\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + foreign.url + )).await; + let cache_dir = std::env::temp_dir().join(format!( + "moli-worker-importscripts-csp-{}-{}", + std::process::id(), + fastrand::u64(..), + )); + let mut config = FetchConfig::default(); + config.set_http_cache_dir(Some(cache_dir.display().to_string())); + let client = ResourceRequestClient::new(&config).unwrap(); + for (blocked, contacts) in [(false, 1), (true, 1), (false, 2)] { + let script = r#" + let name; + try { importScripts('./redirect.js'); } catch (error) { name = error.name; } + if (name) { + addEventListener('securitypolicyviolation', event => { + postMessage([name, self.loaded === true, event.effectiveDirective]); + close(); + }); + } else { postMessage(['ok', self.loaded === true]); close(); } + "#; + let mut handle = spawn_test_worker_with_options( + WorkerSpawnOptions::new_with_request_client( + script.into(), + format!("{}/worker.js", source.url), + client.clone(), + ) + .with_content_security_policies(vec![if blocked { + "script-src 'self'".into() + } else { + "script-src http:".into() + }]), + ); + let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap(); + assert_eq!( + expect_post_json(message), + if blocked { + r#"["NetworkError",false,"script-src-elem"]"# + } else { + r#"["ok",true]"# + } + ); + assert_eq!( + source.requests.lock().len(), + 1, + "the redirect should come from the HTTP cache after the first load" + ); + assert_eq!( + foreign.requests.lock().len(), + contacts, + "cached redirects must honor the current worker's CSP before contacting the target" + ); + } + drop(client); + std::fs::remove_dir_all(cache_dir).unwrap(); +} + #[tokio::test] async fn worker_importscripts_cross_origin_does_not_bypass_module_cors() { ensure_v8();