fix(workers): enforce response CSP gates

This commit is contained in:
ldm0
2026-11-02 06:01:27 +08:00
parent cbefbeea5e
commit 6bd1f710c1
15 changed files with 368 additions and 64 deletions
@@ -47,7 +47,6 @@ content-security-policy/inheritance/javascript-url-open-in-main-window.html
content-security-policy/inheritance/location-reload.html
content-security-policy/inheritance/window.html
content-security-policy/inside-worker/dedicatedworker-report-only.html
content-security-policy/inside-worker/dedicatedworker-worker-src.html
content-security-policy/inside-worker/serviceworker-report-only.https.sub.html
content-security-policy/meta/sandbox-iframe.html
content-security-policy/navigation/javascript-url-navigation-evaluated-to-string-inherits-csp.html
@@ -578,6 +578,7 @@ content-security-policy/img-src/img-src-targeting.html
content-security-policy/img-src/img-src-wildcard-allowed.html
content-security-policy/inheritance/blob-inherits-from-meta-http-equiv-with-invalid-characters.html
content-security-policy/inheritance/inherited-csp-list-modifications-are-local.html
content-security-policy/inside-worker/dedicatedworker-worker-src.html
content-security-policy/media-src/media-src-7_1.html
content-security-policy/media-src/media-src-7_2.html
content-security-policy/media-src/media-src-blocked-blob-url.html
+2 -2
View File
@@ -1338,7 +1338,7 @@ impl ContentSecurityPolicyResourceKind {
Self::DocumentFont => "font-src",
Self::DocumentScriptElement | Self::WorkerDynamicModuleImport => SCRIPT_SRC_ELEM,
Self::DocumentStyleElement => STYLE_SRC_ELEM,
Self::SharedWorkerScript | Self::WorkerStaticModuleImport => WORKER_SRC,
Self::WorkerConstructor | Self::WorkerStaticModuleImport => WORKER_SRC,
Self::WorkerConnect => CONNECT_SRC,
Self::WorkerScript => SCRIPT_SRC,
}
@@ -1354,7 +1354,7 @@ impl ContentSecurityPolicyResourceKind {
Self::DocumentFont => &["font-src", DEFAULT_SRC],
Self::DocumentScriptElement => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
Self::DocumentStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC],
Self::SharedWorkerScript => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
Self::WorkerConstructor => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
Self::WorkerConnect => &[CONNECT_SRC, DEFAULT_SRC],
Self::WorkerDynamicModuleImport => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
Self::WorkerScript => &[SCRIPT_SRC, DEFAULT_SRC],
+13 -13
View File
@@ -698,10 +698,10 @@ fn frame_ancestors_matches_origins_and_rejects_opaque_ancestors() {
}
#[test]
fn worker_src_none_blocks_shared_worker_script() {
fn worker_src_none_blocks_worker_constructor() {
assert!(!allowed(
"worker-src 'none'; script-src 'self'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
}
@@ -737,34 +737,34 @@ fn document_font_requests_use_font_src_and_default_src() {
}
#[test]
fn shared_worker_script_uses_script_src_and_default_src_fallbacks() {
fn worker_constructor_uses_script_src_and_default_src_fallbacks() {
assert!(!allowed(
"script-src 'none'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
assert!(!allowed(
"default-src 'none'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
assert!(allowed(
"default-src 'self'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
}
#[test]
fn shared_worker_script_uses_child_src_before_script_src_fallback() {
fn worker_constructor_uses_child_src_before_script_src_fallback() {
assert!(!allowed(
"child-src 'none'; script-src 'self'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
assert!(allowed(
"child-src https://workers.test; script-src 'none'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://workers.test/worker.js"
));
}
@@ -789,15 +789,15 @@ fn document_script_element_uses_script_src_elem_fallbacks() {
}
#[test]
fn worker_src_takes_precedence_for_shared_worker_scripts() {
fn worker_src_takes_precedence_for_worker_constructors() {
assert!(allowed(
"default-src 'none'; script-src 'none'; worker-src 'self'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
assert!(!allowed(
"default-src *; script-src *; worker-src 'none'",
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
"https://app.test/worker.js"
));
}
@@ -1428,7 +1428,7 @@ fn exact_host_port_wildcards_apply_across_resource_kinds() {
ContentSecurityPolicyResourceKind::DocumentStyleElement,
ContentSecurityPolicyResourceKind::WorkerConnect,
ContentSecurityPolicyResourceKind::WorkerScript,
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
] {
for source in ["https://cdn.test:*", "http://cdn.test:*", "CDN.TEST:*"] {
+1 -1
View File
@@ -10,7 +10,7 @@ pub enum ContentSecurityPolicyResourceKind {
DocumentFont,
DocumentScriptElement,
DocumentStyleElement,
SharedWorkerScript,
WorkerConstructor,
WorkerConnect,
WorkerDynamicModuleImport,
WorkerScript,
@@ -471,38 +471,37 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
return;
}
};
let (script_url, script_source) = match materialize_nested_worker_script_source(
&resolved_url,
&nested_context,
worker_options.worker_type,
worker_options.credentials_mode.0,
) {
Ok(source) => source,
Err(message) => {
let _ =
nested_context
.wake_tx
.send(crate::worker::WorkerMessage::NestedWorkerEvent {
worker_id: nested_context.worker_id,
message: Box::new(crate::worker::WorkerToParentMessage::Error {
message,
filename: resolved_url.to_string(),
lineno: 0,
colno: 0,
event_kind: crate::worker::WorkerParentErrorEventKind::Event,
phase: crate::worker::WorkerErrorPhase::Bootstrap,
source: crate::worker::WorkerErrorSource::Runtime,
}),
});
set_private_value(
scope,
worker,
WORKER_ID_SLOT,
v8::Number::new(scope, nested_context.worker_id.as_u64() as f64).into(),
);
return;
}
};
if let Err(message) =
crate::worker::check_and_queue_nested_worker_constructor_csp(scope, &resolved_url)
{
queue_nested_worker_script_load_error(
scope,
worker,
&nested_context,
&resolved_url,
message,
);
return;
}
let (script_url, script_source) =
match materialize_nested_worker_script_source(
&resolved_url,
&nested_context,
worker_options.worker_type,
worker_options.credentials_mode.0,
) {
Ok(source) => source,
Err(message) => {
queue_nested_worker_script_load_error(
scope,
worker,
&nested_context,
&resolved_url,
message,
);
return;
}
};
let mut network_policy = nested_context.network_policy.clone();
network_policy.secure_context = Url::parse(&script_url).ok().is_some_and(|script_url| {
worker_secure_context_for_script_url(
@@ -749,6 +748,35 @@ pub(in crate::context_bootstrap) fn document_query_encoding_override(
.filter(|encoding| *encoding != encoding_rs::UTF_8)
}
fn queue_nested_worker_script_load_error(
scope: &mut v8::PinScope<'_, '_>,
worker: v8::Local<'_, v8::Object>,
context: &NestedWorkerContext,
script_url: &Url,
message: String,
) {
let _ = context
.wake_tx
.send(crate::worker::WorkerMessage::NestedWorkerEvent {
worker_id: context.worker_id,
message: Box::new(crate::worker::WorkerToParentMessage::Error {
message,
filename: script_url.to_string(),
lineno: 0,
colno: 0,
event_kind: crate::worker::WorkerParentErrorEventKind::Event,
phase: crate::worker::WorkerErrorPhase::Bootstrap,
source: crate::worker::WorkerErrorSource::Runtime,
}),
});
set_private_value(
scope,
worker,
WORKER_ID_SLOT,
v8::Number::new(scope, context.worker_id.as_u64() as f64).into(),
);
}
pub(in crate::context_bootstrap) fn worker_constructor_base_url(
host: &crate::native_bridge::JsContextHost,
) -> Url {
@@ -290,7 +290,7 @@ impl SharedWorkerScriptRequestPolicy {
&self.document_content_security_policies,
document_url,
script_url,
ContentSecurityPolicyResourceKind::SharedWorkerScript,
ContentSecurityPolicyResourceKind::WorkerConstructor,
|| {
format!(
"Failed to load shared worker script `{script_url}`: blocked by Content Security Policy."
@@ -5,9 +5,10 @@ use url::Url;
use crate::RendererSyntheticResponseBody;
use crate::content_security_policy::{
ContentSecurityPolicyDisposition, ContentSecurityPolicyRedirectStatus,
ContentSecurityPolicyResourceKind, ContentSecurityPolicyUrlViolation,
ContentSecurityPolicyViolationEventFields, content_security_policy_report_requests,
ContentSecurityPolicyDisposition, ContentSecurityPolicyNonUrlKind,
ContentSecurityPolicyRedirectStatus, ContentSecurityPolicyResourceKind,
ContentSecurityPolicyUrlViolation, ContentSecurityPolicyViolationEventFields,
content_security_policy_non_url_violation_with_source, content_security_policy_report_requests,
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints,
content_security_policy_trusted_types_sink_violation_with_disposition_and_reporting_endpoints,
content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints,
@@ -823,6 +824,34 @@ pub(super) fn worker_content_security_policy_violation(
)
}
pub(super) fn worker_eval_content_security_policy_violation(
state: &WorkerGlobalState,
protected_url: &Url,
allow_trusted_types_eval: bool,
source: Option<&str>,
disposition: ContentSecurityPolicyDisposition,
) -> Option<ContentSecurityPolicyUrlViolation> {
let policies = match disposition {
ContentSecurityPolicyDisposition::Enforce => &state.content_security_policies,
ContentSecurityPolicyDisposition::Report => &state.content_security_report_only_policies,
};
let kind = if allow_trusted_types_eval {
ContentSecurityPolicyNonUrlKind::TrustedTypesEval
} else {
ContentSecurityPolicyNonUrlKind::Eval
};
policies.iter().find_map(|policy| {
content_security_policy_non_url_violation_with_source(
policy,
protected_url,
kind,
source,
disposition,
&state.content_security_reporting_endpoints,
)
})
}
pub(super) fn worker_content_security_policy_violation_with_redirect_status(
state: &WorkerGlobalState,
protected_url: &Url,
@@ -1031,7 +1060,6 @@ pub(crate) fn worker_trusted_types_for_script_requirements(
),
)
}
pub(crate) fn worker_allows_trusted_types_eval(scope: &mut v8::PinScope<'_, '_>) -> Option<bool> {
Some(
crate::content_security_policy::content_security_policy_allows_trusted_types_eval(
@@ -200,7 +200,8 @@ pub(crate) use messaging::{
};
pub(super) use nested_workers::dispatch_nested_worker_event;
pub(crate) use nested_workers::{
NestedWorkerContext, forget_nested_worker_context, reserve_nested_worker_context,
NestedWorkerContext, check_and_queue_nested_worker_constructor_csp,
forget_nested_worker_context, reserve_nested_worker_context,
};
pub(super) use network_state::{
PausedWorkerSubresourceResponse, PendingWorkerCspReport, PendingWorkerFetch,
@@ -155,3 +155,47 @@ pub(in crate::worker) fn dispatch_nested_worker_event(
},
}
}
pub(crate) fn check_and_queue_nested_worker_constructor_csp(
scope: &mut v8::PinScope<'_, '_>,
request_url: &Url,
) -> Result<(), String> {
let state = get_worker_state(scope)
.expect("nested Worker construction requires an installed worker global state");
let (wake_tx, report_only_violation, enforce_violation) = {
let state = state.borrow();
let protected_url = state
.current_script_url
.as_ref()
.expect("nested Worker construction requires a current worker script URL");
(
state.worker_wake_tx.clone(),
worker_content_security_policy_report_only_violation(
&state,
protected_url,
request_url,
crate::content_security_policy::ContentSecurityPolicyResourceKind::WorkerConstructor,
),
worker_content_security_policy_violation(
&state,
protected_url,
request_url,
crate::content_security_policy::ContentSecurityPolicyResourceKind::WorkerConstructor,
),
)
};
if let Some(violation) = report_only_violation {
let _ = wake_tx.send(WorkerMessage::DispatchContentSecurityPolicyViolation(
Box::new(violation),
));
}
let Some(violation) = enforce_violation else {
return Ok(());
};
let message = worker_content_security_policy_error_message(&violation, "Worker");
let _ = wake_tx.send(WorkerMessage::DispatchContentSecurityPolicyViolation(
Box::new(violation),
));
Err(message)
}
+4
View File
@@ -145,6 +145,10 @@ pub(crate) enum WorkerMessage {
),
/// Run the worker's queued unhandled promise rejection notification task.
DispatchPendingPromiseRejections,
/// Dispatch a CSP violation queued while the current worker was still evaluating script.
DispatchContentSecurityPolicyViolation(
Box<crate::content_security_policy::ContentSecurityPolicyUrlViolation>,
),
/// A worker spawned from this worker has queued a parent-facing event.
NestedWorkerEvent {
worker_id: DedicatedWorkerId,
+4 -3
View File
@@ -24,9 +24,10 @@ mod timer_callback;
pub(crate) use data_url::decode_data_url_script_source;
pub(crate) use global_scope::{
NestedWorkerContext, WorkerGlobalState, WorkerOpfsCompletion, WorkerWebCryptoCompletion,
cancel_worker_opfs_task, check_worker_websocket_csp, close_worker_websocket,
dispatch_worker_trusted_types_sink_violation_event,
NestedWorkerContext, WorkerGlobalState, WorkerOpfsCompletion,
WorkerWebCryptoCompletion, cancel_worker_opfs_task,
check_and_queue_nested_worker_constructor_csp, check_worker_websocket_csp,
close_worker_websocket, dispatch_worker_trusted_types_sink_violation_event,
ensure_worker_opfs_directory_iterator_registry, ensure_worker_opfs_handle_registry,
forget_nested_worker_context, forget_worker_broadcast_channel_wrapper,
forget_worker_message_port_wrapper, get_worker_state, register_worker_blob_read_task,
+5 -6
View File
@@ -75,9 +75,10 @@ use super::global_scope::{
continue_pending_worker_fetch, continue_pending_worker_fetch_response,
continue_pending_worker_xhr, continue_pending_worker_xhr_response,
dispatch_nested_worker_event, dispatch_worker_csp_violation_event,
dispatch_worker_websocket_event, drain_service_worker_client_focus_result,
drain_service_worker_client_navigate_result, drain_service_worker_client_query_result,
drain_service_worker_clients_open_window_result, drain_service_worker_get_notifications_result,
dispatch_worker_csp_violation_event_for_state, dispatch_worker_websocket_event,
drain_service_worker_client_focus_result, drain_service_worker_client_navigate_result,
drain_service_worker_client_query_result, drain_service_worker_clients_open_window_result,
drain_service_worker_get_notifications_result,
drain_service_worker_periodic_sync_get_tags_result,
drain_service_worker_periodic_sync_registration_result,
drain_service_worker_periodic_sync_unregistration_result,
@@ -2674,9 +2675,7 @@ async fn worker_main(
let scope = &mut scope.init();
let ctx = v8::Local::new(scope, &context);
let scope = &mut v8::ContextScope::new(scope, ctx);
super::global_scope::dispatch_worker_csp_violation_event_for_state(
scope, &state, &violation,
);
dispatch_worker_csp_violation_event_for_state(scope, &state, &violation);
perform_worker_microtask_checkpoint_and_report_pending_promise_rejections(scope);
drain_worker_dynamic_module_imports(scope, &state, &module_graph_fetch_tx);
}
@@ -1620,3 +1620,107 @@ async fn worker_drop_terminates() {
drop(handle);
// If we reach here without hanging, the test passes.
}
#[tokio::test]
async fn nested_worker_constructor_csp_block_is_async_and_reports_to_parent_global() {
ensure_v8();
let mut handle = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
r#"
const result = {
constructed: false,
violation: null,
error: null,
ping: false
};
function finish() {
if (result.violation && result.error) {
postMessage(result);
close();
}
}
const child = new Worker("data:text/javascript,postMessage('ping')");
child.addEventListener("message", () => {
result.ping = true;
postMessage(result);
close();
});
addEventListener("securitypolicyviolation", event => {
result.violation = {
type: event.type,
effectiveDirective: event.effectiveDirective,
violatedDirective: event.violatedDirective,
blockedURI: event.blockedURI,
documentURI: event.documentURI,
originalPolicy: event.originalPolicy,
disposition: event.disposition,
instance: event instanceof SecurityPolicyViolationEvent
};
finish();
});
child.addEventListener("error", event => {
event.preventDefault();
result.error = {
messageIncludesCsp: event.message.includes("Content Security Policy"),
filename: event.filename
};
finish();
});
result.constructed = true;
"#
.into(),
"https://app.example/parent.js".into(),
)
.with_content_security_policies(vec!["worker-src 'none'".to_owned()]),
);
assert_eq!(
recv_post_json(&mut handle).await,
r#"{"constructed":true,"violation":{"type":"securitypolicyviolation","effectiveDirective":"worker-src","violatedDirective":"worker-src","blockedURI":"data","documentURI":"https://app.example/parent.js","originalPolicy":"worker-src 'none'","disposition":"enforce","instance":true},"error":{"messageIncludesCsp":true,"filename":"data:text/javascript,postMessage('ping')"},"ping":false}"#
);
}
#[tokio::test]
async fn nested_worker_constructor_report_only_csp_is_async_and_does_not_block() {
ensure_v8();
let mut handle = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
r#"
const result = {
constructed: false,
violation: null,
childMessage: null
};
function finish() {
if (result.violation && result.childMessage) {
postMessage(result);
close();
}
}
const child = new Worker("data:text/javascript,postMessage('ping')");
addEventListener("securitypolicyviolation", event => {
result.violation = {
effectiveDirective: event.effectiveDirective,
blockedURI: event.blockedURI,
disposition: event.disposition,
instance: event instanceof SecurityPolicyViolationEvent
};
finish();
});
child.addEventListener("message", event => {
result.childMessage = event.data;
finish();
});
result.constructed = true;
"#
.into(),
"https://app.example/parent.js".into(),
)
.with_content_security_report_only_policies(vec!["worker-src 'none'".to_owned()]),
);
assert_eq!(
recv_post_json(&mut handle).await,
r#"{"constructed":true,"violation":{"effectiveDirective":"worker-src","blockedURI":"data","disposition":"report","instance":true},"childMessage":"ping"}"#
);
}
@@ -1060,6 +1060,101 @@ async fn worker_trusted_script_eval_is_unwrapped_with_trusted_types_eval_keyword
assert_eq!(expect_post_json(msg), r#"{"trusted":7,"string":9}"#);
}
#[tokio::test]
async fn worker_trusted_types_eval_keyword_requires_enforced_trusted_types() {
ensure_v8();
for report_only_policies in [
Vec::new(),
vec!["require-trusted-types-for 'script'".to_owned()],
] {
let mut handle = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
r#"
let evalRan = false;
let errorName = null;
trustedTypes.createPolicy("default", { createScript: value => value });
addEventListener("securitypolicyviolation", event => {
postMessage({
evalRan,
errorName,
event: {
type: event.type,
effectiveDirective: event.effectiveDirective,
violatedDirective: event.violatedDirective,
blockedURI: event.blockedURI,
documentURI: event.documentURI,
originalPolicy: event.originalPolicy,
disposition: event.disposition,
instance: event instanceof SecurityPolicyViolationEvent,
},
});
close();
});
try {
eval("evalRan = true");
errorName = "allowed";
} catch (error) {
errorName = `${error.name}:${error instanceof EvalError}`;
}
postMessage({ phase: "evaluated", evalRan, errorName });
"#
.to_owned(),
"https://app.test/worker/main.js".to_owned(),
)
.with_content_security_policies(vec![
"script-src 'self' 'trusted-types-eval'".to_owned(),
])
.with_content_security_report_only_policies(report_only_policies),
);
let evaluated = timeout(TIMEOUT, handle.recv())
.await
.expect("timed out")
.expect("channel closed");
assert_eq!(
expect_post_json(evaluated),
r#"{"phase":"evaluated","evalRan":false,"errorName":"EvalError:true"}"#
);
let violation = timeout(TIMEOUT, handle.recv())
.await
.expect("timed out waiting for violation")
.expect("channel closed");
assert_eq!(
expect_post_json(violation),
r#"{"evalRan":false,"errorName":"EvalError:true","event":{"type":"securitypolicyviolation","effectiveDirective":"script-src","violatedDirective":"script-src","blockedURI":"eval","documentURI":"https://app.test/worker/main.js","originalPolicy":"script-src 'self' 'trusted-types-eval'","disposition":"enforce","instance":true}}"#
);
}
}
#[tokio::test]
async fn worker_trusted_types_eval_keyword_allows_eval_when_trusted_types_are_enforced() {
ensure_v8();
let mut handle = spawn_test_worker_with_options(
WorkerSpawnOptions::new(
r#"
let violations = 0;
addEventListener("securitypolicyviolation", () => violations++);
const value = eval("40 + 2");
setTimeout(() => {
postMessage({ value, violations });
close();
});
"#
.to_owned(),
"https://app.test/worker/main.js".to_owned(),
)
.with_content_security_policies(vec![
"script-src 'self' 'trusted-types-eval'; require-trusted-types-for 'script'".to_owned(),
]),
);
let msg = timeout(TIMEOUT, handle.recv())
.await
.expect("timed out")
.expect("channel closed");
assert_eq!(expect_post_json(msg), r#"{"value":42,"violations":0}"#);
}
#[tokio::test]
async fn worker_trusted_script_code_like_brand_drives_function_constructor() {
ensure_v8();