From edd8f770513a4e085adcc5cb80beea82286f574d Mon Sep 17 00:00:00 2001 From: ldm0 Date: Fri, 6 Nov 2026 02:23:51 +0800 Subject: [PATCH] fix(performance): retain fetch and XHR initiator URLs Capture the outer classic script source independently of its resolution base and preserve it across Promise continuations. Snapshot the source and Window origin when admitting a fetch or XHR, then retain it through response completion and lazy resource timing publication. Expose initiatorUrl through native resource timing slots and toJSON. Keep unknown, redacted, opaque, cached and synthetic response attribution empty. Other resource producers and callback task sources remain unattributed. Add regression coverage for caller versus callee provenance, delayed response publication, Promise and microtask propagation, and readable network response requirements for both buffered and streaming completions. --- .../context_bootstrap/performance_runtime.rs | 6 + .../performance_runtime/entries.rs | 15 ++ .../performance_runtime/fetch_timing.rs | 31 +++ .../window_state/pending.rs | 7 +- .../context_host/resource_loading.rs | 16 ++ .../src/network_host/fetch/bindings/paths.rs | 2 + .../fetch/bindings/service_worker.rs | 1 + moli-renderer-v8/src/network_host/xhr/send.rs | 1 + moli-renderer-v8/src/script_continuation.rs | 77 +++++- moli-renderer-v8/src/script_vm/eval_exec.rs | 13 + .../subresource_fetch/fetch_dispatch.rs | 5 + .../script_vm/subresource_fetch/streaming.rs | 10 +- .../src/script_vm/tests/dom_xhr/xhr.rs | 7 + .../script_vm/tests/fetch_resource_timing.rs | 253 ++++++++++++++++++ moli-renderer-v8/src/script_vm/tests/mod.rs | 2 + moli-renderer-v8/src/types.rs | 8 +- 16 files changed, 438 insertions(+), 16 deletions(-) diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs index da339a1db21..fd0b887bf73 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs @@ -42,6 +42,8 @@ pub(in crate::context_bootstrap) const PERFORMANCE_ENTRY_DETAIL_SLOT: &str = "__moliPerformanceEntryDetail"; pub(in crate::context_bootstrap) const PERFORMANCE_RESOURCE_INITIATOR_TYPE_SLOT: &str = "__moliPerformanceResourceInitiatorType"; +pub(in crate::context_bootstrap) const PERFORMANCE_RESOURCE_INITIATOR_URL_SLOT: &str = + "__moliPerformanceResourceInitiatorUrl"; pub(in crate::context_bootstrap) const PERFORMANCE_RESOURCE_NEXT_HOP_PROTOCOL_SLOT: &str = "__moliPerformanceResourceNextHopProtocol"; pub(in crate::context_bootstrap) const PERFORMANCE_RESOURCE_WORKER_START_SLOT: &str = @@ -341,6 +343,7 @@ pub(crate) struct ResourcePerformanceEntry { preload_state: moli_fetch::ResponsePreloadState, name: String, initiator_type: String, + initiator_url: String, start_unix_millis: Option, fetch_start_unix_millis: Option, redirect_start_unix_millis: Option, @@ -452,6 +455,7 @@ impl ResourcePerformanceEntry { preload_state, name: name.into(), initiator_type: initiator_type.to_owned(), + initiator_url: String::new(), start_unix_millis, fetch_start_unix_millis: None, redirect_start_unix_millis: None, @@ -530,6 +534,7 @@ impl ResourcePerformanceEntry { preload_state: Default::default(), name: name.into(), initiator_type: initiator_type.to_owned(), + initiator_url: String::new(), start_unix_millis, fetch_start_unix_millis: None, redirect_start_unix_millis: None, @@ -611,6 +616,7 @@ fn append_resource_performance_entry<'s>( resource, &entry.delivery_type, &entry.content_encoding, + &entry.initiator_url, ); if let Some(end_time) = end_time { let fetch_start = entry.fetch_start_unix_millis.map_or(start_time, |start| { diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs index 390009e7fa6..2dcb351c8af 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs @@ -67,6 +67,9 @@ struct PerformanceResourceTimingSlotDeclaration { #[webapi(slot = PERFORMANCE_RESOURCE_INITIATOR_TYPE_SLOT)] initiator_type: String, + #[webapi(slot = PERFORMANCE_RESOURCE_INITIATOR_URL_SLOT, constructor_default = "")] + initiator_url: &'static str, + #[webapi(slot = PERFORMANCE_RESOURCE_NEXT_HOP_PROTOCOL_SLOT, constructor_default = "")] next_hop_protocol: &'static str, @@ -158,6 +161,7 @@ struct PerformanceResourceTimingJsonSnapshotDeclaration { duration: f64, navigation_id: f64, initiator_type: String, + initiator_url: String, delivery_type: String, next_hop_protocol: String, worker_start: f64, @@ -200,6 +204,7 @@ impl PerformanceResourceTimingJsonSnapshotDeclaration { performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_DURATION_SLOT)?, performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_NAVIGATION_ID_SLOT)?, performance_entry_slot_string(scope, entry, PERFORMANCE_RESOURCE_INITIATOR_TYPE_SLOT)?, + performance_entry_slot_string(scope, entry, PERFORMANCE_RESOURCE_INITIATOR_URL_SLOT)?, performance_entry_slot_string(scope, entry, PERFORMANCE_RESOURCE_DELIVERY_TYPE_SLOT)?, performance_entry_slot_string( scope, @@ -560,6 +565,13 @@ struct PerformanceResourceTimingPrototypeAccessorsDeclaration { enumerable )] content_encoding: (), + #[webapi( + accessor_property, + getter = performance_resource_timing_attribute_getter_callback, + data = callback_data_index_value(scope, 28), + enumerable + )] + initiator_url: (), } #[derive(WebApiFunctionTemplate)] @@ -829,6 +841,7 @@ const PERFORMANCE_RESOURCE_TIMING_ATTRIBUTE_SLOTS: &[&str] = &[ PERFORMANCE_RESOURCE_RENDER_BLOCKING_STATUS_SLOT, PERFORMANCE_RESOURCE_CONTENT_TYPE_SLOT, PERFORMANCE_RESOURCE_CONTENT_ENCODING_SLOT, + PERFORMANCE_RESOURCE_INITIATOR_URL_SLOT, ]; pub(in crate::context_bootstrap) fn performance_get_entries_callback<'s>( @@ -1095,10 +1108,12 @@ pub(super) fn initialize_resource_timing_response_metadata<'s>( entry: v8::Local<'s, v8::Object>, delivery_type: &str, content_encoding: &str, + initiator_url: &str, ) { for (slot, value) in [ (PERFORMANCE_RESOURCE_DELIVERY_TYPE_SLOT, delivery_type), (PERFORMANCE_RESOURCE_CONTENT_ENCODING_SLOT, content_encoding), + (PERFORMANCE_RESOURCE_INITIATOR_URL_SLOT, initiator_url), ] { if let Some(value) = v8_string(scope, value) { set_private_value(scope, entry, slot, value.into()); diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs index c208dc3029e..e9ced44dbfd 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs @@ -11,6 +11,7 @@ use super::{ResourceConnectionTiming, ResourcePerformanceEntry}; #[derive(Debug)] pub(crate) struct FetchResourceTiming { initiator_type: &'static str, + initiator_url: String, started: Instant, start_unix_millis: f64, response_timing: Option>, @@ -46,12 +47,35 @@ impl FetchResourceTiming { ) -> Self { Self { initiator_type, + initiator_url: String::new(), started, start_unix_millis, response_timing: None, } } + pub(crate) fn capture_window_initiator( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host: &mut crate::native_bridge::JsContextHost, + ) { + let Some(initiator) = crate::script_continuation::resource_initiator(scope) else { + return; + }; + if initiator.origin.is_some() + && initiator.origin == host.window_origin_key_for_current_realm(scope) + { + self.initiator_url = initiator + .source_url + .map(|url| url.into()) + .unwrap_or_default(); + } + } + + pub(crate) fn clear_initiator(&mut self) { + self.initiator_url.clear(); + } + fn now(&self) -> f64 { self.start_unix_millis + self.started.elapsed().as_secs_f64() * 1000.0 } @@ -158,6 +182,13 @@ impl FetchResourceTiming { ); if readable { self.apply_native_body_sizes(&mut entry, head); + // TAO alone cannot expose the initiating script, and a locally + // fulfilled response does not represent another network download. + if head.cache_state == ResponseCacheState::None + && !head.preload_state.from_service_worker() + { + entry.initiator_url.clone_from(&self.initiator_url); + } } if !readable { entry.response_status = 0.0; diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/window_state/pending.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/window_state/pending.rs index 11d1c4055ce..42889ea8c90 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/window_state/pending.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/window_state/pending.rs @@ -68,13 +68,16 @@ pub(in crate::context_bootstrap::performance_runtime) fn queue_pending_resource_ ) { let global = scope.get_current_context().global(scope); let entries = ensure_private_array(scope, global, WINDOW_PERFORMANCE_PENDING_RESOURCES_SLOT, 0); - let record = v8::Array::new(scope, 25); + let record = v8::Array::new(scope, 26); let Some(name) = v8_string(scope, &entry.name) else { return; }; let Some(initiator_type) = v8_string(scope, &entry.initiator_type) else { return; }; + let Some(initiator_url) = v8_string(scope, &entry.initiator_url) else { + return; + }; let Some(render_blocking_status) = v8_string(scope, &entry.render_blocking_status) else { return; }; @@ -160,6 +163,7 @@ pub(in crate::context_bootstrap::performance_runtime) fn queue_pending_resource_ .redirect_end_unix_millis .map(|value| v8::Number::new(scope, value).into()) .unwrap_or_else(|| v8::undefined(scope).into()), + initiator_url.into(), ]; for (index, value) in fields.into_iter().enumerate() { let _ = record.set_index(scope, index as u32, value); @@ -185,6 +189,7 @@ pub(in crate::context_bootstrap::performance_runtime) fn take_pending_resource_e preload_state: Default::default(), name: array_string(scope, record, 0)?, initiator_type: array_string(scope, record, 1)?, + initiator_url: array_string(scope, record, 25)?, redirect_start_unix_millis: record .get_index(scope, 23) .filter(|value| !value.is_undefined()) diff --git a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs index 6871bb6e163..ebe4bb8b251 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs @@ -676,6 +676,7 @@ impl JsContextHost { policy_context: crate::types::SubresourcePolicyContext, blob_url_entry: Option, mut info: PendingSubresourceFetchInfo, + scope: &mut v8::PinScope<'_, '_>, ) -> Option<()> { self.assign_pending_subresource_fetch_identity(&mut info); let disposition = if keepalive { @@ -695,6 +696,8 @@ impl JsContextHost { None, )?; self.push_pending_subresource_fetch_info(info.clone()); + let mut timing = crate::context_bootstrap::FetchResourceTiming::new(); + timing.capture_window_initiator(scope, self); self.pending_subresource_fetches.insert( info.internal_id, PendingSubresourceFetchState { @@ -715,6 +718,7 @@ impl JsContextHost { csp_report_context, redirect_mode, integrity, + timing, ), ), deferred_request_started: false, @@ -971,6 +975,7 @@ impl JsContextHost { policy_context: crate::types::SubresourcePolicyContext, mut info: PendingSubresourceFetchInfo, defer_request_started: bool, + scope: &mut v8::PinScope<'_, '_>, ) -> Option { self.assign_pending_subresource_fetch_identity(&mut info); let internal_id = info.internal_id; @@ -993,6 +998,8 @@ impl JsContextHost { if !defer_request_started { self.record_pending_subresource_request_started(&info, load.disposition()); } + let mut timing = crate::context_bootstrap::FetchResourceTiming::new(); + timing.capture_window_initiator(scope, self); self.pending_subresource_fetches.insert( internal_id, PendingSubresourceFetchState { @@ -1013,6 +1020,7 @@ impl JsContextHost { csp_report_context, redirect_mode, integrity, + timing, ), ), deferred_request_started: defer_request_started, @@ -1704,6 +1712,9 @@ impl JsContextHost { None, ); self.push_pending_subresource_fetch_info(info.clone()); + let mut timing = + crate::context_bootstrap::FetchResourceTiming::for_initiator_type("xmlhttprequest"); + timing.capture_window_initiator(scope, self); self.pending_subresource_fetches.insert( internal_id, PendingSubresourceFetchState { @@ -1720,6 +1731,7 @@ impl JsContextHost { xhr, use_cors_preflight, csp, + timing, ), deferred_request_started: false, blob_url_entry, @@ -1793,6 +1805,9 @@ impl JsContextHost { cancel_handle.clone(), ); self.record_pending_subresource_request_started(&info, load.disposition()); + let mut timing = + crate::context_bootstrap::FetchResourceTiming::for_initiator_type("xmlhttprequest"); + timing.capture_window_initiator(scope, self); self.pending_subresource_fetches.insert( internal_id, PendingSubresourceFetchState { @@ -1809,6 +1824,7 @@ impl JsContextHost { xhr, use_cors_preflight, csp, + timing, ), deferred_request_started: false, blob_url_entry: None, diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs b/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs index 0a89e42768a..2d9f3a0d771 100644 --- a/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs +++ b/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs @@ -48,6 +48,7 @@ pub(super) fn record_intercepted_fetch( resource_type: SubresourceResourceType::Fetch, request_cookie_report, }, + scope, ) } @@ -340,6 +341,7 @@ pub(super) fn spawn_network_fetch<'s>( request_cookie_report, }, requires_preflight, + scope, ) .ok_or_else(|| anyhow::anyhow!("Failed to fetch"))?; if prepared.body_source_is_null diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs b/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs index e784505f30c..a9a7aca9a2a 100644 --- a/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs +++ b/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs @@ -85,6 +85,7 @@ pub(super) fn dispatch_service_worker_fetch<'s>( request_cookie_report: request_cookie_report.clone(), }, requires_preflight, + scope, ) .ok_or_else(|| anyhow::anyhow!("Failed to fetch"))?; let mut request = host.service_worker_fetch_request( diff --git a/moli-renderer-v8/src/network_host/xhr/send.rs b/moli-renderer-v8/src/network_host/xhr/send.rs index 7317dece10a..1bdd5d51b9a 100644 --- a/moli-renderer-v8/src/network_host/xhr/send.rs +++ b/moli-renderer-v8/src/network_host/xhr/send.rs @@ -304,6 +304,7 @@ fn send_synchronous_network_xhr( ) { let mut timing = crate::context_bootstrap::FetchResourceTiming::for_initiator_type("xmlhttprequest"); + timing.capture_window_initiator(scope, host); let csp = crate::network_host::WindowCspRequestContext::capture(scope, host, prepared.owner) .expect("synchronous XHR prepared a live Document request authority"); let mut request = Request::new_bytes( diff --git a/moli-renderer-v8/src/script_continuation.rs b/moli-renderer-v8/src/script_continuation.rs index d0bfbc0bd35..0077a5a985a 100644 --- a/moli-renderer-v8/src/script_continuation.rs +++ b/moli-renderer-v8/src/script_continuation.rs @@ -2,7 +2,8 @@ //! the Window generation and origin captured before a subsequent navigation. use crate::{ native_bridge::{ - RuntimeObservableContextToken, WindowExecutionContextIdentity, WindowSecurityOrigin, + RuntimeObservableContextToken, WindowExecutionContextIdentity, WindowOriginKey, + WindowSecurityOrigin, }, util::{get_private_value, set_private_value}, }; @@ -10,6 +11,16 @@ use crate::{ const BASE_URL_SLOT: &str = "moli.scriptContinuationBaseURL"; const WINDOW_SLOT: &str = "moli.scriptContinuationWindow"; const WINDOW_STATE_SLOT: &str = "moli.scriptContinuationWindowState"; +const RESOURCE_INITIATOR_SLOT: &str = "moli.scriptContinuationResourceInitiator"; +const RESOURCE_INITIATOR_STATE_SLOT: &str = "moli.scriptContinuationResourceInitiatorState"; + +/// Attribution is separate from the script's resolution base and from Window +/// authority. A redacted script still establishes an explicit unknown source. +#[derive(Clone, Debug)] +pub(crate) struct ResourceInitiator { + pub(crate) source_url: Option, + pub(crate) origin: Option, +} #[derive(Clone)] pub(crate) struct WindowContinuation { @@ -20,7 +31,8 @@ pub(crate) struct WindowContinuation { pub(crate) fn base_url_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { let data = scope.get_continuation_preserved_embedder_data(); if let Ok(object) = v8::Local::::try_from(data) - && get_private_value(scope, object, WINDOW_SLOT).is_some() + && (get_private_value(scope, object, WINDOW_SLOT).is_some() + || get_private_value(scope, object, RESOURCE_INITIATOR_SLOT).is_some()) { // Undefined is a valid base URL payload, not the absence of the // surrounding continuation record. @@ -30,6 +42,42 @@ pub(crate) fn base_url_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local< data } +fn resource_initiator_anchor<'s>( + scope: &mut v8::PinScope<'s, '_>, +) -> Option> { + let data = + v8::Local::::try_from(scope.get_continuation_preserved_embedder_data()).ok()?; + v8::Local::::try_from(get_private_value(scope, data, RESOURCE_INITIATOR_SLOT)?).ok() +} + +pub(crate) fn resource_initiator(scope: &mut v8::PinScope<'_, '_>) -> Option { + let anchor = resource_initiator_anchor(scope)?; + let value = get_private_value(scope, anchor, RESOURCE_INITIATOR_STATE_SLOT)?; + let external = v8::Local::::try_from(value).ok()?; + // The private anchor owns this allocation until its V8 finalizer runs. + Some(unsafe { &*external.value().cast::() }.clone()) +} + +pub(crate) fn with_resource_initiator<'s>( + scope: &mut v8::PinScope<'s, '_>, + initiator: ResourceInitiator, +) -> v8::Local<'s, v8::Value> { + let base_url = base_url_value(scope); + let window = window_anchor(scope); + let anchor = v8::Object::new(scope); + let mut initiator = Box::new(initiator); + let pointer = (&mut *initiator as *mut ResourceInitiator).cast(); + let external = v8::External::new(scope, pointer); + set_private_value( + scope, + anchor, + RESOURCE_INITIATOR_STATE_SLOT, + external.into(), + ); + crate::v8_finalizer::track_context_owned_v8_finalizer(scope, anchor, move || drop(initiator)); + data_with_parts(scope, base_url, window, Some(anchor)) +} + fn window_anchor<'s>(scope: &mut v8::PinScope<'s, '_>) -> Option> { let data = v8::Local::::try_from(scope.get_continuation_preserved_embedder_data()).ok()?; @@ -60,14 +108,23 @@ pub(crate) fn running_window<'s>( (owner.identity.realm_token() == *token).then_some(owner) } -fn data_with_window<'s>( +fn data_with_parts<'s>( scope: &mut v8::PinScope<'s, '_>, base_url: v8::Local<'s, v8::Value>, - anchor: v8::Local<'s, v8::Object>, + window: Option>, + resource_initiator: Option>, ) -> v8::Local<'s, v8::Value> { + if window.is_none() && resource_initiator.is_none() { + return base_url; + } let data = v8::Object::new(scope); set_private_value(scope, data, BASE_URL_SLOT, base_url); - set_private_value(scope, data, WINDOW_SLOT, anchor.into()); + if let Some(anchor) = window { + set_private_value(scope, data, WINDOW_SLOT, anchor.into()); + } + if let Some(anchor) = resource_initiator { + set_private_value(scope, data, RESOURCE_INITIATOR_SLOT, anchor.into()); + } data.into() } @@ -75,10 +132,9 @@ pub(crate) fn with_base_url<'s>( scope: &mut v8::PinScope<'s, '_>, base_url: v8::Local<'s, v8::Value>, ) -> v8::Local<'s, v8::Value> { - match window_anchor(scope) { - Some(anchor) => data_with_window(scope, base_url, anchor), - None => base_url, - } + let window = window_anchor(scope); + let initiator = resource_initiator_anchor(scope); + data_with_parts(scope, base_url, window, initiator) } pub(crate) fn with_window<'s>( @@ -89,11 +145,12 @@ pub(crate) fn with_window<'s>( return scope.get_continuation_preserved_embedder_data(); } let base_url = base_url_value(scope); + let initiator = resource_initiator_anchor(scope); let anchor = v8::Object::new(scope); let mut owner = Box::new(owner); let pointer = (&mut *owner as *mut WindowContinuation).cast(); let external = v8::External::new(scope, pointer); set_private_value(scope, anchor, WINDOW_STATE_SLOT, external.into()); crate::v8_finalizer::track_context_owned_v8_finalizer(scope, anchor, move || drop(owner)); - data_with_window(scope, base_url, anchor) + data_with_parts(scope, base_url, Some(anchor), initiator) } diff --git a/moli-renderer-v8/src/script_vm/eval_exec.rs b/moli-renderer-v8/src/script_vm/eval_exec.rs index a451a14255b..2502c4f72e5 100644 --- a/moli-renderer-v8/src/script_vm/eval_exec.rs +++ b/moli-renderer-v8/src/script_vm/eval_exec.rs @@ -274,6 +274,19 @@ fn run_source_text_on_current_stack_with_completion( { scope.set_continuation_preserved_embedder_data(value); } + if let Some(provenance) = provenance + && crate::script_continuation::resource_initiator(&mut scope).is_none() + { + let origin = context_host_ptr_from_global_bridge(&mut scope) + .and_then(|host| unsafe { &mut *host }.window_origin_key_for_current_realm(&mut scope)); + let source_url = (!script_fetch_metadata.is_some_and(|metadata| metadata.muted_errors)) + .then(|| provenance.source_url().clone()); + let data = crate::script_continuation::with_resource_initiator( + &mut scope, + crate::script_continuation::ResourceInitiator { source_url, origin }, + ); + scope.set_continuation_preserved_embedder_data(data); + } let watchdog = V8ExecutionWatchdog::arm( V8ExecutionWatchdogKind::ScriptTurn, scope.thread_safe_handle(), diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs index 9ce1f993f1d..72651fed694 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs @@ -444,6 +444,11 @@ impl ScriptVm { network_error_text: Option, completion_result: AsyncSubresourceFetchResult, ) -> Result { + if skip_fetch_security_validation + && let Some(timing) = pending.continuation.window_resource_timing_mut() + { + timing.clear_initiator(); + } let consumed_preload = match &completion_result { AsyncSubresourceFetchResult::PreloadFailure(_) => true, AsyncSubresourceFetchResult::Response(response) diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs index 737206679b6..87603b50a35 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs @@ -126,7 +126,7 @@ impl ScriptVm { result: std::result::Result, ) -> Result { let RunningSubresourceFetchState { - pending, + mut pending, request_url, request_method, request_headers, @@ -135,6 +135,11 @@ impl ScriptVm { handle_auth_requests, initial_auth_network_request_headers, } = running; + if skip_fetch_security_validation + && let Some(timing) = pending.continuation.window_resource_timing_mut() + { + timing.clear_initiator(); + } let internal_id = pending.info.internal_id; let resource_type = pending.info.resource_type; let trace_started = moli_trace::cdp_runtime_trace_enabled().then(Instant::now); @@ -906,6 +911,9 @@ impl ScriptVm { return Ok(AsyncSubresourceFetchBodyActivity::NoWindowRealmEntered); }; if let Some(timing) = pending.continuation.window_resource_timing_mut() { + if started.skip_fetch_security_validation { + timing.clear_initiator(); + } timing.response_started(); if let Some(native) = pending.load.response_timing() { timing.observe_native_timing(native); diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs index 8444f736eb9..d7d9233826e 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs @@ -294,6 +294,7 @@ fn pending_fetch_continuation<'s>( .expect("test Fetch should capture its CSP report context"), moli_fetch::RequestRedirectMode::Follow, String::new(), + crate::context_bootstrap::FetchResourceTiming::new(), ), ) } @@ -3521,6 +3522,9 @@ async fn streaming_subresource_finish_preserves_response_head_cache_state() { v8::Global::new(scope, xhr), false, csp, + crate::context_bootstrap::FetchResourceTiming::for_initiator_type( + "xmlhttprequest", + ), ), load: crate::network::loads::resource_load_lease_for_test( load_client, @@ -4773,6 +4777,9 @@ async fn streaming_xhr_materialization_failure_errors_body_source_before_close() v8::Global::new(scope, xhr), false, csp, + crate::context_bootstrap::FetchResourceTiming::for_initiator_type( + "xmlhttprequest", + ), ), load: crate::network::loads::resource_load_lease_for_test( load_client, diff --git a/moli-renderer-v8/src/script_vm/tests/fetch_resource_timing.rs b/moli-renderer-v8/src/script_vm/tests/fetch_resource_timing.rs index 1408a6ccae0..f222aa6665f 100644 --- a/moli-renderer-v8/src/script_vm/tests/fetch_resource_timing.rs +++ b/moli-renderer-v8/src/script_vm/tests/fetch_resource_timing.rs @@ -277,6 +277,259 @@ async fn window_fetch_reports_native_resource_timing_at_body_terminal() { .await; } +#[test] +fn resource_timing_initiator_retains_the_triggering_script_until_publication() { + let mut vm = new_storage_test_vm("https://resource-initiator.test/page.html"); + vm.set_fetch_subresource_interception(true, Some(crate::types::SubresourceResourceType::Xhr)); + for (url, source) in [ + ( + "https://resource-initiator.test/library.js", + "function requestFromLibrary() { const xhr = new XMLHttpRequest(); xhr.open('GET', '/data'); xhr.send(); }", + ), + ( + "https://resource-initiator.test/caller.js", + "requestFromLibrary();", + ), + ( + "https://resource-initiator.test/later.js", + "globalThis.laterScriptExecuted = true;", + ), + ] { + vm.exec_in_enclosing_script_turn_with_provenance( + source, + &crate::script_provenance::CompiledStringProvenance::at_url(Url::parse(url).unwrap()), + 0, + None, + true, + ) + .map_err(|error| error.into_anyhow()) + .expect("the resource initiator scripts should execute"); + } + let requests = vm.take_pending_subresource_fetch_infos(); + assert_eq!(requests.len(), 1); + let request = &requests[0]; + vm.complete_async_subresource_fetch(crate::types::AsyncSubresourceFetchCompletion { + internal_id: request.internal_id, + request_url: request.url.clone(), + request_method: "GET".to_owned(), + request_headers: Default::default(), + request_body: None, + response_status_text: None, + skip_fetch_security_validation: false, + response_filter: None, + network_error_text: None, + result: Ok(crate::types::NavigationResponse::from_text_body( + request.url.clone(), + 200, + vec![("content-type".to_owned(), b"text/plain".to_vec())], + "body".to_owned(), + )) + .into(), + }) + .expect("the initiating request should complete"); + assert_eq!( + vm.eval("String(performance.getEntriesByType('resource')[0].initiatorUrl)") + .unwrap(), + "https://resource-initiator.test/caller.js", + "resource timing must capture the caller, not the callee or publication-time script" + ); + assert_eq!( + vm.eval("performance.getEntriesByType('resource')[0].toJSON().initiatorUrl") + .unwrap(), + "https://resource-initiator.test/caller.js" + ); +} + +#[test] +fn resource_timing_initiator_survives_promises_and_keeps_its_source_url() { + let mut vm = new_storage_test_vm("https://resource-initiator.test/page.html"); + vm.set_fetch_subresource_interception(true, Some(crate::types::SubresourceResourceType::Fetch)); + vm.exec_in_enclosing_script_turn_with_provenance( + "new Promise(resolve => { globalThis.releaseInitiator = resolve; }).then(async () => { await new Promise(resolve => queueMicrotask(resolve)); return fetch('/data'); });", + &crate::script_provenance::CompiledStringProvenance::new( + Url::parse("https://resource-initiator.test/caller.js").unwrap(), + Url::parse("https://resolution-base.test/different/").unwrap(), + ), + 0, None, true, + ).map_err(|error| error.into_anyhow()).unwrap(); + assert!(vm.take_pending_subresource_fetch_infos().is_empty()); + vm.exec_in_enclosing_script_turn_with_provenance( + "releaseInitiator();", + &crate::script_provenance::CompiledStringProvenance::at_url( + Url::parse("https://resource-initiator.test/later.js").unwrap(), + ), + 0, + None, + true, + ) + .map_err(|error| error.into_anyhow()) + .unwrap(); + let requests = vm.take_pending_subresource_fetch_infos(); + assert_eq!(requests.len(), 1); + let request = &requests[0]; + assert_eq!(request.url.as_str(), "https://resource-initiator.test/data"); + vm.complete_async_subresource_fetch(crate::types::AsyncSubresourceFetchCompletion { + internal_id: request.internal_id, + request_url: request.url.clone(), + request_method: "GET".to_owned(), + request_headers: Default::default(), + request_body: None, + response_status_text: None, + skip_fetch_security_validation: false, + response_filter: None, + network_error_text: None, + result: Ok(crate::types::NavigationResponse::from_text_body( + request.url.clone(), + 200, + vec![("content-type".to_owned(), b"text/plain".to_vec())], + "body".to_owned(), + )) + .into(), + }) + .unwrap(); + assert_eq!( + vm.eval("performance.getEntriesByType('resource')[0].initiatorUrl") + .unwrap(), + "https://resource-initiator.test/caller.js", + ); + assert_eq!( + vm.eval( + r#"(() => { + const entry = performance.getEntriesByType('resource')[0]; + Object.defineProperty(entry, 'initiatorUrl', {get() { throw Error('author getter'); }}); + return entry.toJSON().initiatorUrl; + })()"# + ) + .unwrap(), + "https://resource-initiator.test/caller.js" + ); +} + +#[test] +fn resource_timing_initiator_requires_a_known_source_and_readable_network_response() { + for streaming in [false, true] { + for scenario in [ + "same", + "cors", + "opaque-tao", + "cache", + "synthetic", + "muted", + "unknown", + ] { + let mut vm = new_storage_test_vm("https://resource-initiator.test/page.html"); + vm.set_fetch_subresource_interception( + true, + Some(crate::types::SubresourceResourceType::Fetch), + ); + let target = if matches!(scenario, "cors" | "opaque-tao") { + "https://other-initiator.test/data" + } else { + "https://resource-initiator.test/data" + }; + let mode = if scenario == "opaque-tao" { + "no-cors" + } else { + "cors" + }; + let source = + format!("fetch('{target}', {{mode: '{mode}'}}).then(response => response.text());"); + if scenario == "unknown" { + vm.eval(&source).unwrap(); + } else { + let metadata = crate::planning::ScriptFetchMetadata { + muted_errors: scenario == "muted", + ..Default::default() + }; + vm.exec_in_enclosing_script_turn_with_provenance( + &source, + &crate::script_provenance::CompiledStringProvenance::at_url( + Url::parse("https://resource-initiator.test/caller.js").unwrap(), + ), + 0, + Some(&metadata), + true, + ) + .map_err(|error| error.into_anyhow()) + .unwrap(); + } + let requests = vm.take_pending_subresource_fetch_infos(); + assert_eq!(requests.len(), 1, "{scenario}, streaming={streaming}"); + let request = &requests[0]; + let mut headers = vec![("content-type".to_owned(), b"text/plain".to_vec())]; + if scenario == "cors" { + headers.push(("access-control-allow-origin".to_owned(), b"*".to_vec())); + } + if scenario == "opaque-tao" { + headers.push(("timing-allow-origin".to_owned(), b"*".to_vec())); + } + let mut response = crate::types::NavigationResponse::from_text_body( + request.url.clone(), + 200, + headers, + "body".to_owned(), + ); + if scenario == "cache" { + response.from_cache = true; + response.cache_state = moli_fetch::ResponseCacheState::Local; + } + let synthetic = scenario == "synthetic"; + if streaming { + let body_source_id = crate::network_host::new_network_body_source_id(); + vm.start_streaming_async_subresource_fetch( + crate::types::AsyncSubresourceStreamingStarted { + internal_id: request.internal_id, + request_url: request.url.clone(), + request_method: "GET".to_owned(), + request_headers: Default::default(), + request_body: None, + skip_fetch_security_validation: synthetic, + response_filter: None, + body_source_id, + head: response.head(), + network_request_headers: None, + }, + ) + .unwrap(); + vm.append_streaming_async_subresource_fetch_chunk(body_source_id, b"body".to_vec()); + vm.finish_streaming_async_subresource_fetch( + request.internal_id, + body_source_id, + Ok(()), + ) + .unwrap(); + } else { + vm.complete_async_subresource_fetch( + crate::types::AsyncSubresourceFetchCompletion { + internal_id: request.internal_id, + request_url: request.url.clone(), + request_method: "GET".to_owned(), + request_headers: Default::default(), + request_body: None, + response_status_text: None, + skip_fetch_security_validation: synthetic, + response_filter: None, + network_error_text: None, + result: Ok(response).into(), + }, + ) + .unwrap(); + } + let expected = if matches!(scenario, "same" | "cors") { + "https://resource-initiator.test/caller.js" + } else { + "" + }; + assert_eq!( + vm.eval("performance.getEntriesByType('resource')[0].initiatorUrl") + .unwrap(), + expected, + "{scenario}, streaming={streaming}", + ); + } + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 32)] async fn resource_connection_phases_survive_lazy_realms_and_native_json() { run_resource_timing_fixture( diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index 7d080d05db9..9a32360ecd3 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -361,6 +361,7 @@ fn register_pending_window_fetch_for_test( request_cookie_report: None, }, false, + scope, ) .expect("test Fetch should be admitted"); @@ -532,6 +533,7 @@ fn register_pending_window_fetch_with_connect_policy_for_test( request_cookie_report: None, }, false, + scope, ) .expect("test Fetch should be admitted"); ( diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs index 363290bac88..2e1365ef499 100644 --- a/moli-renderer-v8/src/types.rs +++ b/moli-renderer-v8/src/types.rs @@ -265,14 +265,13 @@ impl PendingSubresourceContinuation { xhr: v8::Global, use_cors_preflight: bool, csp: crate::network_host::WindowCspRequestContext, + timing: crate::context_bootstrap::FetchResourceTiming, ) -> Self { Self::Xhr { xhr, use_cors_preflight, csp: Box::new(csp), - timing: Some( - crate::context_bootstrap::FetchResourceTiming::for_initiator_type("xmlhttprequest"), - ), + timing: Some(timing), } } @@ -401,11 +400,12 @@ impl PendingWindowFetchContinuation { csp_report_context: crate::network_host::WindowCspReportRequestContext, redirect_mode: moli_fetch::RequestRedirectMode, integrity: String, + timing: crate::context_bootstrap::FetchResourceTiming, ) -> Box { Box::new(Self { promise: PendingWindowFetchPromise::Active(resolver), upload: None, - timing: crate::context_bootstrap::FetchResourceTiming::new(), + timing, keepalive, redirect_csp_state: crate::network_host::FetchCspRedirectState::new(&connect_policy), connect_policy,