fix(csp): enforce typed worker module network policies

This commit is contained in:
ldm0
2026-11-21 20:03:37 +08:00
parent 2c37882132
commit 4ea81c260c
6 changed files with 394 additions and 10 deletions
@@ -109,7 +109,7 @@ impl ModuleFetchCspContext {
let message = enforce.first().map(|violation| {
format!(
"Module request blocked by Content Security Policy directive `{}`",
violation.effective_directive
violation.effective_directive,
)
});
let mut state = self.0.state.lock();
@@ -130,9 +130,6 @@ impl ModuleFetchCspContext {
// Coalesced/cache consumers still validate every recorded redirect against
// their own policy. The transport owner's checks are not another owner's authority.
pub(crate) fn check_response(&self, response: &moli_fetch::Response) -> anyhow::Result<()> {
self.check_response_head(&response.head())
}
pub(crate) fn check_response_head(
&self,
+35 -3
View File
@@ -1,4 +1,3 @@
use super::handle::WorkerErrorPhase;
mod module_map;
mod tree;
@@ -33,8 +32,12 @@ use tokio::sync::mpsc;
use url::Url;
use super::global_scope::worker_current_script_url;
use super::handle::{WorkerParentErrorEventKind, WorkerScriptResource, WorkerScriptResourceKind};
use crate::content_security_policy::ContentSecurityPolicyUrlViolation;
use super::handle::{
WorkerErrorPhase, WorkerParentErrorEventKind, WorkerScriptResource, WorkerScriptResourceKind,
};
use crate::content_security_policy::{
ContentSecurityPolicySourceLocation, ContentSecurityPolicyUrlViolation,
};
#[derive(Clone)]
pub(super) struct WorkerBootstrapError {
@@ -433,6 +436,7 @@ pub(super) fn evaluate_module_worker_bootstrap_source(
),
target: WorkerModuleTreeTarget::Bootstrap,
options: WorkerModuleGraphFetchOptions {
root_source_location: None,
initiator_url: static_import_initiator_url.unwrap_or(root_url),
csp_source: WorkerModuleGraphFetchCspSource::StaticModuleGraph,
browser_request_metadata: BrowserRequestMetadata::Worker,
@@ -831,6 +835,7 @@ pub(super) fn run_next_worker_dynamic_module_import(scope: &mut v8::PinScope<'_,
position: module_tree::TextPosition::default(),
});
let options = WorkerModuleGraphFetchOptions {
root_source_location: Some((key.clone(), job.source_location.clone())),
initiator_url: job.fetch_initiator_url.clone(),
csp_source: WorkerModuleGraphFetchCspSource::DynamicImportGraph,
browser_request_metadata: job.browser_request_metadata(),
@@ -1320,6 +1325,7 @@ impl WorkerDynamicModuleResolver {
attributes: ModuleAttributesKey,
phase: ModuleImportPhase,
audio_worklet_bootstrap: bool,
source_location: ContentSecurityPolicySourceLocation,
) {
self.next_import_id = self
.next_import_id
@@ -1336,6 +1342,7 @@ impl WorkerDynamicModuleResolver {
attributes,
phase,
audio_worklet_bootstrap,
source_location,
});
}
}
@@ -1350,6 +1357,7 @@ struct WorkerDynamicModuleImportJob {
attributes: ModuleAttributesKey,
phase: ModuleImportPhase,
audio_worklet_bootstrap: bool,
source_location: ContentSecurityPolicySourceLocation,
}
impl WorkerDynamicModuleImportJob {
@@ -1373,6 +1381,7 @@ struct WorkerModuleGraphFetchOptions {
csp_source: WorkerModuleGraphFetchCspSource,
referrer_policy: Option<String>,
browser_request_metadata: BrowserRequestMetadata,
root_source_location: Option<(WorkerModuleKey, ContentSecurityPolicySourceLocation)>,
}
#[derive(Clone)]
@@ -1384,6 +1393,7 @@ pub(super) struct WorkerModuleGraphFetchRequest {
credentials_mode: RequestCredentialsMode,
referrer_policy: Option<String>,
browser_request_metadata: BrowserRequestMetadata,
source_location: Option<ContentSecurityPolicySourceLocation>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -1410,9 +1420,22 @@ impl WorkerModuleGraphFetchRequest {
credentials_mode,
referrer_policy,
browser_request_metadata,
source_location: None,
}
}
fn with_source_location(
mut self,
source_location: ContentSecurityPolicySourceLocation,
) -> Self {
self.source_location = Some(source_location);
self
}
pub(super) fn source_location(&self) -> Option<&ContentSecurityPolicySourceLocation> {
self.source_location.as_ref()
}
pub(super) fn module_key(&self) -> WorkerModuleKey {
self.key.clone()
}
@@ -2625,6 +2648,14 @@ fn queue_worker_dynamic_import<'s>(
);
return Some(promise);
};
let source_location = super::global_scope::worker_content_security_policy_snapshot(scope)
.filter(|policy| {
!policy.header_policies.is_empty()
|| !policy.meta_policies.is_empty()
|| !policy.report_only_policies.is_empty()
})
.map(|_| ContentSecurityPolicySourceLocation::capture(scope))
.unwrap_or_default();
dynamic_imports.borrow_mut().queue_import(
v8::Global::new(scope, context),
v8::Global::new(scope, resolver),
@@ -2634,6 +2665,7 @@ fn queue_worker_dynamic_import<'s>(
attributes,
phase,
audio_worklet_import == AudioWorkletDynamicImport::Bootstrap,
source_location,
);
Some(promise)
}
@@ -56,7 +56,12 @@ impl WorkerModuleMap {
self.next_fetch_id = fetch_id
.checked_add(1)
.expect("worker module fetch id space exhausted");
let request = WorkerModuleGraphFetchRequest::new(
let source_location = options
.root_source_location
.as_ref()
.filter(|(root, _)| root == &key)
.map(|(_, location)| location.clone());
let mut request = WorkerModuleGraphFetchRequest::new(
fetch_id,
key,
options.initiator_url.clone(),
@@ -65,6 +70,9 @@ impl WorkerModuleMap {
options.referrer_policy.clone(),
options.browser_request_metadata,
);
if let Some(location) = source_location {
request = request.with_source_location(location);
}
entry.insert(WorkerModuleMapEntry::Fetching {
request: Box::new(request.clone()),
clients: vec![client],
@@ -150,6 +158,7 @@ mod tests {
let url = url::Url::parse("https://example.test/module.mjs").unwrap();
let key = WorkerModuleKey::javascript_or_wasm(url.clone());
let options = WorkerModuleGraphFetchOptions {
root_source_location: None,
initiator_url: url,
csp_source: WorkerModuleGraphFetchCspSource::DynamicImportGraph,
referrer_policy: None,
+6 -2
View File
@@ -720,19 +720,23 @@ fn start_worker_module_graph_fetch(
};
let resource_kind = request.module_type().csp_resource_kind(resource_kind);
let initiator = request.initiator_url().clone();
let source_location = request.source_location().cloned();
let csp_context = crate::content_security_policy::ModuleFetchCspContext::new(
request.url().clone(),
None,
move |url, original_url, redirect_status| {
let check = |disposition| {
policy.policies(disposition).find_map(|(value, report_uri_enabled)| {
policy.policies(disposition).filter_map(|(value, report_uri_enabled)| {
let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
std::slice::from_ref(value), &initiator, policy.self_url.as_ref(), url, original_url, resource_kind,
redirect_status, disposition, &policy.reporting_endpoints, crate::content_security_policy::ContentSecurityPolicyUrlRequest::Standard,
)?;
if !report_uri_enabled { violation.report_uri_endpoints.clear(); }
if redirect_status == ContentSecurityPolicyRedirectStatus::NoRedirect {
if let Some(location) = &source_location { location.apply_to(&mut violation); }
}
Some(violation)
})
}).collect::<Vec<_>>()
};
(
check(ContentSecurityPolicyDisposition::Report),
@@ -11,6 +11,7 @@ mod native_exception_data;
mod event_target_prototype;
mod module_csp;
mod module_csp_typed;
mod notification_init;
mod request_init;
mod text_codecs;
@@ -0,0 +1,341 @@
use super::*;
use crate::worker::WorkerGlobalKind;
use serde_json::{Value, json};
struct ModuleServer {
url: String,
requests: Arc<parking_lot::Mutex<Vec<String>>>,
task: JoinHandle<()>,
}
impl ModuleServer {
async fn spawn(response: impl Fn(&str) -> String + Send + 'static) -> 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.clone());
stream
.write_all(response(&request).as_bytes())
.await
.unwrap();
}
});
Self {
url,
requests,
task,
}
}
async fn modules() -> Self {
Self::spawn(|request| {
let (mime, body) = if request.starts_with("GET /data.json") {
("application/json", r#"{"answer":42}"#)
} else if request.starts_with("GET /data.txt") {
("text/plain", "module-text")
} else {
("text/javascript", "export default 42;")
};
format!(
"HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nAccess-Control-Allow-Origin: *\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}).await
}
}
impl Drop for ModuleServer {
fn drop(&mut self) {
self.task.abort();
}
}
fn global_kinds() -> [WorkerGlobalKind; 2] {
[
WorkerGlobalKind::Dedicated {
name: String::new(),
},
WorkerGlobalKind::Shared {
name: "module-csp".into(),
storage_key: moli_storage_key::MoliStorageKey::first_party_from_url(
&url::Url::parse("http://127.0.0.1/").unwrap(),
None,
),
},
]
}
fn probe(requests: Value) -> String {
r#"
const events = [];
addEventListener('securitypolicyviolation', event => events.push({
directive: event.effectiveDirective, disposition: event.disposition,
policy: event.originalPolicy, blockedURI: event.blockedURI,
documentURI: event.documentURI, sourceFile: event.sourceFile,
line: event.lineNumber, column: event.columnNumber,
native: event instanceof SecurityPolicyViolationEvent, trusted: event.isTrusted
}));
(async () => {
const results = [];
for (const [url, type] of REQUESTS) {
const result = {};
try {
const imported = type === 'javascript' ? import(url) : import(url, {with: {type}});
const module = await imported;
result.value = type === 'json' ? module.default.answer : module.default;
} catch (error) {
result.error = error.name;
result.native = error instanceof TypeError;
}
result.events = events.splice(0);
results.push(result);
}
console.log(JSON.stringify(results));
})().catch(error => console.error(String(error.stack || error)));
"#
.replace("REQUESTS", &requests.to_string())
}
async fn result(mut worker: WorkerTestHandle) -> Value {
let text = timeout(TIMEOUT, async {
loop {
match worker
.recv()
.await
.expect("module worker must remain alive")
{
WorkerToParentMessage::Console(console) => break console.message,
WorkerToParentMessage::Error(WorkerErrorReport { message, .. }) => {
panic!("{message}")
}
_ => {}
}
}
})
.await
.expect("module imports must settle");
worker.terminate_and_join();
serde_json::from_str(text.strip_prefix("log: ").expect(&text)).unwrap()
}
#[tokio::test]
async fn worker_typed_module_csp_blocks_before_contact_and_reports_every_policy() {
ensure_v8();
let server = ModuleServer::modules().await;
for kind in [WorkerScriptKind::Classic, WorkerScriptKind::Module] {
for global in global_kinds() {
let worker = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
probe(json!([
[format!("{}/data.json", server.url), "json"],
[format!("{}/data.txt", server.url), "text"]
])),
format!("{}/main.js", server.url),
)
.with_script_kind(kind)
.with_global_kind(global)
.with_module_static_import_content_security_policies(vec!["connect-src *".into()])
.with_content_security_policies(vec![
"connect-src 'none'".into(),
"default-src 'none'".into(),
])
.with_content_security_report_only_policies(vec![
"connect-src 'none'".into(),
"default-src 'none'".into(),
]),
);
let actual = result(worker).await;
for (index, extension) in ["json", "txt"].into_iter().enumerate() {
assert_eq!(actual[index]["error"], "TypeError", "{actual}");
assert_eq!(actual[index]["native"], true);
let events = actual[index]["events"].as_array().unwrap();
assert_eq!(events.len(), 4, "{actual}");
for (event, (disposition, policy)) in events.iter().zip([
("report", "connect-src 'none'"),
("report", "default-src 'none'"),
("enforce", "connect-src 'none'"),
("enforce", "default-src 'none'"),
]) {
assert_eq!(event["directive"], "connect-src");
assert_eq!(event["disposition"], disposition);
assert_eq!(event["policy"], policy);
assert_eq!(
event["blockedURI"],
format!("{}/data.{extension}", server.url)
);
assert_eq!(event["documentURI"], format!("{}/main.js", server.url));
assert_eq!(event["sourceFile"], format!("{}/main.js", server.url));
assert!(event["line"].as_i64().unwrap() > 0);
assert!(event["column"].as_i64().unwrap() > 0);
assert_eq!(event["native"], true);
assert_eq!(event["trusted"], true);
}
}
}
}
assert!(
server.requests.lock().is_empty(),
"CSP must prevent network contact"
);
}
#[tokio::test]
async fn worker_typed_module_csp_uses_connect_instead_of_script_directives() {
ensure_v8();
for kind in [WorkerScriptKind::Classic, WorkerScriptKind::Module] {
for global in global_kinds() {
let server = ModuleServer::modules().await;
let worker = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
probe(json!([
[format!("{}/data.json", server.url), "json"],
[format!("{}/data.txt", server.url), "text"],
[format!("{}/data.js", server.url), "javascript"]
])),
format!("{}/main.js", server.url),
)
.with_script_kind(kind)
.with_global_kind(global)
.with_content_security_policies(vec![
"script-src 'none'; connect-src 'self'".into(),
])
.with_content_security_report_only_policies(vec!["connect-src 'none'".into()]),
);
let actual = result(worker).await;
assert_eq!(actual[0]["value"], 42, "{actual}");
assert_eq!(actual[1]["value"], "module-text", "{actual}");
for index in 0..2 {
assert_eq!(actual[index]["events"].as_array().unwrap().len(), 1);
assert_eq!(actual[index]["events"][0]["directive"], "connect-src");
assert_eq!(actual[index]["events"][0]["disposition"], "report");
}
assert_eq!(actual[2]["error"], "TypeError", "{actual}");
assert_eq!(actual[2]["events"][0]["directive"], "script-src-elem");
let requests = server.requests.lock();
assert_eq!(requests.len(), 2);
for (request, destination) in requests.iter().zip(["json", "text"]) {
assert!(
request
.to_ascii_lowercase()
.contains(&format!("sec-fetch-dest: {destination}\r\n")),
"{request}"
);
}
}
}
}
#[tokio::test]
async fn worker_typed_module_redirect_csp_stops_each_forbidden_hop_once() {
ensure_v8();
for global in global_kinds() {
for (extension, module_type, value) in [
("json", "json", json!(42)),
("txt", "text", json!("module-text")),
] {
for enforce in [false, true] {
let target = ModuleServer::modules().await;
let target_url = format!("{}/data.{extension}", target.url);
let source = ModuleServer::spawn(move |_| format!(
"HTTP/1.1 302 Found\r\nLocation: {target_url}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)).await;
let request_url = format!("{}/redirect.{extension}", source.url);
let worker = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
probe(json!([[request_url, module_type]])),
format!("{}/main.js", source.url),
)
.with_global_kind(global.clone())
.with_content_security_policies(if enforce {
vec!["connect-src 'self'".into()]
} else {
vec![]
})
.with_content_security_report_only_policies(vec!["connect-src 'self'".into()]),
);
let actual = result(worker).await;
if enforce {
assert_eq!(actual[0]["error"], "TypeError", "{actual}");
} else {
assert_eq!(actual[0]["value"], value, "{actual}");
}
let events = actual[0]["events"].as_array().unwrap();
assert_eq!(events.len(), if enforce { 2 } else { 1 }, "{actual}");
for (index, event) in events.iter().enumerate() {
assert_eq!(event["directive"], "connect-src");
assert_eq!(
event["disposition"],
if index == 0 { "report" } else { "enforce" }
);
assert_eq!(event["blockedURI"], request_url);
assert_eq!(event["sourceFile"], "");
assert_eq!(event["line"], 0);
assert_eq!(event["column"], 0);
}
assert_eq!(source.requests.lock().len(), 1);
assert_eq!(
target.requests.lock().len(),
usize::from(!enforce),
"enforced redirects must never reach the target"
);
}
}
}
}
#[tokio::test]
async fn worker_typed_module_static_import_uses_creator_connect_policy() {
ensure_v8();
for global in global_kinds() {
for blocked in [false, true] {
let server = ModuleServer::modules().await;
let mut worker = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
"import json from './data.json' with {type: 'json'};\n\
import text from './data.txt' with {type: 'text'};\n\
console.log(JSON.stringify([json.answer, text]));"
.into(),
format!("{}/main.js", server.url),
)
.with_global_kind(global.clone())
.with_script_kind(WorkerScriptKind::Module)
.with_module_static_import_content_security_policies(vec![
if blocked {
"worker-src *; connect-src 'none'"
} else {
"connect-src 'self'; script-src 'none'"
}
.into(),
])
.with_content_security_policies(vec![
if blocked {
"connect-src *"
} else {
"connect-src 'none'"
}
.into(),
]),
);
if blocked {
let message = timeout(TIMEOUT, worker.recv()).await.unwrap().unwrap();
match message {
WorkerToParentMessage::Error(WorkerErrorReport { message, phase, .. }) => {
assert!(message.contains("Content Security Policy"), "{message}");
assert_eq!(phase, WorkerErrorPhase::Bootstrap);
}
other => panic!("expected CSP bootstrap error, got {other:?}"),
}
worker.terminate_and_join();
assert!(server.requests.lock().is_empty());
} else {
assert_eq!(result(worker).await, json!([42, "module-text"]));
assert_eq!(server.requests.lock().len(), 2);
}
}
}
}