diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs index aa8aa2ba1cf..587714e65b7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs @@ -6,8 +6,10 @@ use crate::frame_owner_model::{ FrameDocumentLocalWindowTransition, FrameLocalWindowOwnerTransition, }; use crate::{ - document_runtime::DomHandle, dom::native::DocumentReadyState, + document_runtime::DomHandle, + dom::native::DocumentReadyState, frame_owner_model::FrameDocumentOwnerTransition, + native_bridge::{OwnerDispatchScope, WindowExecutionContextOwner}, }; use moli_web_mime::is_xml_document_mime; use url::Url; @@ -330,6 +332,22 @@ impl PageScriptHost { .expect("synthetic child Document commit requires its parent authority") .clone() }); + // A replacement can reuse the WindowProxy before deferred realm + // teardown. Finish the old timeline while its exact binding resolves. + if local_window_transition == FrameDocumentLocalWindowTransition::ReplaceLocalWindow + && let Some(owner) = expected_current_owner + && let Some(binding) = self.clone_window_execution_context_binding( + scope, + WindowExecutionContextOwner::Frame(owner.local_window_id), + OwnerDispatchScope::Child(handle), + ) + { + let host_ptr = self as *mut Self; + binding.with_current_scope(scope, host_ptr, |scope, _| { + unsafe { &mut *host_ptr } + .retire_beacon_timings_for_context(scope, binding.realm_token()); + }); + } let web_mcp_navigation = self.current_child_navigation_load(handle); let owner_transition = self .frame_owner_store 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 0b715683708..6331fc6cb78 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 @@ -18,6 +18,60 @@ use crate::{ }; impl PageScriptHost { + pub(crate) fn record_window_resource_timing( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + identity: super::WindowExecutionContextIdentity, + entry: crate::context_bootstrap::ResourcePerformanceEntry, + ) -> bool { + if !self.window_execution_context_identity_is_current(identity) { + return false; + } + let Some(binding) = self.clone_window_execution_context_binding( + scope, + identity.owner(), + identity.dispatch_scope(), + ) else { + return false; + }; + let host_ptr = self as *mut Self; + binding + .with_current_scope(scope, host_ptr, |scope, _| { + crate::context_bootstrap::record_resource_performance_entry(scope, entry); + }) + .is_some() + } + + /// Finish the old Window's public timing before its wrapper cache retires. + /// Transport leases remain alive and their terminal cannot report twice. + pub(crate) fn retire_beacon_timings_for_context( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + realm_token: super::RuntimeObservableContextToken, + ) { + let mut entries = Vec::new(); + self.for_each_subresource_fetch_state_mut(|pending| { + if pending + .execution_context + .window_network_only_identity() + .is_none_or(|identity| identity.realm_token() != realm_token) + { + return; + } + if let PendingSubresourceContinuation::Beacon(beacon) = &mut pending.continuation + && let Some(timing) = beacon.timing.take() + { + if let Some(native) = pending.load.response_timing() { + timing.observe_native_timing(native); + } + entries.push(timing.failed(&pending.info.url)); + } + }); + for entry in entries { + crate::context_bootstrap::record_resource_performance_entry(scope, entry); + } + } + pub(crate) fn record_document_resource_timing( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -861,7 +915,7 @@ impl PageScriptHost { request_mode, network_partition_key, policy_context, - continuation: PendingSubresourceContinuation::Fetch(Box::new( + continuation: PendingSubresourceContinuation::Fetch( crate::types::PendingWindowFetchContinuation::new( resolver, resource_timing, @@ -872,7 +926,7 @@ impl PageScriptHost { redirect_mode, integrity, ), - )), + ), deferred_request_started: defer_request_started, blob_url_entry: None, }, @@ -1398,14 +1452,25 @@ impl PageScriptHost { pub(crate) fn record_async_subresource_beacon( &mut self, execution_context: super::WindowExecutionContextIdentity, + beacon: crate::types::PendingBeacon, cancel_handle: Option, - network_partition_key: Option, mut info: PendingSubresourceFetchInfo, ) -> Option { - self.assign_pending_subresource_fetch_identity(&mut info); - let internal_id = info.internal_id; - let (load, request_origin) = self.register_document_resource_load_for_dispatch_scope( - execution_context.dispatch_scope(), + let target = beacon.report_context.identity(); + if target.dispatch_scope() != execution_context.dispatch_scope() + || !self.window_execution_context_owner_is_current( + execution_context.owner(), + execution_context.dispatch_scope(), + ) + || !self.window_document_owner_is_current_for_dispatch_scope( + target.owner(), + target.dispatch_scope(), + ) + { + return None; + } + let (load, request_origin) = self.register_document_resource_load( + target.owner(), info.resource_type, ResourceLoadDisposition::Keepalive { body_bytes: info @@ -1413,8 +1478,10 @@ impl PageScriptHost { .as_ref() .map_or(0, bytes::Bytes::len), }, - cancel_handle.clone(), + cancel_handle, )?; + self.assign_pending_subresource_fetch_identity(&mut info); + let internal_id = info.internal_id; self.record_pending_subresource_request_started(&info, load.disposition()); self.pending_subresource_fetches.insert( internal_id, @@ -1427,11 +1494,11 @@ impl PageScriptHost { execution_context: PendingSubresourceExecutionContext::window_network_only( execution_context, ), - credentials_mode: moli_fetch::RequestCredentialsMode::Include, - request_mode: moli_fetch::RequestMode::NoCors, - network_partition_key, - policy_context: Default::default(), - continuation: PendingSubresourceContinuation::Beacon, + credentials_mode: beacon.request.credentials_mode, + request_mode: beacon.request.request_mode, + network_partition_key: beacon.request.network_partition_key().map(str::to_owned), + policy_context: beacon.policy_context, + continuation: PendingSubresourceContinuation::Beacon(Box::new(beacon)), deferred_request_started: false, blob_url_entry: None, }, @@ -1488,50 +1555,6 @@ impl PageScriptHost { internal_id } - pub(crate) fn record_pending_subresource_beacon( - &mut self, - execution_context: super::WindowExecutionContextIdentity, - network_partition_key: Option, - mut info: PendingSubresourceFetchInfo, - ) -> Option { - self.assign_pending_subresource_fetch_identity(&mut info); - let internal_id = info.internal_id; - let (load, request_origin) = self.register_document_resource_load_for_dispatch_scope( - execution_context.dispatch_scope(), - info.resource_type, - ResourceLoadDisposition::Keepalive { - body_bytes: info - .request_body_bytes - .as_ref() - .map_or(0, bytes::Bytes::len), - }, - None, - )?; - self.push_pending_subresource_fetch_info(info.clone()); - self.pending_subresource_fetches.insert( - internal_id, - PendingSubresourceFetchState { - dispatch: None, - redirect_headers: None, - request_origin, - info, - load, - execution_context: PendingSubresourceExecutionContext::window_network_only( - execution_context, - ), - credentials_mode: moli_fetch::RequestCredentialsMode::Include, - request_mode: moli_fetch::RequestMode::NoCors, - network_partition_key, - policy_context: Default::default(), - continuation: PendingSubresourceContinuation::Beacon, - deferred_request_started: false, - blob_url_entry: None, - }, - ); - self.note_subresource_activity(); - Some(internal_id) - } - #[allow(clippy::too_many_arguments)] pub(crate) fn record_pending_subresource_csp_report( &mut self, @@ -2944,7 +2967,10 @@ impl PageScriptHost { let mut pending = self .subresource_fetch_states() .filter(|pending| { - matches!(pending.continuation, PendingSubresourceContinuation::Beacon) + matches!( + pending.continuation, + PendingSubresourceContinuation::Beacon(_) + ) }) .filter_map(|pending| { Some(( diff --git a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs index 54cfe0cb4dc..c7dc801edfa 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs @@ -1523,6 +1523,7 @@ fn image_submitter_coordinate_component(value: f64, max: f64) -> u32 { } fn send_anchor_ping_requests( + scope: &mut v8::PinScope<'_, '_>, runtime_ptr: *mut PageScriptHost, handle: DomHandle, destination_url: &str, @@ -1534,7 +1535,13 @@ fn send_anchor_ping_requests( .split_ascii_whitespace() .filter_map(|raw_url| base_url.join(raw_url).ok()) { - crate::network_host::send_link_audit_ping(runtime_ptr, handle, ping_url, destination_url); + crate::network_host::send_link_audit_ping( + scope, + runtime_ptr, + handle, + ping_url, + destination_url, + ); } } @@ -1646,7 +1653,7 @@ fn anchor_click_default_action( pending_child_navigations_before_default: &[(DomHandle, ChildBrowsingContextBootstrap)], ) -> Option { let resolved = parsed_hyperlink_url(unsafe { &*runtime_ptr }, handle)?.to_string(); - send_anchor_ping_requests(runtime_ptr, handle, &resolved); + send_anchor_ping_requests(scope, runtime_ptr, handle, &resolved); let runtime = unsafe { &*runtime_ptr }; if has_reflected_attribute(runtime, handle, "download") { let suggested_filename = diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs index d3762d538eb..83632a25e9f 100644 --- a/moli-renderer-v8/src/native_bridge/identity.rs +++ b/moli-renderer-v8/src/native_bridge/identity.rs @@ -776,6 +776,11 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown( include_shared_default_world: bool, ) { let context = scope.get_current_context(); + if let Some(host) = crate::util::context_host_ptr_from_context_slot(context) + && let Some(realm_token) = context.get_slot::() + { + unsafe { &mut *host }.retire_beacon_timings_for_context(scope, *realm_token); + } let _ = context.set_slot(Rc::new(RetiredWrapperContext)); let _ = crate::context_bootstrap::retain_window_document_in_retired_realm(scope); crate::context_bootstrap::retire_idle_detectors_in_current_context(scope); diff --git a/moli-renderer-v8/src/network_host/beacon.rs b/moli-renderer-v8/src/network_host/beacon.rs index 78476f24202..d798b8cca29 100644 --- a/moli-renderer-v8/src/network_host/beacon.rs +++ b/moli-renderer-v8/src/network_host/beacon.rs @@ -68,22 +68,28 @@ pub(crate) fn navigator_send_beacon_callback<'s>( rv.set_bool(false); return; }; - let Some(request_context) = - window_ping_request_context_for_execution_context(host, execution_context) + let Some(document_target) = host + .current_window_document_task_target_for_dispatch_scope(execution_context.dispatch_scope()) else { - rv.set(v8::Boolean::new(scope, false).into()); + rv.set_bool(false); + return; + }; + let Some(request_context) = + window_ping_request_context(scope, host, execution_context, document_target) + else { + rv.set_bool(false); return; }; let WindowPingRequestContext { - execution_context, resource_loader, frame_id, document_url, base_url, request_origin, network_partition_key, - } = request_context; - let resolved_url = match resolve_context_url(&base_url, &raw_url, None) { + .. + } = &request_context; + let resolved_url = match resolve_context_url(base_url, &raw_url, None) { Ok(url) => url, Err(_) => { crate::util::throw_type_error(scope, "The URL argument is ill-formed or unsupported."); @@ -97,14 +103,21 @@ pub(crate) fn navigator_send_beacon_callback<'s>( let mut request_headers = Vec::new(); append_default_body_content_type(&mut request_headers, body_content_type.as_deref()); - request_headers = filter_headers_for_guard(&request_headers, HeadersGuard::RequestNoCors); + let request_mode = if body_content_type.as_ref().is_some_and(|content_type| { + !moli_fetch::is_cors_safelisted_request_header("Content-Type", content_type) + }) { + RequestMode::Cors + } else { + RequestMode::NoCors + }; + let preflight_request_headers = request_headers.clone(); let request_headers = merge_subresource_request_headers(host.extra_http_headers(), &request_headers); let request_body_text = request_body_text(&body); let request_cookie_report = observe_subresource_request_cookie_report( resource_loader.request_client(), - &document_url, - &request_origin, + document_url, + request_origin, &resolved_url, "POST", RequestCredentialsMode::Include, @@ -125,47 +138,14 @@ pub(crate) fn navigator_send_beacon_callback<'s>( request_cookie_report, }; - if host.should_intercept_subresource(SubresourceResourceType::Ping) { - let admitted = host - .record_pending_subresource_beacon( - execution_context, - network_partition_key.clone(), - info, - ) - .is_some(); - rv.set_bool(admitted); - return; - } - - if host.network_offline() { - record_beacon_failure(host, info, "Network emulation offline".to_owned()); - rv.set(v8::Boolean::new(scope, true).into()); - return; - } - if host.is_url_blocked(&resolved_url) { - record_beacon_failure(host, info, BLOCKED_BY_CLIENT_ERROR_TEXT.to_owned()); - rv.set(v8::Boolean::new(scope, true).into()); - return; - } - if should_request_be_blocked_due_to_bad_port(&resolved_url) { - record_beacon_failure( - host, - info, - format!("sendBeacon: blocked bad port for `{resolved_url}`"), - ); - rv.set(v8::Boolean::new(scope, true).into()); - return; - } - - let loader = resource_loader.request_client().clone(); let request = match Request::new_bytes("POST", resolved_url.as_str(), body, request_headers.clone()) { Ok(request) => request - .with_initiator_url(&document_url) + .with_initiator_url(document_url) .with_request_origin(request_origin.clone()) .with_resource_type(RequestResourceType::Beacon) .with_browser_request_metadata(moli_fetch::BrowserRequestMetadata::Beacon) - .with_request_mode(RequestMode::NoCors) + .with_request_mode(request_mode) .with_credentials_mode(RequestCredentialsMode::Include) .with_network_partition_key(network_partition_key.clone()) .with_redirect_mode(RequestRedirectMode::Follow) @@ -175,41 +155,32 @@ pub(crate) fn navigator_send_beacon_callback<'s>( return; } }; - let cancel_handle = FetchCancelHandle::new(); - let network_context = AsyncSubresourceNetworkContext { - frame_id: info.frame_id.clone(), - request_origin: request_origin.clone(), - document_url: info.document_url.clone(), - resource_type: info.resource_type, - policy_context: Default::default(), + let request = match request + .with_subresource_request_metadata(moli_fetch::SubresourceRequestMetadata { + document_referrer_policy: request_context.referrer_policy.clone(), + ..Default::default() + }) + .with_fetch_referrer(&request_context.referrer_for(&resolved_url)) + { + Ok(request) => request, + Err(error) => { + crate::util::throw_type_error(scope, &error.to_string()); + return; + } }; - let Some(internal_id) = host.record_async_subresource_beacon( - execution_context, - Some(cancel_handle.clone()), - network_partition_key, - info, - ) else { - rv.set_bool(false); - return; - }; - spawn_async_subresource_fetch( - resource_loader.task_runner(), - host.resource_completion_sender(), - loader, + rv.set_bool(start_window_ping( + scope, + host, + &request_context, request, - Some(cancel_handle), - Vec::new(), - internal_id, - network_context, - resolved_url, - "POST".to_owned(), - request_headers, - request_body_text, - ); - rv.set(v8::Boolean::new(scope, true).into()); + info, + preflight_request_headers, + "beacon", + )); } pub(crate) fn send_link_audit_ping( + scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, link: crate::document_runtime::DomHandle, ping_url: url::Url, @@ -226,26 +197,30 @@ pub(crate) fn send_link_audit_ping( else { return; }; + let Some(document_target) = host + .current_window_document_task_target_for_dispatch_scope(execution_context.dispatch_scope()) + else { + return; + }; let Some(request_context) = - window_ping_request_context_for_execution_context(host, execution_context) + window_ping_request_context(scope, host, execution_context, document_target) else { return; }; let WindowPingRequestContext { - execution_context, resource_loader, frame_id, document_url, - base_url: _, request_origin, network_partition_key, - } = request_context; + .. + } = &request_context; let mut request_headers = vec![ ("Content-Type".to_owned(), "text/ping".to_owned()), ("Cache-Control".to_owned(), "max-age=0".to_owned()), ("Ping-To".to_owned(), destination_url.to_owned()), ]; - if document_url.scheme() == "http" || moli_url::same_origin(&document_url, &ping_url) { + if document_url.scheme() == "http" || moli_url::same_origin(document_url, &ping_url) { request_headers.push(("Ping-From".to_owned(), document_url.as_str().to_owned())); } let request_headers = @@ -253,8 +228,8 @@ pub(crate) fn send_link_audit_ping( let request_body = Some("PING".to_owned()); let request_cookie_report = observe_subresource_request_cookie_report( resource_loader.request_client(), - &document_url, - &request_origin, + document_url, + request_origin, &ping_url, "POST", RequestCredentialsMode::Include, @@ -277,33 +252,6 @@ pub(crate) fn send_link_audit_ping( request_cookie_report, }; - if host.should_intercept_subresource(SubresourceResourceType::Ping) { - let _ = host.record_pending_subresource_beacon( - execution_context, - network_partition_key.clone(), - info, - ); - return; - } - - if host.network_offline() { - record_beacon_failure(host, info, "Network emulation offline".to_owned()); - return; - } - if host.is_url_blocked(&ping_url) { - record_beacon_failure(host, info, BLOCKED_BY_CLIENT_ERROR_TEXT.to_owned()); - return; - } - if should_request_be_blocked_due_to_bad_port(&ping_url) { - record_beacon_failure( - host, - info, - format!("ping: blocked bad port for `{ping_url}`"), - ); - return; - } - - let loader = resource_loader.request_client().clone(); let request = match Request::new_bytes( "POST", ping_url.as_str(), @@ -311,8 +259,8 @@ pub(crate) fn send_link_audit_ping( request_headers.clone(), ) { Ok(request) => request + .with_initiator_url(document_url) .without_inferred_referrer() - .with_initiator_url(&document_url) .with_request_origin(request_origin.clone()) .with_resource_type(RequestResourceType::Ping) .with_browser_request_metadata(moli_fetch::BrowserRequestMetadata::Ping) @@ -326,40 +274,23 @@ pub(crate) fn send_link_audit_ping( return; } }; - let cancel_handle = FetchCancelHandle::new(); - let network_context = AsyncSubresourceNetworkContext { - frame_id: info.frame_id.clone(), - request_origin: request_origin.clone(), - document_url: info.document_url.clone(), - resource_type: info.resource_type, - policy_context: Default::default(), - }; - let Some(internal_id) = host.record_async_subresource_beacon( - execution_context, - Some(cancel_handle.clone()), - network_partition_key, - info, - ) else { - return; - }; - spawn_async_subresource_fetch( - resource_loader.task_runner(), - host.resource_completion_sender(), - loader, + let _ = start_window_ping( + scope, + host, + &request_context, request, - Some(cancel_handle), + info, Vec::new(), - internal_id, - network_context, - ping_url, - "POST".to_owned(), - request_headers, - request_body, + "ping", ); } struct WindowPingRequestContext { execution_context: crate::native_bridge::WindowExecutionContextIdentity, + document_target: crate::native_bridge::WindowDocumentTaskTarget, + policy_context: crate::types::SubresourcePolicyContext, + referrer_policy: Option, + referrer_source: Option, resource_loader: crate::network::context::DocumentResourceLoader, frame_id: Option, document_url: url::Url, @@ -368,14 +299,20 @@ struct WindowPingRequestContext { network_partition_key: Option, } -fn window_ping_request_context_for_execution_context( +fn window_ping_request_context( + scope: &mut v8::PinScope<'_, '_>, host: &PageScriptHost, execution_context: crate::native_bridge::WindowExecutionContextIdentity, + document_target: crate::native_bridge::WindowDocumentTaskTarget, ) -> Option { let owner = execution_context.dispatch_scope(); - let resource_loader = host - .document_resource_loader_for_dispatch_scope(owner)? - .clone(); + if !host.window_execution_context_owner_is_current(execution_context.owner(), owner) + || !host.window_document_owner_is_current_for_dispatch_scope(document_target.owner(), owner) + { + return None; + } + let resource_loader = + host.document_resource_loader_for_window_owner(document_target.owner())?; let environment = host.subresource_request_environment(&resource_loader, owner)?; let crate::network::context::SubresourceRequestEnvironment { document_url, @@ -385,6 +322,10 @@ fn window_ping_request_context_for_execution_context( } = environment; Some(WindowPingRequestContext { execution_context, + document_target, + policy_context: effective_subresource_policy_context(scope, host, owner), + referrer_policy: effective_subresource_referrer_policy(host, owner), + referrer_source: host.document_client_referrer_source(owner), resource_loader, frame_id, document_url, @@ -394,6 +335,161 @@ fn window_ping_request_context_for_execution_context( }) } +impl WindowPingRequestContext { + fn referrer_for(&self, url: &url::Url) -> String { + self.referrer_source + .as_ref() + .and_then(|source| { + moli_fetch::referrer_value(source, url, self.referrer_policy.as_deref(), None) + }) + .unwrap_or_default() + } +} + +fn start_window_ping( + scope: &mut v8::PinScope<'_, '_>, + host: &mut PageScriptHost, + context: &WindowPingRequestContext, + mut request: Request, + info: PendingSubresourceFetchInfo, + preflight_request_headers: Vec<(String, String)>, + initiator_type: &'static str, +) -> bool { + let owner = context.execution_context.dispatch_scope(); + let Some(policy) = host.document_connect_policy_snapshot_for_owner(owner) else { + return false; + }; + let Some(report_context) = capture_window_csp_report_request_context(scope, host, owner) else { + return false; + }; + if report_context.identity() != context.document_target { + return false; + } + let (reports, enforced) = policy + .check_url( + &context.document_url, + &request.url, + crate::content_security_policy::ContentSecurityPolicyRedirectStatus::NoRedirect, + ) + .into_violations(); + let policy_error = enforced.first().map(|violation| { + crate::document_runtime::document_content_security_policy_error_message( + violation, + initiator_type, + ) + }); + let host_ptr = host as *mut PageScriptHost; + for violation in reports.into_iter().chain(enforced) { + send_content_security_policy_violation_report_from_window_context( + host, + &report_context, + &violation, + ); + host.dispatch_document_connect_csp_violation_event_for_exact_owner_without_report_best_effort( + scope, host_ptr, context.document_target, &violation, + ); + } + if let Some(error) = policy_error { + // Blink's Beacon path stops before constructing a ResourceRequest. + // Hyperlink auditing instead exposes a failed ping timing, even when + // the keepalive quota is already full. Neither reaches transport. + if request.resource_type == RequestResourceType::Ping { + let timing = crate::context_bootstrap::FetchResourceTiming::capture_for_initiator_type( + scope, + &context.request_origin, + "ping", + ); + host.record_window_resource_timing( + scope, + context.execution_context, + timing.failed(&info.url), + ); + record_beacon_failure(host, info, error); + } + return true; + } + let beacon = crate::types::PendingBeacon { + request: request.clone(), + policy_context: context.policy_context, + redirect_state: FetchCspRedirectState::new(&policy), + policy, + report_context, + timing: Some( + crate::context_bootstrap::FetchResourceTiming::capture_for_initiator_type( + scope, + &context.request_origin, + initiator_type, + ), + ), + }; + let cancel_handle = FetchCancelHandle::new(); + let Some(internal_id) = host.record_async_subresource_beacon( + context.execution_context, + beacon, + Some(cancel_handle.clone()), + info.clone(), + ) else { + return false; + }; + let error = if host.network_offline() { + Some("Network emulation offline".to_owned()) + } else if host.is_url_blocked(&request.url) { + Some(BLOCKED_BY_CLIENT_ERROR_TEXT.to_owned()) + } else if should_request_be_blocked_due_to_bad_port(&request.url) { + Some(format!( + "{initiator_type}: blocked bad port for `{}`", + request.url + )) + } else { + None + }; + if let Some(error) = error { + let _ = host.resource_completion_sender().send_async_subresource( + crate::types::AsyncSubresourceFetchCompletion { + internal_id, + request_url: request.url, + request_method: request.method, + request_headers: request.request_headers, + request_body: info.request_body, + response_status_text: None, + skip_fetch_security_validation: false, + response_filter: None, + network_error_text: None, + result: Err(error).into(), + }, + ); + return true; + } + if host.should_intercept_subresource(SubresourceResourceType::Ping) { + host.pause_pending_subresource_fetch(internal_id); + return true; + } + if let Some(check) = host.window_fetch_redirect_check(internal_id) { + request = request.with_redirect_check(check); + } + spawn_async_subresource_fetch( + context.resource_loader.task_runner(), + host.resource_completion_sender(), + context.resource_loader.request_client().clone(), + request, + Some(cancel_handle), + preflight_request_headers, + internal_id, + AsyncSubresourceNetworkContext { + frame_id: info.frame_id, + request_origin: context.request_origin.clone(), + document_url: info.document_url, + resource_type: info.resource_type, + policy_context: context.policy_context, + }, + info.url, + info.method, + info.request_headers, + info.request_body, + ); + true +} + fn navigator_beacon_body<'s>( scope: &mut v8::PinScope<'s, '_>, args: &v8::FunctionCallbackArguments<'s>, diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch.rs index f6e2405a04b..a874a8b07e6 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch.rs @@ -12,6 +12,7 @@ use { crate::types::{PendingSubresourceAuthResponse, PendingSubresourceResponseDetails}, }; +mod beacon; mod document_completion; mod fetch_dispatch; mod intercepted_fetch; @@ -209,10 +210,17 @@ fn detached_window_fetch_csp_redirect_failure_message( if redirect_state.was_checked(final_url) { return None; } - let redirect_status = ContentSecurityPolicyRedirectStatus::FollowedRedirect; - if let Some(mut violation) = - policy.report_only_violation(&pending.info.document_url, final_url, redirect_status) - { + let (reports, enforced) = policy + .check_url( + &pending.info.document_url, + final_url, + ContentSecurityPolicyRedirectStatus::FollowedRedirect, + ) + .into_violations(); + let error = enforced.first().map(|violation| { + crate::document_runtime::document_content_security_policy_error_message(violation, "fetch") + }); + for mut violation in reports.into_iter().chain(enforced) { violation.blocked_uri = crate::content_security_policy::csp_url_for_report(&pending.info.url); crate::content_security_policy::ContentSecurityPolicySourceLocation::default() @@ -223,21 +231,7 @@ fn detached_window_fetch_csp_redirect_failure_message( &violation, ); } - let mut violation = - policy.enforce_violation(&pending.info.document_url, final_url, redirect_status)?; - violation.blocked_uri = crate::content_security_policy::csp_url_for_report(&pending.info.url); - crate::content_security_policy::ContentSecurityPolicySourceLocation::default() - .apply_to(&mut violation); - crate::network_host::send_content_security_policy_violation_report_from_window_context( - &mut context_host.borrow_mut(), - report_context, - &violation, - ); - Some( - crate::document_runtime::document_content_security_policy_error_message( - &violation, "fetch", - ), - ) + error } enum MediaSubresourceTerminal<'a> { @@ -690,7 +684,7 @@ fn pending_subresource_continuation_kind( PendingSubresourceContinuation::StylesheetSubresource { .. } => "stylesheet_subresource", PendingSubresourceContinuation::Dictionary(_) => "dictionary", PendingSubresourceContinuation::ResponsePreload(_) => "response_preload", - PendingSubresourceContinuation::Beacon => "beacon", + PendingSubresourceContinuation::Beacon(_) => "beacon", PendingSubresourceContinuation::CspReport { .. } => "csp_report", PendingSubresourceContinuation::Xhr { .. } => "xhr", PendingSubresourceContinuation::WebSocket(..) => "websocket", diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/beacon.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/beacon.rs new file mode 100644 index 00000000000..519a8884066 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/beacon.rs @@ -0,0 +1,58 @@ +use super::*; + +impl ScriptVm { + pub(super) fn complete_beacon_timing( + &mut self, + pending: &mut PendingSubresourceFetchState, + head: Option<&moli_fetch::ResponseHead>, + response_filter: Option<&crate::types::AsyncSubresourceFetchResponseFilter>, + body_size: usize, + ) -> Result { + let PendingSubresourceContinuation::Beacon(beacon) = &mut pending.continuation else { + return Ok(AsyncSubresourceFetchBodyActivity::NoWindowRealmEntered); + }; + let Some(timing) = beacon.timing.take() else { + return Ok(AsyncSubresourceFetchBodyActivity::NoWindowRealmEntered); + }; + if let Some(native) = pending.load.response_timing() { + timing.observe_native_timing(native); + } + let entry = if let Some(head) = head { + let filter = response_filter.cloned().unwrap_or_else(|| { + crate::network_host::FetchResponseRequest { + method: &pending.info.method, + mode: pending.request_mode, + redirect_mode: beacon.request.redirect_mode(), + } + .network_response_filter( + &pending.request_origin, + head, + pending.credentials_mode, + ) + }); + timing.completed( + &pending.info.url, + &pending.request_origin, + pending.request_mode, + head, + body_size, + Some(&filter), + ) + } else { + timing.failed(&pending.info.url) + }; + // document.open keeps the same Window timeline. Navigation retires + // that Window's timing separately while its transport may continue. + let Some(identity) = pending.execution_context.window_network_only_identity() else { + return Ok(AsyncSubresourceFetchBodyActivity::NoWindowRealmEntered); + }; + let entered = self.with_default_context_scope(|scope, host_ptr| { + Ok(unsafe { &mut *host_ptr }.record_window_resource_timing(scope, identity, entry)) + })?; + Ok(if entered { + AsyncSubresourceFetchBodyActivity::WindowRealmEntered + } else { + AsyncSubresourceFetchBodyActivity::NoWindowRealmEntered + }) + } +} 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 7b3a5abb373..5e8653dc2d8 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 @@ -29,6 +29,7 @@ impl ScriptVm { pending.continuation, PendingSubresourceContinuation::Dictionary(_) | PendingSubresourceContinuation::ResponsePreload(_) + | PendingSubresourceContinuation::Beacon(_) ) { result.and_then(|response| { if !response.redirect_chain.is_empty() @@ -63,12 +64,28 @@ impl ScriptVm { result }; - let activity = self.complete_response_preload( - &mut pending, - response_filter.as_ref(), - skip_fetch_security_validation, - &result, - )?; + let activity = if matches!( + pending.continuation, + PendingSubresourceContinuation::Beacon(_) + ) { + let head = result.as_ref().ok().map(|response| response.head()); + let body_size = result + .as_ref() + .map_or(0, |response| response.body_bytes().len()); + self.complete_beacon_timing( + &mut pending, + head.as_ref(), + response_filter.as_ref(), + body_size, + )? + } else { + self.complete_response_preload( + &mut pending, + response_filter.as_ref(), + skip_fetch_security_validation, + &result, + )? + }; match result { Ok(response) => { let network_request_headers = response @@ -1002,7 +1019,7 @@ impl ScriptVm { } PendingSubresourceContinuation::Dictionary(_) | PendingSubresourceContinuation::ResponsePreload(_) - | PendingSubresourceContinuation::Beacon + | PendingSubresourceContinuation::Beacon(_) | PendingSubresourceContinuation::CspReport { .. } | PendingSubresourceContinuation::EventSource(_) | PendingSubresourceContinuation::WebSocket(..) @@ -1136,7 +1153,7 @@ impl ScriptVm { } PendingSubresourceContinuation::Dictionary(_) | PendingSubresourceContinuation::ResponsePreload(_) - | PendingSubresourceContinuation::Beacon + | PendingSubresourceContinuation::Beacon(_) | PendingSubresourceContinuation::CspReport { .. } | PendingSubresourceContinuation::EventSource(_) | PendingSubresourceContinuation::WebSocket(..) diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs index 7330d69bac5..8d770d5ea90 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs @@ -40,6 +40,10 @@ pub(super) fn request_for_pending_subresource( .dispatch .as_ref() .map(|dispatch| &dispatch.request) + .or(match &pending.continuation { + PendingSubresourceContinuation::Beacon(beacon) => Some(&beacon.request), + _ => None, + }) .or_else(|| { pending .continuation 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 001dc67586c..8bebaf1da25 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs @@ -621,6 +621,7 @@ impl ScriptVm { || matches!( pending.continuation, PendingSubresourceContinuation::ResponsePreload(_) + | PendingSubresourceContinuation::Beacon(_) )) .then(|| { if !started.head.redirect_chain.is_empty() @@ -652,12 +653,24 @@ impl ScriptVm { .flatten(); if let Some(error_text) = security_error { - let activity = self.complete_response_preload( - &mut pending, - started.response_filter.as_ref(), - started.skip_fetch_security_validation, - &Err(error_text.clone()), - )?; + let activity = if matches!( + pending.continuation, + PendingSubresourceContinuation::Beacon(_) + ) { + self.complete_beacon_timing( + &mut pending, + None, + started.response_filter.as_ref(), + 0, + )? + } else { + self.complete_response_preload( + &mut pending, + started.response_filter.as_ref(), + started.skip_fetch_security_validation, + &Err(error_text.clone()), + )? + }; pending.load.cancel(); let mut network_record = crate::types::SubresourceNetworkRecord::failure( pending.info.frame_id.clone(), @@ -973,7 +986,7 @@ impl ScriptVm { } PendingSubresourceContinuation::Dictionary(_) | PendingSubresourceContinuation::ResponsePreload(_) - | PendingSubresourceContinuation::Beacon + | PendingSubresourceContinuation::Beacon(_) | PendingSubresourceContinuation::CspReport { .. } | PendingSubresourceContinuation::WebSocket(..) | PendingSubresourceContinuation::ChildDocument(_) => {} @@ -1298,7 +1311,7 @@ impl ScriptVm { } PendingSubresourceContinuation::Dictionary(_) | PendingSubresourceContinuation::ResponsePreload(_) - | PendingSubresourceContinuation::Beacon + | PendingSubresourceContinuation::Beacon(_) | PendingSubresourceContinuation::CspReport { .. } | PendingSubresourceContinuation::Xhr { .. } | PendingSubresourceContinuation::WebSocket(..) @@ -1605,6 +1618,16 @@ impl ScriptVm { } }); let activity = if matches!( + streaming.pending.continuation, + PendingSubresourceContinuation::Beacon(_) + ) { + self.complete_beacon_timing( + &mut streaming.pending, + Some(&streaming.head), + streaming.response_filter.as_ref(), + response_body.len(), + )? + } else if matches!( streaming.pending.continuation, PendingSubresourceContinuation::ResponsePreload(_) ) { diff --git a/moli-renderer-v8/src/script_vm/tests/beacon_request_policy.rs b/moli-renderer-v8/src/script_vm/tests/beacon_request_policy.rs new file mode 100644 index 00000000000..08476b4bbae --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/beacon_request_policy.rs @@ -0,0 +1,538 @@ +use super::*; +use crate::runtime::PageVmTaskExecutorTestHarness; + +fn beacon_url(server: &StaticHttpServer, path: &str) -> String { + server.base_url().join(path).unwrap().to_string() +} + +fn beacon_referrer_policy(vm: &mut PageVmTaskExecutorTestHarness, policy: &str) { + vm.eval(&format!( + "document.head.appendChild(Object.assign(document.createElement('meta'), {{name:'referrer',content:{policy:?}}}));true" + )).unwrap(); +} + +async fn finish_beacon_timing( + vm: &mut PageVmTaskExecutorTestHarness, + loader: &ResourceRequestClient, + url: &str, +) -> serde_json::Value { + advance_page_task_executor_until_eval_equals( + vm, + loader, + &format!("String(performance.getEntriesByName({url:?}).length)"), + "1", + "Beacon native resource timing at its transport terminal", + ) + .await; + serde_json::from_str(&vm.eval(&format!( + "JSON.stringify(performance.getEntriesByName({url:?}).map(entry=>[entry.initiatorType,entry.responseStatus]))" + )).unwrap()).unwrap() +} + +#[tokio::test(flavor = "current_thread")] +async fn beacon_cors_preserves_content_type_credentials_referrer_and_native_lifetime() { + let server = StaticHttpServer::spawn_with_responder( + 2, + "Content-Type: text/plain\r\nAccess-Control-Allow-Origin: http://beacon-source.test\r\nAccess-Control-Allow-Credentials: true\r\nAccess-Control-Allow-Methods: POST\r\nAccess-Control-Allow-Headers: content-type\r\n", + |_, _| "ok".to_owned(), + ).await; + let loader = static_http_loader(std::iter::empty::()); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "http://beacon-source.test/path?query=1", + &loader, + ); + beacon_referrer_policy(&mut vm, "origin"); + let url = beacon_url(&server, "/beacon"); + assert_eq!(vm.eval(&format!( + "String(navigator.sendBeacon({url:?}, new Blob(['payload'],{{type:'application/octet-stream'}})))" + )).unwrap(), "true"); + { + let host = vm._context_host.borrow(); + let pending = host.pending_window_beacon_execution_contexts_for_test(); + assert_eq!(pending.len(), 1); + assert!( + !pending[0].2, + "accepted Beacon must not retain its V8 context" + ); + assert!( + !host.has_pending_load_event_delaying_subresource_requests(), + "an accepted Beacon must not delay the Document's load event" + ); + } + assert_eq!( + finish_beacon_timing(&mut vm, &loader, &url).await, + serde_json::json!([["beacon", 200]]) + ); + let requests = server.finish().await; + assert_eq!(requests.len(), 2); + assert_eq!(requests[0].method, "OPTIONS"); + assert_eq!( + requests[0].header_value("access-control-request-headers"), + Some("content-type") + ); + assert_eq!(requests[1].method, "POST"); + assert_eq!(requests[1].body, b"payload"); + assert_eq!( + requests[1].header_value("content-type"), + Some("application/octet-stream") + ); + for request in requests { + assert_eq!( + request.header_value("origin"), + Some("http://beacon-source.test") + ); + assert_eq!( + request.header_value("referer"), + Some("http://beacon-source.test/") + ); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn beacon_preflight_requires_credential_permission_before_sending_body() { + let server = StaticHttpServer::spawn_with_responder( + 1, + "Content-Type: text/plain\r\nAccess-Control-Allow-Origin: http://beacon-source.test\r\nAccess-Control-Allow-Methods: POST\r\nAccess-Control-Allow-Headers: content-type\r\n", + |_, _| "ok".to_owned(), + ).await; + let loader = static_http_loader(std::iter::empty::()); + let mut vm = + new_storage_page_task_executor_test_vm_with_loader("http://beacon-source.test/", &loader); + let url = beacon_url(&server, "/no-credentials"); + assert_eq!(vm.eval(&format!( + "String(navigator.sendBeacon({url:?},new Blob(['private'],{{type:'application/json'}})))" + )).unwrap(), "true"); + assert_eq!( + finish_beacon_timing(&mut vm, &loader, &url).await, + serde_json::json!([["beacon", 0]]) + ); + let requests = server.finish().await; + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].method, "OPTIONS"); + assert!(requests[0].body.is_empty()); +} + +#[tokio::test(flavor = "current_thread")] +async fn beacon_interception_keeps_request_policy_across_document_open() { + let server = StaticHttpServer::spawn_with_responder( + 2, + "Content-Type: text/plain\r\nAccess-Control-Allow-Origin: http://beacon-source.test\r\nAccess-Control-Allow-Credentials: true\r\nAccess-Control-Allow-Methods: POST\r\nAccess-Control-Allow-Headers: content-type\r\n", + |_, _| "ok".to_owned(), + ).await; + let loader = static_http_loader(std::iter::empty::()); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "http://beacon-source.test/page", + &loader, + ); + beacon_referrer_policy(&mut vm, "no-referrer"); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + let url = beacon_url(&server, "/paused"); + assert_eq!(vm.eval(&format!( + "String(navigator.sendBeacon({url:?}, new Blob(['payload'],{{type:'application/json'}})))" + )).unwrap(), "true"); + let accepted = vm + ._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(); + assert_eq!(accepted.len(), 1); + assert!(!accepted[0].2); + vm.eval("document.open();document.write(\"\");document.close();true").unwrap(); + vm.set_fetch_subresource_interception(crate::types::SubresourceInterceptionClasses::NONE); + vm.continue_pending_subresource_fetch(accepted[0].0, None, None, None, None, false, false) + .unwrap(); + assert_eq!( + finish_beacon_timing(&mut vm, &loader, &url).await, + serde_json::json!([["beacon", 200]]) + ); + let requests = server.finish().await; + assert_eq!(requests.len(), 2); + assert_eq!(requests[0].method, "OPTIONS"); + assert_eq!(requests[1].method, "POST"); + assert_eq!(requests[1].body, b"payload"); + assert_eq!( + requests[1].header_value("content-type"), + Some("application/json") + ); + assert!( + requests + .iter() + .all(|request| request.header_value("referer").is_none()) + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn beacon_referrer_policy_uses_the_initiating_document() { + for policy in [ + "no-referrer", + "origin", + "strict-origin", + "same-origin", + "unsafe-url", + ] { + let server = + StaticHttpServer::spawn_with_responder(1, "Content-Type: text/plain\r\n", |_, _| { + "ok".to_owned() + }) + .await; + let loader = static_http_loader(std::iter::empty::()); + let document = beacon_url(&server, "/path/page?query=1#fragment"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(&document, &loader); + beacon_referrer_policy(&mut vm, policy); + let url = beacon_url(&server, "/beacon"); + assert_eq!( + vm.eval(&format!("String(navigator.sendBeacon({url:?},'payload'))")) + .unwrap(), + "true" + ); + assert_eq!( + finish_beacon_timing(&mut vm, &loader, &url).await, + serde_json::json!([["beacon", 200]]) + ); + let expected = match policy { + "no-referrer" => None, + "origin" | "strict-origin" => Some(server.base_url().to_string()), + _ => Some(document.trim_end_matches("#fragment").to_owned()), + }; + let requests = server.finish().await; + assert_eq!(requests[0].method, "POST"); + assert_eq!( + requests[0].header_value("content-type"), + Some("text/plain;charset=UTF-8") + ); + assert_eq!( + requests[0].header_value("referer"), + expected.as_deref(), + "{policy}" + ); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn link_audit_ping_omits_referer_without_losing_ping_headers() { + let server = + StaticHttpServer::spawn_with_responder(1, "Content-Type: text/plain\r\n", |_, _| { + "ok".to_owned() + }) + .await; + let loader = static_http_loader(std::iter::empty::()); + let document = beacon_url(&server, "/page?query=1"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(&document, &loader); + let url = beacon_url(&server, "/ping"); + vm.eval(&format!( + "const a=document.body.appendChild(document.createElement('a'));a.href='#destination';a.ping={url:?};a.click();true" + )).unwrap(); + assert_eq!( + finish_beacon_timing(&mut vm, &loader, &url).await, + serde_json::json!([["ping", 200]]) + ); + let requests = server.finish().await; + assert_eq!(requests.len(), 1); + let request = &requests[0]; + assert_eq!(request.method, "POST"); + assert_eq!(request.body, b"PING"); + assert_eq!(request.header_value("content-type"), Some("text/ping")); + assert_eq!(request.header_value("referer"), None); + assert_eq!(request.header_value("ping-from"), Some(document.as_str())); + assert_eq!( + request.header_value("ping-to"), + Some(format!("{document}#destination").as_str()) + ); +} + +fn complete_intercepted_beacon(vm: &mut StandaloneScriptVmHarness, internal_id: u64, url: &str) { + vm.complete_async_subresource_fetch(crate::types::AsyncSubresourceFetchCompletion { + internal_id, + request_url: Url::parse(url).unwrap(), + request_method: "POST".to_owned(), + request_headers: Vec::new().into(), + request_body: Some("payload".to_owned()), + response_status_text: Some("No Content".to_owned()), + skip_fetch_security_validation: false, + response_filter: None, + network_error_text: None, + result: Ok(crate::types::NavigationResponse::from_text_body( + Url::parse(url).unwrap(), + 204, + Vec::new(), + String::new(), + )) + .into(), + }) + .unwrap(); +} + +#[test] +fn beacon_csp_rejection_precedes_quota_and_does_not_create_network_timing() { + let mut vm = new_storage_html_test_vm("https://beacon-policy.test/page"); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + vm.eval("document.head.appendChild(Object.assign(document.createElement('meta'),{httpEquiv:'Content-Security-Policy',content:\"connect-src 'none'\"}));true").unwrap(); + assert_eq!(vm.eval("JSON.stringify([navigator.sendBeacon('/blocked','payload'),navigator.sendBeacon('/blocked','x'.repeat(65537))])").unwrap(), "[true,true]"); + assert!( + vm._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test() + .is_empty() + ); + assert_eq!( + vm.eval( + "String(performance.getEntriesByName('https://beacon-policy.test/blocked').length)" + ) + .unwrap(), + "0" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn beacon_argument_conversion_uses_the_current_document_in_the_same_window() { + let server = + StaticHttpServer::spawn_with_responder(2, "Content-Type: text/plain\r\n", |_, _| { + "ok".to_owned() + }) + .await; + let loader = static_http_loader(std::iter::empty::()); + let document = beacon_url(&server, "/main"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(&document, &loader); + for kind in ["url", "body"] { + assert_eq!(vm.eval(&format!(r#"(() => {{ + const kind={kind:?}; + const rewrite=()=>{{ + document.open(); + document.write('replacement'); + document.close(); + return kind==='url'?'capture?case=url':'payload-body'; + }}; + return String(navigator.sendBeacon( + kind==='url'?{{toString:rewrite}}:'capture?case=body', + kind==='body'?{{toString:rewrite}}:'payload-url')); + }})()"#)).unwrap(), "true", "{kind}"); + let url = beacon_url(&server, &format!("/changed/{kind}/capture?case={kind}")); + assert_eq!( + finish_beacon_timing(&mut vm, &loader, &url).await, + serde_json::json!([["beacon", 200]]) + ); + } + let requests = server.finish().await; + assert_eq!(requests.len(), 2); + for (request, kind) in requests.iter().zip(["url", "body"]) { + assert_eq!(request.method, "POST"); + assert_eq!( + request.target, + format!("/changed/{kind}/capture?case={kind}") + ); + assert_eq!(request.body, format!("payload-{kind}").as_bytes()); + assert_eq!(request.header_value("referer"), Some(document.as_str())); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn csp_blocked_link_ping_records_failure_without_admitting_full_keepalive_quota() { + let loader = static_http_loader(std::iter::empty::()); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://ping-policy.test/page", + &loader, + ); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + assert_eq!( + vm.eval("String(navigator.sendBeacon('/filled','x'.repeat(65536)))") + .unwrap(), + "true" + ); + let accepted = vm + ._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(); + assert_eq!(accepted.len(), 1); + vm.eval("document.head.appendChild(Object.assign(document.createElement('meta'),{httpEquiv:'Content-Security-Policy',content:\"connect-src 'none'\"}));const a=document.body.appendChild(document.createElement('a'));a.href='#destination';a.ping='/blocked';a.click();true").unwrap(); + assert_eq!( + finish_beacon_timing(&mut vm, &loader, "https://ping-policy.test/blocked").await, + serde_json::json!([["ping", 0]]) + ); + assert_eq!( + vm._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(), + accepted + ); + assert_eq!( + vm.eval("String(navigator.sendBeacon('/blocked-beacon','x'.repeat(65537)))") + .unwrap(), + "true" + ); + assert_eq!( + vm.eval( + "String(performance.getEntriesByName('https://ping-policy.test/blocked-beacon').length)" + ) + .unwrap(), + "0" + ); +} + +#[test] +fn beacon_document_open_keeps_the_window_timeline_without_retaining_v8() { + let mut vm = new_storage_test_vm("https://beacon-timeline.test/page"); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + assert_eq!( + vm.eval("String(navigator.sendBeacon('/beacon','payload'))") + .unwrap(), + "true" + ); + let accepted = vm + ._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(); + assert_eq!(accepted.len(), 1); + assert!(!accepted[0].2); + vm.eval("globalThis.originalPerformance=performance;document.open();document.write('replacement');document.close();true").unwrap(); + complete_intercepted_beacon( + &mut vm, + accepted[0].0, + "https://beacon-timeline.test/beacon", + ); + assert_eq!(vm.eval("String(performance===originalPerformance && performance.getEntriesByName('https://beacon-timeline.test/beacon').length===1 && performance.getEntriesByName('https://beacon-timeline.test/beacon')[0].responseStatus===204)").unwrap(), "true"); +} + +#[test] +fn beacon_registered_native_proxy_uses_its_navigator_window_without_author_traps() { + let mut vm = new_storage_html_test_vm("https://beacon-native-proxy.test/page"); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + vm.eval("globalThis.frame=document.body.appendChild(document.createElement('iframe'));globalThis.childNavigator=frame.contentWindow.navigator;globalThis.childPerformance=frame.contentWindow.performance;globalThis.aliasTraps=0;globalThis.aliasTrap=()=>{aliasTraps++;throw Error('author trap')};true").unwrap(); + let context_ptr = &vm.current_main_world().unwrap().context as *const _; + vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| { + let global = scope.get_current_context().global(scope); + let target_key = crate::util::v8str(scope, "childNavigator"); + let target = global.get(scope, target_key.into()).unwrap(); + let target = v8::Local::::try_from(target).unwrap(); + let handler = crate::util::new_null_prototype_object(scope); + let trap_key = crate::util::v8str(scope, "aliasTrap"); + let trap = global.get(scope, trap_key.into()).unwrap(); + let get_key = crate::util::v8str(scope, "get"); + assert_eq!( + handler.create_data_property(scope, get_key.into(), trap), + Some(true) + ); + let proxy = v8::Proxy::new(scope, target, handler).unwrap(); + moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap(); + let alias_key = crate::util::v8str(scope, "navigatorAlias"); + assert_eq!( + global.create_data_property(scope, alias_key.into(), proxy.into()), + Some(true) + ); + Ok(()) + }) + .unwrap(); + assert_eq!( + vm.eval("String(Navigator.prototype.sendBeacon.call(navigatorAlias,'/alias','payload'))") + .unwrap(), + "true" + ); + let accepted = vm + ._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(); + assert_eq!(accepted.len(), 1); + assert!(!accepted[0].2); + complete_intercepted_beacon( + &mut vm, + accepted[0].0, + "https://beacon-native-proxy.test/alias", + ); + assert_eq!(vm.eval("String(childPerformance.getEntriesByName('https://beacon-native-proxy.test/alias').length===1 && performance.getEntriesByName('https://beacon-native-proxy.test/alias').length===0 && aliasTraps===0)").unwrap(), "true"); + assert_eq!(vm.eval("(() => {let conversions=0,error;try{Navigator.prototype.sendBeacon.call(new Proxy(navigatorAlias,{get:aliasTrap}),{toString(){conversions++;return '/author'}},'payload')}catch(caught){error=caught}return String(error instanceof TypeError && conversions===0 && aliasTraps===0)})()").unwrap(), "true"); +} + +#[test] +fn beacon_window_retirement_records_one_failure_and_keeps_accepted_transport() { + let mut vm = new_storage_html_test_vm("https://beacon-timeline.test/page"); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + vm.eval("globalThis.frame=document.body.appendChild(document.createElement('iframe'));globalThis.oldPerformance=frame.contentWindow.performance;frame.contentWindow.navigator.sendBeacon('/retired','payload');true").unwrap(); + let accepted = vm + ._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(); + assert_eq!(accepted.len(), 1); + assert!(!accepted[0].2); + vm.eval("frame.remove();true").unwrap(); + assert_eq!(vm.eval("JSON.stringify(oldPerformance.getEntriesByName('https://beacon-timeline.test/retired').map(entry=>[entry.initiatorType,entry.responseStatus]))").unwrap(), r#"[["beacon",0]]"#); + assert_eq!( + vm._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(), + accepted + ); + complete_intercepted_beacon( + &mut vm, + accepted[0].0, + "https://beacon-timeline.test/retired", + ); + assert_eq!(vm.eval("JSON.stringify(oldPerformance.getEntriesByName('https://beacon-timeline.test/retired').map(entry=>[entry.initiatorType,entry.responseStatus]))").unwrap(), r#"[["beacon",0]]"#); + assert_eq!( + vm.eval( + "String(performance.getEntriesByName('https://beacon-timeline.test/retired').length)" + ) + .unwrap(), + "0" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn beacon_child_navigation_finishes_the_retired_performance_timeline() { + let loader = static_http_loader(std::iter::empty::()); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://beacon-navigation.test/page", + &loader, + ); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Ping, + ), + ); + vm.eval("globalThis.frame=document.body.appendChild(document.createElement('iframe'));globalThis.oldPerformance=frame.contentWindow.performance;frame.contentWindow.navigator.sendBeacon('/retired','payload');true").unwrap(); + let accepted = vm + ._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(); + assert_eq!(accepted.len(), 1); + assert!(!accepted[0].2); + vm.eval("frame.srcdoc='

