diff --git a/moli-core/tests/scripts/dynamic_import_credentials.rs b/moli-core/tests/scripts/dynamic_import_credentials.rs new file mode 100644 index 00000000000..5c018a5c7c5 --- /dev/null +++ b/moli-core/tests/scripts/dynamic_import_credentials.rs @@ -0,0 +1,125 @@ +use super::*; + +pub(super) fn importer_source(name: &str) -> String { + format!( + r#"globalThis.importers[{0}] = (url, timer) => {{ + if (!timer) return import(url); + return new Promise((resolve, reject) => {{ + globalThis.timerImports[url] = {{resolve, reject}}; + const key = JSON.stringify(url); + setTimeout('import(' + key + ').then(timerImports[' + key + '].resolve, timerImports[' + key + '].reject)', 0); + }}); + }}; + globalThis.importerReady[{0}]();"#, + serde_json::to_string(name).unwrap() + ) +} + +async fn check_dynamic_import_credentials(child: bool) -> Result<()> { + let servers = IntegrityServers::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let mut page = browser + .fetch(&format!("{}/cookie-page.html", servers.origin)) + .await?; + let mut cases = Vec::new(); + for kind in ["classic", "module"] { + for external in [false, true] { + for credentials in ["default", "anonymous", "use-credentials"] { + let name = format!("{kind}-{external}-{credentials}"); + cases.push(serde_json::json!({ + "name":name, "kind":kind, "external":external, + "credentials":credentials, "source":importer_source(&name), + })); + } + } + } + let probe = format!( + r#"(async () => {{ + globalThis.importers = {{}}; + globalThis.importerReady = {{}}; + globalThis.timerImports = {{}}; + const cases = {cases}; + for (const test of cases) {{ + const script = document.createElement('script'); + if (test.kind === 'module') script.type = 'module'; + if (test.credentials !== 'default') script.crossOrigin = test.credentials; + if (test.external) script.src = '/import-credentials.js?' + test.name; + else script.textContent = test.source; + await new Promise((resolve, reject) => {{ + const timer = setTimeout(() => reject(new Error('source did not run: ' + test.name)), 3000); + importerReady[test.name] = () => {{ clearTimeout(timer); resolve(); }}; + script.onerror = () => reject(new Error('failed to load ' + test.name)); + document.head.append(script); + }}); + // Later mutation/removal must not change the compiled script's fetch options. + script.crossOrigin = test.credentials === 'use-credentials' ? 'anonymous' : 'use-credentials'; + script.remove(); + for (const invocation of ['direct', 'timer']) + for (const [label, origin] of [['same', location.origin], ['cross', {cross}]]) + await importers[test.name](origin + '/echo-origin.js?credentials-' + test.name + '-' + invocation + '-' + label, invocation === 'timer'); + }} + return true; + }})()"#, + cases = serde_json::to_string(&cases)?, + cross = serde_json::to_string(&servers.cross_origin)?, + ); + let expression = if child { + format!( + r#"(async () => {{ + const frame = document.createElement('iframe'); + frame.src = '/page.html?child'; + await new Promise(resolve => {{ frame.onload = resolve; document.body.append(frame); }}); + return frame.contentWindow.eval({}); + }})()"#, + serde_json::to_string(&probe)? + ) + } else { + probe + }; + let result = tokio::time::timeout( + Duration::from_secs(15), + page.evaluate_runtime_expression_with_await_async(&expression, true), + ) + .await??; + assert_eq!(result["value"], true, "child={child}: {result}"); + let requests = servers.requests.lock(); + let mut mismatches = Vec::new(); + for test in cases { + for invocation in ["direct", "timer"] { + for origin in ["same", "cross"] { + let path = format!( + "/echo-origin.js?credentials-{}-{invocation}-{origin}", + test["name"].as_str().unwrap() + ); + let matching: Vec<_> = requests + .iter() + .filter(|request| request.path == path) + .collect(); + assert_eq!(matching.len(), 1, "child={child}, {path}: {requests:?}"); + let request = matching[0]; + assert_eq!(request.sec_fetch_mode.as_deref(), Some("cors"), "{path}"); + assert_eq!(request.sec_fetch_dest.as_deref(), Some("script"), "{path}"); + let expected = (origin == "same" || test["credentials"] == "use-credentials") + .then_some("sriSession=present"); + if request.cookie.as_deref() != expected { + mismatches.push(format!( + "{path}: {:?}, expected {expected:?}", + request.cookie + )); + } + } + } + } + assert!(mismatches.is_empty(), "child={child}: {mismatches:#?}"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn main_dynamic_imports_preserve_script_credentials() -> Result<()> { + check_dynamic_import_credentials(false).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn child_dynamic_imports_preserve_script_credentials() -> Result<()> { + check_dynamic_import_credentials(true).await +} diff --git a/moli-core/tests/scripts/integrity.rs b/moli-core/tests/scripts/integrity.rs index 72dcc568792..8198a5e96bd 100644 --- a/moli-core/tests/scripts/integrity.rs +++ b/moli-core/tests/scripts/integrity.rs @@ -31,6 +31,9 @@ mod runtime_modulepreload; #[path = "child_module_records.rs"] mod child_module_records; +#[path = "dynamic_import_credentials.rs"] +mod dynamic_import_credentials; + struct IntegrityServers { origin: String, cross_origin: String, @@ -194,6 +197,11 @@ fn fixture_response( | "/child-sri-rejected.css" | "/child-sri-accepted.css" | "/child-sri-forbidden.css" => child_stylesheet_integrity::fixture_response(path, query), + "/import-credentials.js" => ( + "200 OK", + format!("{javascript}Cache-Control: no-store\r\n"), + dynamic_import_credentials::importer_source(query), + ), "/module-records.html" | "/module-record.js" | "/module-record-tla.js" diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs index f6b993a9885..b7ab487fa59 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs @@ -2210,6 +2210,7 @@ fn start_connected_child_document_script( owner_document_handle, node, source, + preparation.into_fetch_metadata(), ) { // Script exceptions are reported in the child Window. They do @@ -2281,7 +2282,7 @@ fn execute_committed_inline_classic_script( host_ptr: *mut PageScriptHost, committed: crate::host::CommittedInlineClassicScript, ) { - let (node, host_script_handle, source) = committed.into_parts(); + let (node, host_script_handle, source, fetch_metadata) = committed.into_parts(); // An inserted script executes in its Document's main world, including // when a child or isolated world performed the insertion. let default_context = unsafe { &*host_ptr } @@ -2293,10 +2294,8 @@ fn execute_committed_inline_classic_script( .dom_host .document_base_url_for_handle(runtime.dom_host.document_handle()) .unwrap_or_else(|| script_url.clone()); - let nonce = - crate::host::script_element_nonce_for_csp(&runtime.dom_host, node).map(str::to_owned); let request = crate::content_security_policy::ContentSecurityPolicyScriptElementRequest { - nonce: nonce.as_deref(), + nonce: fetch_metadata.nonce.as_deref(), integrity: None, parser_inserted: false, }; @@ -2315,7 +2314,7 @@ fn execute_committed_inline_classic_script( Some(&script_url), Some(&base_url), 0, - nonce.as_deref(), + Some(&fetch_metadata), true, ); unsafe { &mut *host_ptr }.pop_current_inline_script(node); diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs index 63fac146824..0c772266fc0 100644 --- a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs +++ b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs @@ -163,7 +163,7 @@ impl DocumentRuntime { Some(&script.url), Some(&script.base_url), 0, - script.fetch_metadata.nonce.as_deref(), + Some(&script.fetch_metadata), true, ) }; diff --git a/moli-renderer-v8/src/document_script_scheduler/frame_classic_owner.rs b/moli-renderer-v8/src/document_script_scheduler/frame_classic_owner.rs index 8c90e08f359..397efa8decc 100644 --- a/moli-renderer-v8/src/document_script_scheduler/frame_classic_owner.rs +++ b/moli-renderer-v8/src/document_script_scheduler/frame_classic_owner.rs @@ -622,8 +622,7 @@ mod tests { ), script_url: script_url.clone(), base_url: script_url.clone(), - script_nonce: None, - script_integrity: None, + script_fetch_metadata: None, credentials_mode: RequestCredentialsMode::SameOrigin, referrer_policy: None, }; diff --git a/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs b/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs index d4cb126aa41..b5031fb877e 100644 --- a/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs +++ b/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs @@ -225,6 +225,7 @@ mod tests { source_result: Ok("globalThis.__dynamic = true;".to_owned()), script_url: script_url.clone(), script_base_url: script_url.clone(), + script_fetch_metadata: Default::default(), }; let job = FrameScriptJob { frame_id: FrameId("dynamic-frame".to_owned()), @@ -235,8 +236,7 @@ mod tests { source: FrameScriptSource::SourceText("globalThis.__dynamic = true;".to_owned()), script_url: script_url.clone(), base_url: script_url, - script_nonce: None, - script_integrity: None, + script_fetch_metadata: None, credentials_mode: RequestCredentialsMode::SameOrigin, referrer_policy: None, }; diff --git a/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs b/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs index 3b0bef5ee7c..8bf9e55424b 100644 --- a/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs +++ b/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs @@ -21,6 +21,7 @@ pub(crate) struct PendingChildExternalClassicDocumentScript { pub(crate) source_result: Result, pub(crate) script_url: Url, pub(crate) script_base_url: Url, + pub(crate) script_fetch_metadata: crate::planning::ScriptFetchMetadata, } impl DocumentScriptReadyActionRoute diff --git a/moli-renderer-v8/src/frame_owner_model/records.rs b/moli-renderer-v8/src/frame_owner_model/records.rs index e6ad748123e..51534910519 100644 --- a/moli-renderer-v8/src/frame_owner_model/records.rs +++ b/moli-renderer-v8/src/frame_owner_model/records.rs @@ -1587,8 +1587,7 @@ pub(crate) struct FrameScriptJob { pub(crate) source: FrameScriptSource, pub(crate) script_url: Url, pub(crate) base_url: Url, - pub(crate) script_nonce: Option, - pub(crate) script_integrity: Option, + pub(crate) script_fetch_metadata: Option, #[cfg(test)] pub(crate) credentials_mode: RequestCredentialsMode, pub(crate) referrer_policy: Option, diff --git a/moli-renderer-v8/src/frame_owner_model/store.rs b/moli-renderer-v8/src/frame_owner_model/store.rs index 9042ab63bc0..159afae4679 100644 --- a/moli-renderer-v8/src/frame_owner_model/store.rs +++ b/moli-renderer-v8/src/frame_owner_model/store.rs @@ -4013,7 +4013,7 @@ impl FrameOwnerStore { current_script: Option, script_url: Url, script_base_url: Url, - script_nonce: Option, + script_fetch_metadata: Option, source: String, ) -> Option { if !matches!( @@ -4030,7 +4030,7 @@ impl FrameOwnerStore { current_script, Some(script_url), Some(script_base_url), - script_nonce, + script_fetch_metadata, FrameScriptSource::SourceText(source), ) } @@ -4119,7 +4119,7 @@ impl FrameOwnerStore { current_script: Option, script_url: Url, script_base_url: Url, - script_nonce: Option, + script_fetch_metadata: Option, source: String, ) -> Option { let owner = self.current_child_owner_snapshot(child_handle)?; @@ -4134,7 +4134,7 @@ impl FrameOwnerStore { current_script, script_url, script_base_url, - script_nonce, + script_fetch_metadata, source, ) } @@ -4168,6 +4168,7 @@ impl FrameOwnerStore { current_script: Option, script_url: Url, script_base_url: Url, + script_fetch_metadata: crate::planning::ScriptFetchMetadata, source: String, ) -> Option { let owner = self.current_child_owner_snapshot(child_handle)?; @@ -4182,7 +4183,7 @@ impl FrameOwnerStore { current_script, script_url, script_base_url, - None, + Some(script_fetch_metadata), source, ) } @@ -4253,7 +4254,7 @@ impl FrameOwnerStore { current_script: Option, script_url: Option, script_base_url: Option, - script_nonce: Option, + script_fetch_metadata: Option, source: FrameScriptSource, ) -> Option { let owner = self.current_frame_owner_snapshot(frame_id)?; @@ -4266,8 +4267,7 @@ impl FrameOwnerStore { source, script_url: script_url.unwrap_or_else(|| owner.document_url.clone()), base_url: script_base_url.unwrap_or(owner.document_base_url), - script_nonce, - script_integrity: None, + script_fetch_metadata, #[cfg(test)] credentials_mode: owner.settings.credentials_mode, referrer_policy: owner.settings.referrer_policy, @@ -4283,7 +4283,7 @@ impl FrameOwnerStore { current_script: Option, script_url: Url, script_base_url: Url, - script_nonce: Option, + script_fetch_metadata: Option, source: String, ) -> Option { if !matches!( @@ -4307,8 +4307,7 @@ impl FrameOwnerStore { source: FrameScriptSource::SourceText(source), script_url, base_url: script_base_url, - script_nonce, - script_integrity: None, + script_fetch_metadata, #[cfg(test)] credentials_mode: owner.settings.credentials_mode, referrer_policy: owner.settings.referrer_policy, diff --git a/moli-renderer-v8/src/frame_owner_model/store_tests.rs b/moli-renderer-v8/src/frame_owner_model/store_tests.rs index 72162ab2e21..06ee6ae7f40 100644 --- a/moli-renderer-v8/src/frame_owner_model/store_tests.rs +++ b/moli-renderer-v8/src/frame_owner_model/store_tests.rs @@ -1591,6 +1591,7 @@ fn child_document_commit_replaces_current_owner_records() { Some(handle(16)), url("https://cdn.child.test/stale.js"), url("https://cdn.child.test/stale.js"), + Default::default(), "globalThis.__staleExternalClassic = true;".to_owned(), ) .is_none(), diff --git a/moli-renderer-v8/src/host/scripts/runtime.rs b/moli-renderer-v8/src/host/scripts/runtime.rs index 29971c6d190..7e9748a4628 100644 --- a/moli-renderer-v8/src/host/scripts/runtime.rs +++ b/moli-renderer-v8/src/host/scripts/runtime.rs @@ -10,6 +10,7 @@ use crate::types::ScriptSourceKind; use crate::{ dom::native::{DomHost, NativeNodeId}, frame_owner_model::MainDocumentScriptLoadDelayKind, + planning::ScriptFetchMetadata, { host::{ EventTargetHandle, HostDocumentState, HostEventTargetRegistry, dispatch_host_event, @@ -72,6 +73,7 @@ pub(crate) enum PreparedRuntimeScriptStartCommit { node: NativeNodeId, host_script_handle: String, source: String, + fetch_metadata: ScriptFetchMetadata, }, InlineImportMap { node: NativeNodeId, @@ -89,19 +91,31 @@ pub(crate) struct CommittedInlineClassicScript { node: NativeNodeId, host_script_handle: String, source: String, + fetch_metadata: ScriptFetchMetadata, } impl CommittedInlineClassicScript { - pub(crate) fn new(node: NativeNodeId, host_script_handle: String, source: String) -> Self { + pub(crate) fn new( + node: NativeNodeId, + host_script_handle: String, + source: String, + fetch_metadata: ScriptFetchMetadata, + ) -> Self { Self { node, host_script_handle, source, + fetch_metadata, } } - pub(crate) fn into_parts(self) -> (NativeNodeId, String, String) { - (self.node, self.host_script_handle, self.source) + pub(crate) fn into_parts(self) -> (NativeNodeId, String, String, ScriptFetchMetadata) { + ( + self.node, + self.host_script_handle, + self.source, + self.fetch_metadata, + ) } } @@ -418,6 +432,7 @@ pub(crate) fn prepare_runtime_script_start_commit( node, host_script_handle, source, + fetch_metadata: preparation.fetch_metadata, }) } RuntimeScriptStartDecision::RegisterImportMap { source } => { diff --git a/moli-renderer-v8/src/host/timers.rs b/moli-renderer-v8/src/host/timers.rs index a10f69de3fc..5665a2308c7 100644 --- a/moli-renderer-v8/src/host/timers.rs +++ b/moli-renderer-v8/src/host/timers.rs @@ -16,8 +16,8 @@ use crate::{ page_task_queue::RendererPageTimerSelection, script_provenance::CompiledStringProvenance, util::{ - context_host_ptr_from_global_bridge, create_script_origin_with_base_url_and_nonce, - get_private_value, script_nonce_from_host_defined_options, + context_host_ptr_from_global_bridge, create_script_origin_with_base_url_and_fetch_metadata, + get_private_value, script_fetch_metadata_from_host_defined_options, }, }; use moli_time::{TimerId, TimerScheduleRange, TimerScheduleSnapshot, TimerScheduler}; @@ -32,7 +32,20 @@ struct ScheduledTimerSource { provenance: CompiledStringProvenance, resource_initiator: crate::resource_initiator::CallbackInitiator, // A snapshot of the initiating script, not the eventual timer caller/realm. - script_nonce: Option, + script_fetch_metadata: crate::module_runtime::ModuleFetchMetadata, +} + +fn timer_source_fetch_metadata( + scope: &mut v8::PinScope<'_, '_>, +) -> crate::module_runtime::ModuleFetchMetadata { + let mut metadata = scope + .get_current_host_defined_options() + .and_then(|options| script_fetch_metadata_from_host_defined_options(scope, options)) + .unwrap_or_default(); + // HTML timer initialization inherits the initiating script's credentials + // and nonce, but the compiled timer source is never parser-inserted. + metadata.parser_inserted = false; + metadata } struct ScheduledTimerFunction { @@ -50,7 +63,7 @@ enum ScheduledTimerCallback { InternalFunction(ScheduledTimerFunction), Networking(ScheduledTimerFunction), WindowWebIdl(ScheduledWindowWebIdlCallback), - Source(ScheduledTimerSource), + Source(Box), AnimationFrameWake { context: v8::Global, owner: WindowExecutionContextOwner, @@ -523,9 +536,7 @@ impl HostTimeoutScheduler { owner: HostTimerOwner, extra_args: Vec>, ) -> u32 { - let script_nonce = scope - .get_current_host_defined_options() - .and_then(|options| script_nonce_from_host_defined_options(scope, options)); + let script_fetch_metadata = timer_source_fetch_metadata(scope); let Some(owner) = scheduled_timer_owner_for_target(scope, owner, Some(receiver), context) else { return 0; @@ -546,17 +557,17 @@ impl HostTimeoutScheduler { self.scheduler .schedule_after( ScheduledTimerTask { - callback: ScheduledTimerCallback::Source(ScheduledTimerSource { + callback: ScheduledTimerCallback::Source(Box::new(ScheduledTimerSource { context: v8::Global::new(scope, context), realm_token, use_target_context, source, provenance, - script_nonce, + script_fetch_metadata, resource_initiator: crate::resource_initiator::CallbackInitiator::capture( scope, ), - }), + })), owner, is_interval: false, extra_args, @@ -578,9 +589,7 @@ impl HostTimeoutScheduler { owner: HostTimerOwner, extra_args: Vec>, ) -> u32 { - let script_nonce = scope - .get_current_host_defined_options() - .and_then(|options| script_nonce_from_host_defined_options(scope, options)); + let script_fetch_metadata = timer_source_fetch_metadata(scope); let Some(owner) = scheduled_timer_owner_for_target(scope, owner, Some(receiver), context) else { return 0; @@ -601,17 +610,17 @@ impl HostTimeoutScheduler { self.scheduler .schedule_after( ScheduledTimerTask { - callback: ScheduledTimerCallback::Source(ScheduledTimerSource { + callback: ScheduledTimerCallback::Source(Box::new(ScheduledTimerSource { context: v8::Global::new(scope, context), realm_token, use_target_context, source, provenance, - script_nonce, + script_fetch_metadata, resource_initiator: crate::resource_initiator::CallbackInitiator::capture( scope, ), - }), + })), owner, is_interval: true, extra_args, @@ -1408,12 +1417,12 @@ fn run_window_timer_source( exception: None, })); }; - let origin = create_script_origin_with_base_url_and_nonce( + let origin = create_script_origin_with_base_url_and_fetch_metadata( &mut scope, source.provenance.source_url().as_str(), 0, Some(source.provenance.module_base_url()), - source.script_nonce.as_deref(), + &source.script_fetch_metadata, ); let Some(script) = v8::Script::compile(&scope, source_value, Some(&origin)) else { let exception = scope.exception(); diff --git a/moli-renderer-v8/src/host_bindings.rs b/moli-renderer-v8/src/host_bindings.rs index 07adafb4954..ad723c80123 100644 --- a/moli-renderer-v8/src/host_bindings.rs +++ b/moli-renderer-v8/src/host_bindings.rs @@ -457,7 +457,7 @@ fn host_prepare_script_start_callback( }; match host.plan_and_commit_current_main_runtime_script_start(scope, node, &host_script_handle) { Ok(Some(committed)) => { - let (_, _, source) = committed.into_parts(); + let (_, _, source, _) = committed.into_parts(); if let Some(source) = v8_string(scope, &source) { rv.set(source.into()); } else { diff --git a/moli-renderer-v8/src/module_runtime/dynamic_resolver.rs b/moli-renderer-v8/src/module_runtime/dynamic_resolver.rs index b07522f5c74..15bda030d57 100644 --- a/moli-renderer-v8/src/module_runtime/dynamic_resolver.rs +++ b/moli-renderer-v8/src/module_runtime/dynamic_resolver.rs @@ -12,7 +12,6 @@ use crate::{ native_bridge::{ OwnerDispatchScope, WindowExecutionContextIdentity, WindowExecutionContextOwner, }, - planning::ScriptFetchMetadata, }; use super::{ @@ -33,7 +32,7 @@ pub(crate) struct PendingDynamicModuleImport { resolved_url: Option, attributes: ModuleAttributesKey, phase: ModuleImportPhase, - fetch_metadata: ScriptFetchMetadata, + fetch_metadata: super::ModuleFetchMetadata, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -195,11 +194,14 @@ impl PendingDynamicModuleImport { resolved_url: None, attributes, phase, - fetch_metadata: ScriptFetchMetadata::default(), + fetch_metadata: super::ModuleFetchMetadata::default(), } } - pub(crate) fn with_referrer_fetch_metadata(mut self, metadata: ScriptFetchMetadata) -> Self { + pub(crate) fn with_referrer_fetch_metadata( + mut self, + metadata: super::ModuleFetchMetadata, + ) -> Self { self.fetch_metadata = metadata; self } @@ -241,7 +243,7 @@ impl PendingDynamicModuleImport { self.phase } - pub(crate) fn fetch_metadata(&self) -> &ScriptFetchMetadata { + pub(crate) fn fetch_metadata(&self) -> &super::ModuleFetchMetadata { &self.fetch_metadata } diff --git a/moli-renderer-v8/src/module_runtime/graph.rs b/moli-renderer-v8/src/module_runtime/graph.rs index d675b5bd69c..81007207863 100644 --- a/moli-renderer-v8/src/module_runtime/graph.rs +++ b/moli-renderer-v8/src/module_runtime/graph.rs @@ -2704,10 +2704,10 @@ where attributes: request.attributes().clone(), phase: request.phase(), source_override: None, - fetch_metadata: ModuleFetchMetadata::from_dynamic_import_referrer_fetch_metadata( - request.fetch_metadata(), - ) - .with_import_map_integrity(integrity), + fetch_metadata: request + .fetch_metadata() + .clone() + .with_import_map_integrity(integrity), parser_owned: false, }) } diff --git a/moli-renderer-v8/src/module_runtime/host_callbacks.rs b/moli-renderer-v8/src/module_runtime/host_callbacks.rs index 5063abb9344..a7f07abfa1a 100644 --- a/moli-renderer-v8/src/module_runtime/host_callbacks.rs +++ b/moli-renderer-v8/src/module_runtime/host_callbacks.rs @@ -4,12 +4,10 @@ use url::Url; use super::{ModuleAttributesKey, ModuleImportPhase, PendingDynamicModuleImport}; use crate::{ context_bootstrap::child_browsing_context_handle_for_current_realm_scope, - planning::ScriptFetchMetadata, util::{ callback_arg_string, context_host_ptr_from_global_bridge, script_base_url_from_continuation_data, script_base_url_from_host_defined_options, - script_nonce_from_host_defined_options, script_parser_inserted_from_host_defined_options, - throw_type_error, v8_string, + script_fetch_metadata_from_host_defined_options, throw_type_error, v8_string, }, }; @@ -219,27 +217,14 @@ fn dynamic_import_base_url<'s>( fn dynamic_import_referrer_fetch_metadata( scope: &mut v8::PinScope<'_, '_>, host_defined_options: v8::Local<'_, v8::Data>, -) -> ScriptFetchMetadata { - let nonce = script_nonce_from_host_defined_options(scope, host_defined_options).or_else(|| { - scope - .get_current_host_defined_options() - .and_then(|options| script_nonce_from_host_defined_options(scope, options)) - }); - let parser_inserted = - script_parser_inserted_from_host_defined_options(scope, host_defined_options) - .or_else(|| { - scope - .get_current_host_defined_options() - .and_then(|options| { - script_parser_inserted_from_host_defined_options(scope, options) - }) - }) - .unwrap_or(false); - ScriptFetchMetadata { - nonce, - parser_inserted, - ..ScriptFetchMetadata::default() - } +) -> super::ModuleFetchMetadata { + script_fetch_metadata_from_host_defined_options(scope, host_defined_options) + .or_else(|| { + scope + .get_current_host_defined_options() + .and_then(|options| script_fetch_metadata_from_host_defined_options(scope, options)) + }) + .unwrap_or_default() } fn dynamic_import_base_url_from_compiled_string_resource( diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs index b207c0d08c9..6cba2c9406e 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs @@ -1133,7 +1133,7 @@ impl PageScriptHost { source, script_url, base_url, - script_nonce, + script_fetch_metadata, .. } = job; let result = match source { @@ -1145,7 +1145,7 @@ impl PageScriptHost { Some(&script_url), Some(&base_url), 0, - script_nonce.as_deref(), + script_fetch_metadata.as_ref(), true, ) } @@ -1270,7 +1270,7 @@ impl PageScriptHost { Some(&job.script_url), Some(&job.base_url), (*start_line).saturating_sub(1).min(i32::MAX as u64) as i32, - script.fetch_metadata.nonce.as_deref(), + Some(&script.fetch_metadata), true, ) }; diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs b/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs index 3eb7c80971e..3ae66331487 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs @@ -141,6 +141,7 @@ impl PageScriptHost { owner_document_handle: DomHandle, script_handle: DomHandle, source: String, + fetch_metadata: crate::planning::ScriptFetchMetadata, ) -> anyhow::Result<()> { let Some(child_handle) = self.child_browsing_context_handle_by_document_handle(scope, owner_document_handle) @@ -172,10 +173,7 @@ impl PageScriptHost { else { return Ok(()); }; - job.script_nonce = - crate::host::script_element_nonce_for_csp(self.dom_host(), script_handle) - .map(str::to_owned); - job.script_integrity = self.dom_host().get_attribute(script_handle, "integrity"); + job.script_fetch_metadata = Some(fetch_metadata); // Commit before entering V8: the script can remove and reinsert itself, // mutate another pending script, or replace its preparation Document. let _ = self diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs index 854c00747d3..ac3b04703a0 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs @@ -382,6 +382,7 @@ impl PageScriptHost { source_result: completion.result.clone(), script_url: pending.script.url, script_base_url: pending.script.base_url, + script_fetch_metadata: pending.script.fetch_metadata, }; self.queue_ready_child_external_classic_document_script(work) } else { @@ -441,6 +442,7 @@ impl PageScriptHost { Some(work.script_handle), work.script_url.clone(), work.script_base_url.clone(), + work.script_fetch_metadata.clone(), source.clone(), )?, ), @@ -1926,9 +1928,7 @@ impl PageScriptHost { unreachable!("frame classic execution action must have materialized source") } }; - let script_nonce = fetch_metadata.nonce; - let script_integrity = fetch_metadata.integrity; - let mut job = self + let job = self .frame_owner_store .child_prepared_classic_script_job_for_owner( target.child_handle(), @@ -1938,10 +1938,9 @@ impl PageScriptHost { Some(script_handle), script_url.clone(), script_base_url.clone(), - script_nonce, + Some(fetch_metadata), source, )?; - job.script_integrity = script_integrity; let finish = FrameDocumentClassicScriptExecutionFinish { child_handle: target.child_handle(), owner: target.owner(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_runtime_script_order.rs b/moli-renderer-v8/src/native_bridge/context_host/child_runtime_script_order.rs index 5d307ef038e..4c6eafbdd39 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_runtime_script_order.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_runtime_script_order.rs @@ -153,6 +153,7 @@ mod tests { source_result: Ok(String::new()), script_url: url::Url::parse("https://child-script-order.test/script.js").unwrap(), script_base_url: url::Url::parse("https://child-script-order.test/").unwrap(), + script_fetch_metadata: Default::default(), }) .into() } diff --git a/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs b/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs index 18fb069bc8b..1d6707647e7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs @@ -207,12 +207,14 @@ impl PageScriptHost { node, host_script_handle, source, + fetch_metadata, } => { debug_assert!(load_delay_binding.is_none()); Ok(Some(CommittedInlineClassicScript::new( node, host_script_handle, source, + fetch_metadata, ))) } PreparedRuntimeScriptStartCommit::InlineImportMap { diff --git a/moli-renderer-v8/src/native_bridge/element/script_execution.rs b/moli-renderer-v8/src/native_bridge/element/script_execution.rs index 87ce0a86849..78a1f17e048 100644 --- a/moli-renderer-v8/src/native_bridge/element/script_execution.rs +++ b/moli-renderer-v8/src/native_bridge/element/script_execution.rs @@ -38,8 +38,14 @@ pub(crate) fn prepare_inline_classic_frame_script_job_for_execution( script, source, ContentSecurityPolicyScriptElementRequest { - nonce: job.script_nonce.as_deref(), - integrity: job.script_integrity.as_deref(), + nonce: job + .script_fetch_metadata + .as_ref() + .and_then(|metadata| metadata.nonce.as_deref()), + integrity: job + .script_fetch_metadata + .as_ref() + .and_then(|metadata| metadata.integrity.as_deref()), parser_inserted, }, ) else { diff --git a/moli-renderer-v8/src/script_vm/eval_exec.rs b/moli-renderer-v8/src/script_vm/eval_exec.rs index e53e15dc728..c7ad2c0393a 100644 --- a/moli-renderer-v8/src/script_vm/eval_exec.rs +++ b/moli-renderer-v8/src/script_vm/eval_exec.rs @@ -17,7 +17,7 @@ use crate::network::ResourceRequestClient; use crate::script_provenance::CompiledStringProvenance; use crate::style_engine::StyleInvalidationTurnExitBoundary; use crate::util::{ - context_host_ptr_from_global_bridge, create_script_origin_with_base_url_and_nonce, + context_host_ptr_from_global_bridge, create_script_origin_with_base_url_and_fetch_metadata, script_base_url_continuation_data, v8_string, }; use crate::v8_execution_watchdog::{ @@ -71,7 +71,7 @@ struct MainFrameScriptJob<'a> { source: &'a str, provenance: Option, line_offset: i32, - script_nonce: Option<&'a str>, + script_fetch_metadata: Option<&'a crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, } @@ -164,7 +164,7 @@ pub(crate) fn execute_source_text_on_current_stack( script_url: Option<&Url>, script_base_url: Option<&Url>, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, ) -> Result<()> { let provenance = script_url.cloned().map(|source_url| { @@ -178,7 +178,7 @@ pub(crate) fn execute_source_text_on_current_stack( source, provenance.as_ref(), line_offset, - script_nonce, + script_fetch_metadata, drain_microtasks, UncaughtScriptReportTarget::CurrentWindow, SourceTextScriptCompletionMode::Ignore, @@ -193,7 +193,7 @@ fn execute_source_text_on_current_stack_with_completion( source: &str, provenance: Option<&CompiledStringProvenance>, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, report_target: UncaughtScriptReportTarget, completion_mode: SourceTextScriptCompletionMode, @@ -204,7 +204,7 @@ fn execute_source_text_on_current_stack_with_completion( source, provenance, line_offset, - script_nonce, + script_fetch_metadata, report_target, completion_mode, ); @@ -232,7 +232,7 @@ fn run_source_text_on_current_stack_with_completion( source: &str, provenance: Option<&CompiledStringProvenance>, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, report_target: UncaughtScriptReportTarget, completion_mode: SourceTextScriptCompletionMode, ) -> RawScriptExecutionResult { @@ -245,13 +245,18 @@ fn run_source_text_on_current_stack_with_completion( } let source = v8_string(&scope, source).ok_or_else(|| anyhow!("failed to allocate v8 source string"))?; + let import_metadata = script_fetch_metadata + .map( + crate::module_runtime::ModuleFetchMetadata::from_dynamic_import_referrer_fetch_metadata, + ) + .unwrap_or_default(); let origin = provenance.map(|provenance| { - create_script_origin_with_base_url_and_nonce( + create_script_origin_with_base_url_and_fetch_metadata( &mut scope, provenance.source_url().as_str(), line_offset, Some(provenance.module_base_url()), - script_nonce, + &import_metadata, ) }); let script = v8::Script::compile(&scope, source, origin.as_ref()).ok_or_else(|| { @@ -419,14 +424,14 @@ impl ScriptVm { source: &str, script_url: Option<&Url>, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, ) -> PendingScriptTurn> { let job = MainFrameScriptJob { source, provenance: script_url.cloned().map(CompiledStringProvenance::at_url), line_offset, - script_nonce, + script_fetch_metadata, drain_microtasks, }; self.execute_main_frame_script_job_without_turn_drain(job) @@ -452,7 +457,7 @@ impl ScriptVm { job.source, job.provenance, job.line_offset, - job.script_nonce, + job.script_fetch_metadata, job.drain_microtasks, UncaughtScriptReportTarget::LogOnly, ) @@ -463,14 +468,14 @@ impl ScriptVm { source: &str, provenance: &CompiledStringProvenance, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, ) -> std::result::Result<(), RawScriptExecutionError> { self.execute_main_frame_script_job_without_turn_drain(MainFrameScriptJob { source, provenance: Some(provenance.clone()), line_offset, - script_nonce, + script_fetch_metadata, drain_microtasks, }) .into_inner_for_enclosing_script_turn() @@ -512,7 +517,7 @@ impl ScriptVm { source: &str, provenance: Option, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, report_target: UncaughtScriptReportTarget, ) -> PendingScriptTurn> { @@ -521,7 +526,7 @@ impl ScriptVm { source, provenance, line_offset, - script_nonce, + script_fetch_metadata, drain_microtasks, report_target, SourceTextScriptCompletionMode::Ignore, @@ -536,7 +541,7 @@ impl ScriptVm { script_url: Option<&Url>, script_base_url: Option<&Url>, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, sync_child_records: bool, completion_mode: SourceTextScriptCompletionMode, @@ -553,7 +558,7 @@ impl ScriptVm { source, provenance, line_offset, - script_nonce, + script_fetch_metadata, drain_microtasks, UncaughtScriptReportTarget::CurrentWindow, completion_mode, @@ -582,7 +587,7 @@ impl ScriptVm { script_url: Option<&Url>, script_base_url: Option<&Url>, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, completion_mode: SourceTextScriptCompletionMode, clean_up_classic_script: bool, ) -> Result { @@ -597,7 +602,7 @@ impl ScriptVm { source, provenance, line_offset, - script_nonce, + script_fetch_metadata, clean_up_classic_script, UncaughtScriptReportTarget::CurrentWindow, completion_mode, @@ -612,13 +617,13 @@ impl ScriptVm { source: &str, provenance: Option, line_offset: i32, - script_nonce: Option<&str>, + script_fetch_metadata: Option<&crate::planning::ScriptFetchMetadata>, drain_microtasks: bool, report_target: UncaughtScriptReportTarget, completion_mode: SourceTextScriptCompletionMode, ) -> PendingScriptTurn> { let source = source.to_owned(); - let script_nonce = script_nonce.map(str::to_owned); + let script_fetch_metadata = script_fetch_metadata.cloned(); PendingScriptTurn::new( self.renderer_document_isolate .with_renderer_document_isolate_mut::< @@ -633,7 +638,7 @@ impl ScriptVm { &source, provenance.as_ref(), line_offset, - script_nonce.as_deref(), + script_fetch_metadata.as_ref(), drain_microtasks, report_target, completion_mode, diff --git a/moli-renderer-v8/src/script_vm/frame_script_jobs.rs b/moli-renderer-v8/src/script_vm/frame_script_jobs.rs index a0c3b12d87e..26cd696080e 100644 --- a/moli-renderer-v8/src/script_vm/frame_script_jobs.rs +++ b/moli-renderer-v8/src/script_vm/frame_script_jobs.rs @@ -154,7 +154,7 @@ impl ScriptVm { source, script_url, base_url, - script_nonce, + script_fetch_metadata, .. } = job; let result = match source { @@ -177,7 +177,7 @@ impl ScriptVm { Some(&script_url), Some(&base_url), 0, - script_nonce.as_deref(), + script_fetch_metadata.as_ref(), true, true, source_completion_mode, @@ -189,7 +189,7 @@ impl ScriptVm { Some(&script_url), Some(&base_url), 0, - script_nonce.as_deref(), + script_fetch_metadata.as_ref(), source_completion_mode, clean_up_classic_script, ), diff --git a/moli-renderer-v8/src/script_vm/native_module.rs b/moli-renderer-v8/src/script_vm/native_module.rs index 4d2da6dfaa1..1e7b0818f31 100644 --- a/moli-renderer-v8/src/script_vm/native_module.rs +++ b/moli-renderer-v8/src/script_vm/native_module.rs @@ -1209,8 +1209,7 @@ fn create_module_script_origin<'s>( crate::util::script_host_defined_options_with_fetch_metadata( scope, base_url, - fetch_metadata.nonce(), - fetch_metadata.parser_inserted, + fetch_metadata, false, None, ) diff --git a/moli-renderer-v8/src/script_vm/prepared_scripts.rs b/moli-renderer-v8/src/script_vm/prepared_scripts.rs index 5b1f1ceccc3..fab5d23bdf9 100644 --- a/moli-renderer-v8/src/script_vm/prepared_scripts.rs +++ b/moli-renderer-v8/src/script_vm/prepared_scripts.rs @@ -605,7 +605,7 @@ impl ScriptVm { } else { 0 }, - fetch_metadata.nonce.as_deref(), + Some(fetch_metadata), true, ); match result { diff --git a/moli-renderer-v8/src/script_vm/tests/string_timers.rs b/moli-renderer-v8/src/script_vm/tests/string_timers.rs index d4f12161893..44b43423fa2 100644 --- a/moli-renderer-v8/src/script_vm/tests/string_timers.rs +++ b/moli-renderer-v8/src/script_vm/tests/string_timers.rs @@ -6,7 +6,13 @@ fn execute_nonce_script(vm: &mut ScriptVm, source: &str, url: &Url, nonce: Optio source, &CompiledStringProvenance::at_url(url.clone()), 0, - nonce, + Some(&crate::planning::ScriptFetchMetadata { + nonce: nonce.map(str::to_owned), + cross_origin: Some("use-credentials".to_owned()), + parser_inserted: true, + integrity: Some("sha256-AAAA".to_owned()), + ..Default::default() + }), true, ) .map_err(|error| error.into_anyhow()) @@ -29,9 +35,19 @@ fn assert_import_nonce(vm: &mut ScriptVm, base_url: &Url, nonce: Option<&str>) { .into_dynamic_import_request(); assert_eq!(request.specifier(), "./dependency.mjs"); assert_eq!(request.base_url(), base_url); - assert_eq!(request.fetch_metadata().nonce.as_deref(), nonce); + assert_eq!(request.fetch_metadata().nonce(), nonce); + assert_eq!( + request.fetch_metadata().credentials_mode, + moli_fetch::RequestCredentialsMode::Include + ); assert!(!request.fetch_metadata().parser_inserted); - assert!(request.fetch_metadata().integrity.is_none()); + assert!( + request + .fetch_metadata() + .request_metadata + .integrity + .is_none() + ); } #[test] @@ -52,8 +68,8 @@ fn dynamic_function_imports_preserve_each_initiators_nonce_for_identical_source( .into_dynamic_import_request(); assert_eq!(request.specifier(), "./dependency.mjs"); assert_eq!(request.base_url(), &script_url); - assert_eq!(request.fetch_metadata().nonce.as_deref(), nonce); - assert!(request.fetch_metadata().integrity.is_none()); + assert_eq!(request.fetch_metadata().nonce(), nonce); + assert!(request.fetch_metadata().integrity().is_none()); } } @@ -92,7 +108,7 @@ fn dynamic_function_imports_keep_creation_metadata_when_invoked_by_another_scrip .expect("each created Function should queue its own import") .into_dynamic_import_request(); assert_eq!(request.base_url(), &Url::parse(url).unwrap()); - assert_eq!(request.fetch_metadata().nonce.as_deref(), nonce); + assert_eq!(request.fetch_metadata().nonce(), nonce); } } @@ -113,7 +129,7 @@ fn dynamic_function_imports_keep_origins_for_async_and_generator_constructors() .expect("each constructor kind should queue an import") .into_dynamic_import_request(); assert_eq!(request.base_url(), &script_url); - assert_eq!(request.fetch_metadata().nonce.as_deref(), nonce); + assert_eq!(request.fetch_metadata().nonce(), nonce); } } } @@ -199,7 +215,7 @@ fn dynamic_function_origin_keys_preserve_trusted_types_source_checks() { } #[test] -fn string_timers_preserve_nonce_for_timeout_interval_and_nested_source() { +fn string_timers_preserve_fetch_options_for_timeout_interval_and_nested_source() { for (source, timer_turns) in [ (r#"setTimeout("import('./dependency.mjs')", 0);"#, 1), ( diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rs index f241ebc288f..141e80e064c 100644 --- a/moli-renderer-v8/src/util.rs +++ b/moli-renderer-v8/src/util.rs @@ -321,19 +321,25 @@ pub(super) fn create_script_origin_with_base_url<'s>( line_offset: i32, base_url: Option<&Url>, ) -> v8::ScriptOrigin<'s> { - create_script_origin_with_base_url_and_nonce(scope, resource_name, line_offset, base_url, None) + create_script_origin_with_base_url_and_fetch_metadata( + scope, + resource_name, + line_offset, + base_url, + &crate::module_runtime::ModuleFetchMetadata::default(), + ) } -pub(super) fn create_script_origin_with_base_url_and_nonce<'s>( +pub(super) fn create_script_origin_with_base_url_and_fetch_metadata<'s>( scope: &mut v8::PinScope<'s, '_>, resource_name: &str, line_offset: i32, base_url: Option<&Url>, - nonce: Option<&str>, + metadata: &crate::module_runtime::ModuleFetchMetadata, ) -> v8::ScriptOrigin<'s> { let name = v8::String::new(scope, resource_name).expect("v8 string allocation"); let host_defined_options = base_url.and_then(|base_url| { - script_host_defined_options_with_base_url_and_nonce(scope, base_url, nonce) + script_host_defined_options_with_fetch_metadata(scope, base_url, metadata, false, None) }); v8::ScriptOrigin::new( scope, @@ -484,39 +490,48 @@ pub(crate) fn script_base_url_continuation_data<'s>( Some(crate::resource_initiator::with_base_url(scope, base)) } +#[cfg(test)] pub(crate) fn script_host_defined_options_with_base_url_and_nonce<'s>( scope: &mut v8::PinScope<'s, '_>, base_url: &Url, nonce: Option<&str>, ) -> Option> { - script_host_defined_options_with_fetch_metadata(scope, base_url, nonce, false, false, None) + let metadata = + crate::module_runtime::ModuleFetchMetadata::from_dynamic_import_referrer_fetch_metadata( + &crate::planning::ScriptFetchMetadata { + nonce: nonce.map(str::to_owned), + ..Default::default() + }, + ); + script_host_defined_options_with_fetch_metadata(scope, base_url, &metadata, false, None) } pub(crate) fn script_host_defined_options_with_fetch_metadata<'s>( scope: &mut v8::PinScope<'s, '_>, base_url: &Url, - nonce: Option<&str>, - parser_inserted: bool, + metadata: &crate::module_runtime::ModuleFetchMetadata, muted_errors: bool, request_url: Option<&Url>, ) -> Option> { - // V8 15.2 looks up Function/indirect-eval cache entries before resolving - // the caller script. Partition caller metadata without disabling caching. - // The trailing comment stays outside generated functions' source ranges. + // V8 looks up Function/eval cache entries before resolving the caller. + // Partition all inherited fetch metadata without changing function source. let partition = format!( "\n// moli-referrer:{}", moli_crypto::sha256_hex(format!( - "{base_url}\0{}\0{parser_inserted}\0{muted_errors}\0{}", - nonce.unwrap_or_default(), - request_url.map(Url::as_str).unwrap_or_default() + "{base_url}\0{}\0{}\0{muted_errors}\0{}\0{:?}\0{:?}", + metadata.nonce().unwrap_or_default(), + metadata.parser_inserted, + request_url.map(Url::as_str).unwrap_or_default(), + metadata.credentials_mode, + metadata.request_metadata.referrer_policy, )) ); let marker = v8_string(scope, SCRIPT_BASE_URL_HOST_DEFINED_OPTIONS_MARKER)?; let value = v8_string(scope, base_url.as_str())?; - let nonce = v8_string(scope, nonce.unwrap_or_default())?; + let nonce = v8_string(scope, metadata.nonce().unwrap_or_default())?; let parser_metadata = v8_string( scope, - if parser_inserted { + if metadata.parser_inserted { "parser-inserted" } else { "not-parser-inserted" @@ -524,7 +539,15 @@ pub(crate) fn script_host_defined_options_with_fetch_metadata<'s>( )?; let partition = v8_string(scope, &partition)?; let request_url = v8_string(scope, request_url.map(Url::as_str).unwrap_or_default())?; - let options = v8::PrimitiveArray::new(scope, 7); + let credentials = v8_string( + scope, + match metadata.credentials_mode { + moli_fetch::RequestCredentialsMode::Omit => "omit", + moli_fetch::RequestCredentialsMode::SameOrigin => "same-origin", + moli_fetch::RequestCredentialsMode::Include => "include", + }, + )?; + let options = v8::PrimitiveArray::new(scope, 8); options.set(scope, 0, marker.into()); options.set(scope, 1, value.into()); options.set(scope, 2, nonce.into()); @@ -532,9 +555,41 @@ pub(crate) fn script_host_defined_options_with_fetch_metadata<'s>( options.set(scope, 4, partition.into()); options.set(scope, 5, v8::Boolean::new(scope, muted_errors).into()); options.set(scope, 6, request_url.into()); + options.set(scope, 7, credentials.into()); Some(options.into()) } +pub(crate) fn script_fetch_metadata_from_host_defined_options( + scope: &mut v8::PinScope<'_, '_>, + host_defined_options: v8::Local<'_, v8::Data>, +) -> Option { + script_base_url_from_host_defined_options(scope, host_defined_options)?; + let options = script_host_defined_options_as_fixed_array(host_defined_options)?; + let credentials_mode = if options.length() < 8 { + moli_fetch::RequestCredentialsMode::SameOrigin + } else { + let value = v8::Local::::try_from(options.get(scope, 7)?).ok()?; + match value.to_rust_string_lossy(scope).as_str() { + "omit" => moli_fetch::RequestCredentialsMode::Omit, + "same-origin" => moli_fetch::RequestCredentialsMode::SameOrigin, + "include" => moli_fetch::RequestCredentialsMode::Include, + _ => return None, + } + }; + Some(crate::module_runtime::ModuleFetchMetadata { + credentials_mode, + request_metadata: moli_fetch::ScriptFetchRequestMetadata { + nonce: script_nonce_from_host_defined_options(scope, host_defined_options), + ..Default::default() + }, + parser_inserted: script_parser_inserted_from_host_defined_options( + scope, + host_defined_options, + ) + .unwrap_or(false), + }) +} + pub(super) fn enqueue_host_microtask( scope: &mut v8::PinScope<'_, '_>, callback: v8::Local<'_, v8::Function>, @@ -1027,7 +1082,7 @@ mod tests { use super::{ SCRIPT_BASE_URL_HOST_DEFINED_OPTIONS_MARKER, object_chain_contains, - script_base_url_from_host_defined_options, + script_base_url_from_host_defined_options, script_fetch_metadata_from_host_defined_options, script_host_defined_options_with_base_url_and_nonce, script_host_defined_options_with_fetch_metadata, script_muted_errors_from_host_defined_options, script_nonce_from_host_defined_options, @@ -1195,8 +1250,7 @@ mod tests { let muted = script_host_defined_options_with_fetch_metadata( scope, &base_url, - None, - false, + &crate::module_runtime::ModuleFetchMetadata::default(), true, Some(&request_url), ) @@ -1263,8 +1317,14 @@ mod tests { let parser_options = script_host_defined_options_with_fetch_metadata( scope, &base_url, - Some("abc123"), - true, + &crate::module_runtime::ModuleFetchMetadata { + parser_inserted: true, + request_metadata: moli_fetch::ScriptFetchRequestMetadata { + nonce: Some("abc123".to_owned()), + ..Default::default() + }, + ..Default::default() + }, false, None, ) @@ -1275,6 +1335,79 @@ mod tests { ); } + #[test] + fn script_host_defined_options_preserve_dynamic_import_credentials() { + use crate::module_runtime::ModuleFetchMetadata; + use moli_fetch::RequestCredentialsMode; + + ensure_v8(); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + let scope = pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + let base_url = Url::parse("https://example.test/entry.js").unwrap(); + + for credentials_mode in [ + RequestCredentialsMode::Omit, + RequestCredentialsMode::SameOrigin, + RequestCredentialsMode::Include, + ] { + let metadata = ModuleFetchMetadata { + credentials_mode, + parser_inserted: true, + request_metadata: moli_fetch::ScriptFetchRequestMetadata { + nonce: Some("initiator-nonce".to_owned()), + // The importing script's SRI hash must not apply to its imports. + integrity: Some("sha256-AAAA".to_owned()), + ..Default::default() + }, + }; + let options = script_host_defined_options_with_fetch_metadata( + scope, &base_url, &metadata, false, None, + ) + .unwrap(); + let decoded = script_fetch_metadata_from_host_defined_options(scope, options).unwrap(); + assert_eq!(decoded.credentials_mode, credentials_mode); + assert_eq!(decoded.nonce(), Some("initiator-nonce")); + assert!(decoded.parser_inserted); + assert!(decoded.integrity().is_none()); + } + + let legacy = primitive_host_defined_options( + scope, + &[ + SCRIPT_BASE_URL_HOST_DEFINED_OPTIONS_MARKER, + base_url.as_str(), + "", + "not-parser-inserted", + ], + ); + assert_eq!( + script_fetch_metadata_from_host_defined_options(scope, legacy), + Some(ModuleFetchMetadata::default()) + ); + for (marker, credentials) in [ + (SCRIPT_BASE_URL_HOST_DEFINED_OPTIONS_MARKER, "invalid"), + ("not-moli", "include"), + ] { + let options = primitive_host_defined_options( + scope, + &[ + marker, + base_url.as_str(), + "", + "not-parser-inserted", + "", + "", + "", + credentials, + ], + ); + assert!(script_fetch_metadata_from_host_defined_options(scope, options).is_none()); + } + } + #[test] fn script_host_defined_options_ignore_non_fixed_array_data() { ensure_v8(); 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 8c868d36cd2..acb63804af4 100644 --- a/moli-renderer-v8/src/worker/global_scope/import_scripts.rs +++ b/moli-renderer-v8/src/worker/global_scope/import_scripts.rs @@ -466,8 +466,7 @@ fn evaluate_worker_script( let host_defined_options = crate::util::script_host_defined_options_with_fetch_metadata( scope, base_url, - None, - false, + &crate::module_runtime::ModuleFetchMetadata::default(), muted_errors, Some(request_url), );