Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(trusted-types): report eval violations in report-only mode
ldm0da07e9723c37
diff --git a/moli-renderer-v8/src/context_bootstrap/trusted_types.rs b/moli-renderer-v8/src/context_bootstrap/trusted_types.rsindex 85ff1b3c3..615a58825 100644--- a/moli-renderer-v8/src/context_bootstrap/trusted_types.rs+++ b/moli-renderer-v8/src/context_bootstrap/trusted_types.rs@@ -329,8 +329,9 @@ pub(crate) fn trusted_types_code_generation_check_callback<'s>(modified_source: None,};}+ let requirements = trusted_types_for_script_requirements(scope);let (codegen_allowed, modified_source) =- match trusted_types_code_generation_check(scope, source, is_code_like) {+ match trusted_types_code_generation_check(scope, source, is_code_like, requirements) {TrustedTypesCodeGenerationCheck::AllowOriginal => (true, None),TrustedTypesCodeGenerationCheck::AllowModified(source) => {let source = v8_string(scope, &source);@@ -348,6 +349,7 @@ pub(crate) fn trusted_types_code_generation_check<'s>(scope: &mut v8::PinScope<'s, '_>,source: v8::Local<'s, v8::Value>,is_code_like: bool,+ requirements: TrustedTypesForScriptRequirements,) -> TrustedTypesCodeGenerationCheck {if let Some(value) = trusted_type_string(scope, source, TrustedTypeKind::Script) {return TrustedTypesCodeGenerationCheck::AllowModified(value);@@ -363,7 +365,10 @@ pub(crate) fn trusted_types_code_generation_check<'s>(let Some(original) = js_value_to_string(scope, source) else {return TrustedTypesCodeGenerationCheck::Block;};- trusted_script_string_for_code_generation(scope, &original)+ if !requirements.requires_conversion() {+ return TrustedTypesCodeGenerationCheck::AllowModified(original);+ }+ trusted_script_string_for_code_generation(scope, &original, requirements).map(TrustedTypesCodeGenerationCheck::AllowModified).unwrap_or(TrustedTypesCodeGenerationCheck::Block)}@@ -371,44 +376,20 @@ pub(crate) fn trusted_types_code_generation_check<'s>(fn trusted_script_string_for_code_generation(scope: &mut v8::PinScope<'_, '_>,original: &str,+ requirements: TrustedTypesForScriptRequirements,) -> Option<String> {let Some(function_source) = function_constructor_code_generation_source(original) else {- return trusted_script_string_for_eval_source(scope, original);+ return trusted_script_string_for_eval_source(scope, original, requirements);};- if let Some(default_value) = apply_default_trusted_type_policy(+ trusted_script_string_for_code_generation_sink(scope,+ original,function_source.default_policy_input,- TrustedTypeKind::Script,- "Function",- TrustedTypeErrorKind::Eval,- ) {- if default_value == function_source.default_policy_input {- return Some(original.to_owned());- }- dispatch_trusted_types_sink_violation_event(- scope,- "Function",- function_source.violation_sample,- );- throw_eval_error(- scope,- "Trusted Types default policy must not transform strings passed to Function.",- );- return None;- }- dispatch_trusted_types_sink_violation_event(- scope,"Function",function_source.violation_sample,- );- throw_trusted_type_error(- scope,- TrustedTypeErrorKind::Eval,- "Function",- TrustedTypeKind::Script,- "Function",- );- None+ requirements,+ "Trusted Types default policy must not transform strings passed to Function.",+ )}struct FunctionConstructorCodeGenerationSource<'a> {@@ -439,33 +420,69 @@ fn function_constructor_code_generation_source(fn trusted_script_string_for_eval_source(scope: &mut v8::PinScope<'_, '_>,original: &str,+ requirements: TrustedTypesForScriptRequirements,) -> Option<String> {- if let Some(default_value) = apply_default_trusted_type_policy(+ trusted_script_string_for_code_generation_sink(scope,original,- TrustedTypeKind::Script,+ original,"eval",- TrustedTypeErrorKind::Eval,- ) {- if default_value == original {- return Some(default_value);- }- dispatch_trusted_types_sink_violation_event(scope, "eval", original);- throw_eval_error(- scope,- "Trusted Types default policy must not transform strings passed to eval.",- );- return None;- }- dispatch_trusted_types_sink_violation_event(scope, "eval", original);- throw_trusted_type_error(+ original,+ requirements,+ "Trusted Types default policy must not transform strings passed to eval.",+ )+}++fn trusted_script_string_for_code_generation_sink(+ scope: &mut v8::PinScope<'_, '_>,+ original: &str,+ default_policy_input: &str,+ sink: &'static str,+ violation_sample: &str,+ requirements: TrustedTypesForScriptRequirements,+ transformed_value_error: &'static str,+) -> Option<String> {+ let outcome = apply_default_trusted_type_policy_outcome(scope,- TrustedTypeErrorKind::Eval,- "eval",+ default_policy_input,TrustedTypeKind::Script,- "eval",+ sink,);- None+ match outcome {+ DefaultTrustedTypePolicyOutcome::Value(value) if value == default_policy_input => {+ Some(original.to_owned())+ }+ DefaultTrustedTypePolicyOutcome::Value(_) => {+ dispatch_trusted_types_sink_violation_event(scope, sink, violation_sample);+ throw_eval_error(scope, transformed_value_error);+ None+ }+ DefaultTrustedTypePolicyOutcome::Exception => None,+ outcome @ (DefaultTrustedTypePolicyOutcome::Unavailable+ | DefaultTrustedTypePolicyOutcome::Rejected) => {+ dispatch_trusted_types_sink_violation_event(scope, sink, violation_sample);+ if requirements.is_enforced() {+ if matches!(outcome, DefaultTrustedTypePolicyOutcome::Rejected) {+ throw_trusted_type_policy_result_error(+ scope,+ TrustedTypeErrorKind::Eval,+ TrustedTypeKind::Script,+ );+ } else {+ throw_trusted_type_error(+ scope,+ TrustedTypeErrorKind::Eval,+ sink,+ TrustedTypeKind::Script,+ sink,+ );+ }+ None+ } else {+ Some(original.to_owned())+ }+ }+ }}#[derive(Clone, Copy)]@@ -1030,6 +1047,18 @@ fn trusted_script_string_for_function_constructor<'s>(None}+fn trusted_types_for_script_requirements(+ scope: &mut v8::PinScope<'_, '_>,+) -> TrustedTypesForScriptRequirements {+ if let Some(required) = crate::worker::worker_requires_trusted_types_for_script(scope) {+ return TrustedTypesForScriptRequirements::enforced_only(required);+ }+ let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {+ return TrustedTypesForScriptRequirements::default();+ };+ unsafe { &*host_ptr }.trusted_types_for_script_requirements(scope)+}+fn trusted_types_eval_is_allowed(scope: &mut v8::PinScope<'_, '_>) -> bool {if let Some(allowed) = crate::worker::worker_allows_trusted_types_eval(scope) {return allowed;diff --git a/moli-renderer-v8/src/script_vm/security_policy.rs b/moli-renderer-v8/src/script_vm/security_policy.rsindex dc41b047e..b47f8ebd5 100644--- a/moli-renderer-v8/src/script_vm/security_policy.rs+++ b/moli-renderer-v8/src/script_vm/security_policy.rs@@ -152,9 +152,9 @@ pub(super) fn string_code_generation_check_callback<'s>(if crate::context_bootstrap::consume_internal_javascript_url_eval(scope) {return code_generation_result(true, None);}- let requires_trusted_types_for_script =- unsafe { &*host_ptr }.requires_trusted_types_for_script(scope);- let action = if requires_trusted_types_for_script {+ let trusted_types_requirements =+ unsafe { &*host_ptr }.trusted_types_for_script_requirements(scope);+ let action = if trusted_types_requirements.requires_conversion() {if unsafe { &*host_ptr }.allows_trusted_types_eval(scope) {// The keyword relaxes Trusted Types conversion, but it does not// override another CSP policy. The per-policy CSP gate still runs.@@ -165,7 +165,12 @@ pub(super) fn string_code_generation_check_callback<'s>(modified_source: None,}} else {- match trusted_types_code_generation_check(scope, source, is_code_like) {+ match trusted_types_code_generation_check(+ scope,+ source,+ is_code_like,+ trusted_types_requirements,+ ) {TrustedTypesCodeGenerationCheck::AllowModified(source) => {StringCodeGenerationPolicyAction::CheckCsp {allow_trusted_types_eval: true,@@ -182,11 +187,21 @@ pub(super) fn string_code_generation_check_callback<'s>(}}} else {- let check = trusted_types_code_generation_check(scope, source, is_code_like);+ let check = trusted_types_code_generation_check(+ scope,+ source,+ is_code_like,+ trusted_types_requirements,+ );code_generation_action_from_trusted_types_check(check)}} else if is_code_like || !source.is_string() {- let check = trusted_types_code_generation_check(scope, source, is_code_like);+ let check = trusted_types_code_generation_check(+ scope,+ source,+ is_code_like,+ trusted_types_requirements,+ );code_generation_action_from_trusted_types_check(check)} else {match non_trusted_types_code_generation_source(source, is_code_like) {@@ -199,7 +214,12 @@ pub(super) fn string_code_generation_check_callback<'s>(}NonTrustedTypesCodeGenerationSource::CodeLikeObject| NonTrustedTypesCodeGenerationSource::PassThroughObject => {- match trusted_types_code_generation_check(scope, source, is_code_like) {+ match trusted_types_code_generation_check(+ scope,+ source,+ is_code_like,+ trusted_types_requirements,+ ) {TrustedTypesCodeGenerationCheck::AllowModified(source) => {StringCodeGenerationPolicyAction::CheckCsp {allow_trusted_types_eval: false,diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/trusted_types.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/trusted_types.rsindex 348d37b16..5015d3705 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/trusted_types.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/trusted_types.rs@@ -901,6 +901,61 @@ fn empty_default_policy_report_only_allows_and_reports_each_element_sink() {);}+#[test]+fn report_only_trusted_types_eval_runs_reports_and_applies_the_default_policy() {+ let mut vm = new_storage_test_vm("https://trusted-types-eval-report-only.test/");+ vm.set_response_content_security_policies(&["script-src 'unsafe-eval'".to_owned()]);+ vm.set_response_content_security_report_only_policies(&[+ "require-trusted-types-for 'script'".to_owned()+ ]);++ let result = vm+ .eval(+ r#"+(() => {+ const violations = [];+ const defaultPolicyCalls = [];+ document.addEventListener("securitypolicyviolation", event => {+ if (event.blockedURI === "trusted-types-sink") {+ violations.push({ sample: event.sample, disposition: event.disposition });+ }+ });+ globalThis.__reportOnlyEvalViolations = violations;++ eval("globalThis.__reportOnlyEval = 1");+ const explicit = trustedTypes.createPolicy("explicit-report-only-eval", {+ createScript: value => value+ });+ eval(explicit.createScript("globalThis.__reportOnlyEval = 2"));+ trustedTypes.createPolicy("default", {+ createScript: (...args) => {+ defaultPolicyCalls.push(args);+ return args[0];+ }+ });+ eval("globalThis.__reportOnlyEval = 3");++ return JSON.stringify({ value: globalThis.__reportOnlyEval, defaultPolicyCalls, violations });+})()+"#,+ )+ .expect("report-only Trusted Types eval probe should evaluate");++ assert_eq!(+ result,+ r#"{"value":3,"defaultPolicyCalls":[["globalThis.__reportOnlyEval = 3","TrustedScript","eval"]],"violations":[]}"#+ );+ assert_eq!(+ drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm),+ 1+ );+ assert_eq!(+ vm.eval("JSON.stringify(globalThis.__reportOnlyEvalViolations)")+ .expect("queued report-only eval violation should be observable"),+ r#"[{"sample":"eval|globalThis.__reportOnlyEval = 1","disposition":"report"}]"#+ );+}+#[test]fn report_only_default_policy_transforms_or_preserves_by_callback_outcome() {let mut vm = new_storage_test_vm("https://default-policy-report-only.test/");diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rsindex 8b4a01b0b..a41c03b33 100644--- a/moli-renderer-v8/src/worker/global_scope/mod.rs+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs@@ -4442,6 +4442,16 @@ pub(crate) fn worker_allows_trusted_type_policy_name()}+pub(crate) fn worker_requires_trusted_types_for_script(+ scope: &mut v8::PinScope<'_, '_>,+) -> Option<bool> {+ Some(+ crate::content_security_policy::content_security_policy_requires_trusted_types_for_script(+ &get_worker_state(scope)?.borrow().content_security_policies,+ ),+ )+}+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(diff --git a/moli-renderer-v8/src/worker/mod.rs b/moli-renderer-v8/src/worker/mod.rsindex 5a4b61165..ead54006c 100644--- a/moli-renderer-v8/src/worker/mod.rs+++ b/moli-renderer-v8/src/worker/mod.rs@@ -41,9 +41,9 @@ pub(crate) use global_scope::{worker_broadcast_channel_wrapper, worker_current_script_url, worker_global_is_closed,worker_message_port_registry, worker_message_port_wake_sender, worker_message_port_wrapper,worker_notification_permission_state, worker_opfs_directory_iterator_registry,- worker_opfs_handle_registry, worker_service_worker_control_state, worker_storage_key,- worker_storage_partition_identity, worker_termination_requested,- worker_uses_shared_worker_agent_cluster,+ worker_opfs_handle_registry, worker_requires_trusted_types_for_script,+ worker_service_worker_control_state, worker_storage_key, worker_storage_partition_identity,+ worker_termination_requested, worker_uses_shared_worker_agent_cluster,};pub(crate) use handle::WorkerMessage;pub(crate) use handle::{