successor

';true").unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(frame.contentDocument.body?.textContent==='successor')", + "true", + "child navigation commits its successor Document", + ) + .await; + assert_eq!(vm.eval("JSON.stringify(oldPerformance.getEntriesByName('https://beacon-navigation.test/retired').map(entry=>[entry.initiatorType,entry.responseStatus]))").unwrap(), r#"[["beacon",0]]"#); + assert_eq!(vm.eval("String(frame.contentWindow.performance!==oldPerformance && frame.contentWindow.performance.getEntriesByName('https://beacon-navigation.test/retired').length===0)").unwrap(), "true"); + assert_eq!( + vm._context_host + .borrow() + .pending_window_beacon_execution_contexts_for_test(), + accepted, + "retiring the old timeline must preserve the native transport without a V8 root" + ); +} diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index fd34a3e232d..e62e942e827 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2294,6 +2294,7 @@ mod audio_event_interfaces; mod audio_node_interfaces; mod audio_param_node_interfaces; mod audio_source_interfaces; +mod beacon_request_policy; mod bitmap_renderer; mod bitmap_rendering_context_interface_interfaces; mod blob_range; @@ -2663,23 +2664,3 @@ mod path2d_native; mod vtt_cue_api; mod beacon_receiver_owner; - -mod frame_owner_origin_access; - -async fn drain_content_security_policy_violation_tasks_for_test( - vm: &mut crate::runtime::PageVmTaskExecutorTestHarness, - loader: &ResourceRequestClient, -) -> usize { - let mut count = 0; - while vm - .run_one_exact_selected_page_task_executor_turn( - crate::runtime::PageSelectedTaskTestSelector::MiscPlatformApi, - loader, - ) - .await - .expect("focused CSP fixture should run the selected native task") - { - count += 1; - } - count -} diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs index 74a85d8ac6d..d7b0173913a 100644 --- a/moli-renderer-v8/src/types.rs +++ b/moli-renderer-v8/src/types.rs @@ -111,7 +111,7 @@ pub(super) struct PendingFontFaceFetch { } pub(super) enum PendingSubresourceContinuation { - Beacon, + Beacon(Box), Dictionary(Box), ResponsePreload(Box), CspReport { @@ -151,6 +151,17 @@ pub(super) enum PendingSubresourceContinuation { ChildDocument(Box), } +/// Fire-and-forget HTTP requests retain native policy, not a script realm. +/// Upload bytes in this snapshot share their immutable backing with the lease. +pub(super) struct PendingBeacon { + pub(super) request: moli_fetch::Request, + pub(super) policy_context: SubresourcePolicyContext, + pub(super) policy: crate::document_runtime::DocumentConnectPolicySnapshot, + pub(super) redirect_state: crate::network_host::FetchCspRedirectState, + pub(super) report_context: crate::network_host::WindowCspReportRequestContext, + pub(super) timing: Option, +} + pub(super) struct PendingDictionaryFetch { pub(super) policy: crate::document_runtime::DocumentConnectPolicySnapshot, pub(super) redirect_state: crate::network_host::FetchCspRedirectState, @@ -208,6 +219,11 @@ impl PendingSubresourceContinuation { &crate::network_host::WindowCspReportRequestContext, )> { match self { + Self::Beacon(beacon) => Some(( + &beacon.policy, + &beacon.redirect_state, + &beacon.report_context, + )), Self::Fetch(fetch) => Some(( fetch.connect_policy(), fetch.redirect_csp_state(), @@ -2294,6 +2310,5 @@ mod tests { assert!(media.delays_document_load_event()); assert!(text_track.delays_document_load_event()); assert!(stylesheet_subresource.delays_document_load_event()); - assert!(!PendingSubresourceContinuation::Beacon.delays_document_load_event()); } }