Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(csp): enforce worker string timer policy after conversion

ldm03d4da651f765
diff --git a/moli-renderer-v8/src/content_security_policy.rs b/moli-renderer-v8/src/content_security_policy.rs
index 0264f4f5a..c2c32f2ab 100644
--- a/moli-renderer-v8/src/content_security_policy.rs
+++ b/moli-renderer-v8/src/content_security_policy.rs
@@ -222,8 +222,8 @@ impl<'a> ContentSecurityPolicyViolationEventFields<'a> {
disposition: violation.disposition,
source_file: violation.source_file.as_str(),
sample: violation.sample.as_str(),
- line_number: 0,
- column_number: 0,
+ line_number: violation.line_number,
+ column_number: violation.column_number,
status_code: 0,
}
}
@@ -2065,6 +2065,25 @@ fn inline_source_matches_hash(source: &str, hash_source: CspHashSourceValue<'_>)
}))
}
+pub(crate) fn current_script_violation_location(
+ scope: &mut v8::PinScope<'_, '_>,
+) -> Option<(String, i32, i32)> {
+ let stack = v8::StackTrace::current_stack_trace(scope, 1)?;
+ let frame = stack.get_frame(scope, 0)?;
+ let source_file = frame
+ .get_script_name_or_source_url(scope)
+ .map(|source| source.to_rust_string_lossy(scope))
+ .map(|source| {
+ crate::content_security_policy::content_security_policy_source_file_for_report(&source)
+ })
+ .unwrap_or_default();
+ let line_number = i32::try_from(frame.get_line_number())
+ .unwrap_or_default()
+ .max(0);
+ let column_number = i32::try_from(frame.get_column()).unwrap_or_default().max(0);
+ Some((source_file, line_number, column_number))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
index a059bb031..58d32d999 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
@@ -839,7 +839,7 @@ impl JsContextHost {
}
if include_call_location
&& let Some((source_file, line_number, column_number)) =
- current_script_violation_location(scope)
+ crate::content_security_policy::current_script_violation_location(scope)
{
for violation in [&mut report_only_violation, &mut enforced_violation]
.into_iter()
@@ -1273,22 +1273,3 @@ impl JsContextHost {
Ok(())
}
}
-
-fn current_script_violation_location(
- scope: &mut v8::PinScope<'_, '_>,
-) -> Option<(String, i32, i32)> {
- let stack = v8::StackTrace::current_stack_trace(scope, 1)?;
- let frame = stack.get_frame(scope, 0)?;
- let source_file = frame
- .get_script_name_or_source_url(scope)
- .map(|source| source.to_rust_string_lossy(scope))
- .map(|source| {
- crate::content_security_policy::content_security_policy_source_file_for_report(&source)
- })
- .unwrap_or_default();
- let line_number = i32::try_from(frame.get_line_number())
- .unwrap_or_default()
- .max(0);
- let column_number = i32::try_from(frame.get_column()).unwrap_or_default().max(0);
- Some((source_file, line_number, column_number))
-}
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 dc9a6d068..8efcc0508 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
@@ -960,3 +960,29 @@ pub(super) fn worker_content_security_policy_error_message(
violation.blocked_uri
)
}
+
+pub(super) fn worker_compilation_content_security_policy_violations(
+ state: &WorkerGlobalState,
+ protected_url: &Url,
+ kind: crate::content_security_policy::ContentSecurityPolicyNonUrlKind,
+ source: Option<&str>,
+ disposition: ContentSecurityPolicyDisposition,
+) -> Vec<ContentSecurityPolicyUrlViolation> {
+ let policies = match disposition {
+ ContentSecurityPolicyDisposition::Enforce => &state.content_security_policies,
+ ContentSecurityPolicyDisposition::Report => &state.content_security_report_only_policies,
+ };
+ policies
+ .iter()
+ .filter_map(|policy| {
+ crate::content_security_policy::content_security_policy_non_url_violation_with_source(
+ policy,
+ protected_url,
+ kind,
+ source,
+ disposition,
+ &state.content_security_reporting_endpoints,
+ )
+ })
+ .collect()
+}
diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rs
index 4a3589990..e82c45afc 100644
--- a/moli-renderer-v8/src/worker/global_scope/mod.rs
+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs
@@ -5065,3 +5065,81 @@ pub(super) struct TimerInfo {
pub(super) is_interval: bool,
pub(super) extra_args: Vec<v8::Global<v8::Value>>,
}
+
+pub(crate) fn worker_allows_eval_code_generation_by_csp(
+ scope: &mut v8::PinScope<'_, '_>,
+ allow_trusted_types_eval: bool,
+ source: Option<&str>,
+) -> Option<bool> {
+ use crate::content_security_policy::ContentSecurityPolicyNonUrlKind;
+ let kind = if allow_trusted_types_eval {
+ ContentSecurityPolicyNonUrlKind::TrustedTypesEval
+ } else {
+ ContentSecurityPolicyNonUrlKind::Eval
+ };
+ worker_allows_compilation_by_csp(scope, kind, source)
+}
+
+fn worker_allows_compilation_by_csp(
+ scope: &mut v8::PinScope<'_, '_>,
+ kind: crate::content_security_policy::ContentSecurityPolicyNonUrlKind,
+ source: Option<&str>,
+) -> Option<bool> {
+ let state = get_worker_state(scope)?;
+ let (wake_tx, mut report_only_violations, mut enforce_violations) = {
+ let state = state.borrow();
+ let Some(protected_url) = state.current_script_url.as_ref() else {
+ return Some(true);
+ };
+ (
+ state.worker_wake_tx.clone(),
+ content_security_policy::worker_compilation_content_security_policy_violations(
+ &state,
+ protected_url,
+ kind,
+ source,
+ crate::content_security_policy::ContentSecurityPolicyDisposition::Report,
+ ),
+ content_security_policy::worker_compilation_content_security_policy_violations(
+ &state,
+ protected_url,
+ kind,
+ source,
+ crate::content_security_policy::ContentSecurityPolicyDisposition::Enforce,
+ ),
+ )
+ };
+ if kind != crate::content_security_policy::ContentSecurityPolicyNonUrlKind::WasmEval
+ && (!report_only_violations.is_empty() || !enforce_violations.is_empty())
+ && let Some((source_file, line_number, column_number)) =
+ crate::content_security_policy::current_script_violation_location(scope)
+ {
+ for violation in [&mut report_only_violations, &mut enforce_violations]
+ .into_iter()
+ .flatten()
+ {
+ violation.source_file.clone_from(&source_file);
+ violation.line_number = line_number;
+ violation.column_number = column_number;
+ }
+ }
+ let allowed = enforce_violations.is_empty();
+ for violation in report_only_violations.into_iter().chain(enforce_violations) {
+ let _ = wake_tx.send(
+ super::handle::WorkerMessage::DispatchContentSecurityPolicyViolation(Box::new(
+ violation,
+ )),
+ );
+ }
+ Some(allowed)
+}
+
+pub(super) fn dispatch_worker_csp_violation_event_for_state<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ state: &Rc<RefCell<WorkerGlobalState>>,
+ violation: &crate::content_security_policy::ContentSecurityPolicyUrlViolation,
+) {
+ content_security_policy::dispatch_worker_content_security_policy_violation_event_for_state(
+ scope, state, violation,
+ );
+}
diff --git a/moli-renderer-v8/src/worker/global_scope/timers.rs b/moli-renderer-v8/src/worker/global_scope/timers.rs
index adfd0989c..45ae5ed66 100644
--- a/moli-renderer-v8/src/worker/global_scope/timers.rs
+++ b/moli-renderer-v8/src/worker/global_scope/timers.rs
@@ -27,15 +27,18 @@ pub(super) fn worker_set_timeout_callback<'s>(
};
if args.length() > 0 {
- let callback = match worker_timer_callback_from_arg(scope, args.get(0), "setTimeout") {
+ let Some((handler, delay_ms)) = prepare_worker_timer_arguments(scope, &args, "setTimeout")
+ else {
+ return;
+ };
+ let callback = match worker_timer_callback_from_arg(scope, handler, "setTimeout") {
Ok(Some(callback)) => callback,
Ok(None) => {
- rv.set(v8::Integer::new(scope, timer_id as i32).into());
+ rv.set_uint32(0);
return;
}
Err(()) => return,
};
- let delay_ms = worker_timer_delay_ms(scope, &args, "DedicatedWorkerGlobalScope.setTimeout");
// Collect extra arguments to pass to the callback
let extra_args: Vec<v8::Global<v8::Value>> = (2..args.length())
@@ -72,16 +75,18 @@ pub(super) fn worker_set_interval_callback<'s>(
};
if args.length() > 0 {
- let callback = match worker_timer_callback_from_arg(scope, args.get(0), "setInterval") {
+ let Some((handler, delay_ms)) = prepare_worker_timer_arguments(scope, &args, "setInterval")
+ else {
+ return;
+ };
+ let callback = match worker_timer_callback_from_arg(scope, handler, "setInterval") {
Ok(Some(callback)) => callback,
Ok(None) => {
- rv.set(v8::Integer::new(scope, timer_id as i32).into());
+ rv.set_uint32(0);
return;
}
Err(()) => return,
};
- let delay_ms =
- worker_timer_delay_ms(scope, &args, "DedicatedWorkerGlobalScope.setInterval");
let extra_args: Vec<v8::Global<v8::Value>> = (2..args.length())
.map(|i| v8::Global::new(scope, args.get(i)))
@@ -102,6 +107,36 @@ pub(super) fn worker_set_interval_callback<'s>(
rv.set(v8::Integer::new(scope, timer_id as i32).into());
}
+fn prepare_worker_timer_arguments<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: &v8::FunctionCallbackArguments<'s>,
+ timer_name: &'static str,
+) -> Option<(v8::Local<'s, v8::Value>, u64)> {
+ let value = args.get(0);
+ // Web IDL conversions precede both Trusted Types default-policy calls and
+ // CSP checks. Preserve callable and TrustedScript union members as objects.
+ let preserve_object = v8::Local::<v8::Object>::try_from(value).is_ok_and(|object| {
+ object.is_callable() || crate::web_api_interfaces::TrustedScript::is_instance(scope, object)
+ });
+ let handler = if value.is_string() || preserve_object {
+ value
+ } else {
+ value.to_string(scope)?.into()
+ };
+ let prefix = match timer_name {
+ "setInterval" => "DedicatedWorkerGlobalScope.setInterval",
+ _ => "DedicatedWorkerGlobalScope.setTimeout",
+ };
+ let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
+ let mut scope = try_catch.init();
+ let delay_ms = worker_timer_delay_ms(&mut scope, args, prefix);
+ if scope.has_caught() {
+ let _ = scope.rethrow();
+ return None;
+ }
+ Some((handler, delay_ms))
+}
+
fn worker_timer_callback_from_arg<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
@@ -145,6 +180,13 @@ fn worker_timer_callback_from_arg<'s>(
) else {
return Err(());
};
+ let allow_trusted_types_eval = require_trusted_types_for_script
+ && worker_allows_trusted_types_eval(scope).unwrap_or(false);
+ if !worker_allows_eval_code_generation_by_csp(scope, allow_trusted_types_eval, Some(&source))
+ .unwrap_or(true)
+ {
+ return Ok(None);
+ }
let wrapper = format!("(function() {{\n{source}\n}})");
let Some(source) = v8::String::new(scope, &wrapper) else {
return Ok(None);
diff --git a/moli-renderer-v8/src/worker/handle.rs b/moli-renderer-v8/src/worker/handle.rs
index a444a2e6d..b2e1d81c2 100644
--- a/moli-renderer-v8/src/worker/handle.rs
+++ b/moli-renderer-v8/src/worker/handle.rs
@@ -137,6 +137,10 @@ pub(crate) enum WorkerMessage {
ServiceWorkerShowNotificationResult(ServiceWorkerShowNotificationResult),
/// Resolve a Service Worker `ServiceWorkerRegistration.getNotifications()` request in the worker.
ServiceWorkerGetNotificationsResult(ServiceWorkerGetNotificationsResult),
+ /// Dispatch a CSP violation after the current worker script turn.
+ DispatchContentSecurityPolicyViolation(
+ Box<crate::content_security_policy::ContentSecurityPolicyUrlViolation>,
+ ),
/// Run the worker's queued unhandled promise rejection notification task.
DispatchPendingPromiseRejections,
/// A worker spawned from this worker has queued a parent-facing event.
diff --git a/moli-renderer-v8/src/worker/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rs
index c5b96d696..f6bba6a9d 100644
--- a/moli-renderer-v8/src/worker/thread/mod.rs
+++ b/moli-renderer-v8/src/worker/thread/mod.rs
@@ -2660,6 +2660,25 @@ async fn worker_main(
perform_worker_microtask_checkpoint_and_report_pending_promise_rejections(scope);
drain_worker_dynamic_module_imports(scope, &state, &module_graph_fetch_tx);
}
+ WorkerLoopWake::Message(Some(
+ WorkerMessage::DispatchContentSecurityPolicyViolation(violation),
+ )) => {
+ if pending_module_bootstrap.is_some() {
+ pending_bootstrap_messages.push_back(
+ WorkerMessage::DispatchContentSecurityPolicyViolation(violation),
+ );
+ continue;
+ }
+ let scope = pin!(v8::HandleScope::new(worker_isolate.worker_isolate_mut()));
+ 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,
+ );
+ perform_worker_microtask_checkpoint_and_report_pending_promise_rejections(scope);
+ drain_worker_dynamic_module_imports(scope, &state, &module_graph_fetch_tx);
+ }
WorkerLoopWake::Message(Some(WorkerMessage::NestedWorkerEvent {
worker_id,
message,
diff --git a/moli-renderer-v8/src/worker/thread/tests/modules.rs b/moli-renderer-v8/src/worker/thread/tests/modules.rs
index ed4ea98b4..6e907ab22 100644
--- a/moli-renderer-v8/src/worker/thread/tests/modules.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/modules.rs
@@ -804,6 +804,133 @@ async fn worker_trusted_types_policy_callbacks_follow_webidl_contract() {
);
}
+#[tokio::test]
+async fn worker_string_timer_csp_blocks_and_reports_without_blocking_functions() {
+ ensure_v8();
+ for (policy, report_only, blocked, reports) in [
+ ("script-src 'self' 'report-sample'", false, true, true),
+ ("default-src 'self' 'report-sample'", false, true, true),
+ ("script-src 'self' 'report-sample'", true, false, true),
+ ("script-src 'unsafe-eval'", false, false, false),
+ ] {
+ let source = r#"
+ globalThis.ran = [];
+ const events = [];
+ const first = setTimeout("globalThis.ran.push('timeout')", 10);
+ globalThis.interval = setInterval("globalThis.ran.push('interval'); clearInterval(globalThis.interval)", 10);
+ addEventListener('securitypolicyviolation', e => events.push({
+ directive: e.effectiveDirective, blocked: e.blockedURI,
+ disposition: e.disposition, policy: e.originalPolicy,
+ source: e.sourceFile, line: e.lineNumber, sample: e.sample,
+ }));
+ const synchronousEvents = events.length;
+ setTimeout((value) => ran.push(value), 10, 'function');
+ setTimeout(() => {
+ postMessage({zeroIds: [first === 0, interval === 0], ran: ran.sort(), synchronousEvents, events});
+ close();
+ }, 80);
+ "#;
+ let options = WorkerSpawnOptions::new(
+ source.to_owned(),
+ "https://app.test/worker/main.js".to_owned(),
+ );
+ let options = if report_only {
+ options.with_content_security_report_only_policies(vec![policy.to_owned()])
+ } else {
+ options.with_content_security_policies(vec![policy.to_owned()])
+ };
+ let mut handle = spawn_test_worker_with_options(options);
+ let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
+ let value: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();
+ assert_eq!(value["zeroIds"], serde_json::json!([blocked, blocked]));
+ assert_eq!(
+ value["ran"],
+ if blocked {
+ serde_json::json!(["function"])
+ } else {
+ serde_json::json!(["function", "interval", "timeout"])
+ }
+ );
+ assert_eq!(value["synchronousEvents"], 0);
+ let events = value["events"].as_array().unwrap();
+ assert_eq!(events.len(), if reports { 2 } else { 0 });
+ for (event, (line, sample)) in events.iter().zip([
+ (4, "globalThis.ran.push('timeout')"),
+ (5, "globalThis.ran.push('interval'); clearIn"),
+ ]) {
+ assert_eq!(
+ event,
+ &serde_json::json!({
+ "directive": "script-src", "blocked": "eval",
+ "disposition": if report_only { "report" } else { "enforce" },
+ "policy": policy, "source": "https://app.test/worker/main.js", "line": line, "sample": sample,
+ })
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn worker_string_timer_csp_converts_arguments_before_policy_and_preserves_exceptions() {
+ ensure_v8();
+ let mut handle = spawn_test_worker_with_options(
+ WorkerSpawnOptions::new(r#"
+ const order = [];
+ const events = [];
+ const marker = {};
+ const errors = [];
+ for (const method of ['setTimeout', 'setInterval']) {
+ try {
+ self[method]({toString() { order.push('handler'); throw marker; }}, {valueOf() { order.push('unexpected'); return 0; }});
+ } catch (e) { errors.push(e === marker); }
+ try {
+ self[method]({toString() { order.push('handler'); return "postMessage('unexpected')"; }}, {valueOf() { order.push('delay'); throw marker; }});
+ } catch (e) { errors.push(e === marker); }
+ }
+ addEventListener('securitypolicyviolation', e => events.push(e.blockedURI));
+ setTimeout(() => { postMessage({order, errors, events}); close(); }, 50);
+ "#.to_owned(), "https://app.test/worker/main.js".to_owned())
+ .with_content_security_policies(vec!["script-src 'none'; require-trusted-types-for 'script'".to_owned()]),
+ );
+ let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
+ let value: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();
+ assert_eq!(
+ value,
+ serde_json::json!({
+ "order": ["handler", "handler", "delay", "handler", "handler", "delay"],
+ "errors": [true, true, true, true], "events": [],
+ })
+ );
+}
+
+#[tokio::test]
+async fn worker_string_timer_csp_preserves_trusted_types_relaxation_and_default_policy_order() {
+ ensure_v8();
+ let mut handle = spawn_test_worker_with_options(
+ WorkerSpawnOptions::new(r#"
+ globalThis.ran = [];
+ const order = [];
+ trustedTypes.createPolicy('default', {createScript(value, type, sink) { order.push(sink); return value; }});
+ const explicit = trustedTypes.createPolicy('explicit', {createScript: value => value});
+ const first = setTimeout({toString() { order.push('handler'); return "ran.push('default')"; }}, {valueOf() { order.push('delay'); return 10; }});
+ const trusted = explicit.createScript("ran.push('trusted')");
+ trusted.toString = () => { throw new Error('must not coerce TrustedScript'); };
+ const second = setTimeout(trusted, 10);
+ setTimeout(() => { postMessage({positiveIds: [first > 0, second > 0], ran, order}); close(); }, 50);
+ "#.to_owned(), "https://app.test/worker/main.js".to_owned())
+ .with_content_security_policies(vec!["script-src 'trusted-types-eval'; require-trusted-types-for 'script'".to_owned()]),
+ );
+ let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
+ let value: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();
+ assert_eq!(
+ value,
+ serde_json::json!({
+ "positiveIds": [true, true], "ran": ["default", "trusted"],
+ "order": ["handler", "delay", "WorkerGlobalScope setTimeout"],
+ })
+ );
+}
+
#[tokio::test]
async fn worker_trusted_types_timers_and_eval_use_script_sink() {
ensure_v8();