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 9a4fd2835ee..55f383147e6 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 @@ -995,6 +995,7 @@ impl PageScriptHost { sequence: crate::native_bridge::ImageLoadEventId, owner: OwnerDispatchScope, request_initiator_type: SubresourceRequestInitiatorType, + request_metadata: moli_fetch::SubresourceRequestMetadata, registration: SubresourceFetchRegistration, credentials_mode: moli_fetch::RequestCredentialsMode, request_mode: moli_fetch::RequestMode, @@ -1040,6 +1041,7 @@ impl PageScriptHost { image_handle, sequence, request_initiator_type, + request_metadata, }, deferred_request_started: false, blob_url_entry: None, @@ -1057,6 +1059,7 @@ impl PageScriptHost { sequence: crate::native_bridge::ImageLoadEventId, owner: OwnerDispatchScope, request_initiator_type: SubresourceRequestInitiatorType, + request_metadata: moli_fetch::SubresourceRequestMetadata, credentials_mode: moli_fetch::RequestCredentialsMode, request_mode: moli_fetch::RequestMode, network_partition_key: Option, @@ -1069,6 +1072,7 @@ impl PageScriptHost { sequence, owner, request_initiator_type, + request_metadata, SubresourceFetchRegistration::Intercepted, credentials_mode, request_mode, @@ -1086,6 +1090,7 @@ impl PageScriptHost { sequence: crate::native_bridge::ImageLoadEventId, owner: OwnerDispatchScope, request_initiator_type: SubresourceRequestInitiatorType, + request_metadata: moli_fetch::SubresourceRequestMetadata, cancel_handle: moli_fetch::FetchCancelHandle, credentials_mode: moli_fetch::RequestCredentialsMode, request_mode: moli_fetch::RequestMode, @@ -1099,6 +1104,7 @@ impl PageScriptHost { sequence, owner, request_initiator_type, + request_metadata, SubresourceFetchRegistration::Direct(cancel_handle), credentials_mode, request_mode, diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index 9fca60ec0cd..58e0915b51b 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -500,27 +500,25 @@ pub(crate) use geometry::{ }; #[cfg(feature = "devtools")] pub(crate) use geometry::{observable_deep_hit_test, scroll_node_into_view_at_center}; -pub(crate) use global_attributes::canonical_cross_origin_value; use global_attributes::canonical_fetch_priority_value; pub(super) use global_attributes::{ anchor_target_getter_function, anchor_target_setter_function, area_no_href_setter_function, area_target_getter_function, area_target_setter_function, base_target_getter_function, base_target_setter_function, canonical_dir_value, canonical_loading_value, - canonical_preload_value, canonical_referrer_policy_value, - dom_string_reflection_getter_function, dom_string_reflection_setter_function, - html_align_getter_function, html_align_setter_function, html_alt_getter_function, - html_as_getter_function, html_bg_color_getter_function, html_border_getter_function, - html_charset_getter_function, html_cite_getter_function, html_color_getter_function, - html_compact_getter_function, html_compact_setter_function, html_coords_getter_function, - html_date_time_getter_function, html_decoding_getter_function, html_download_getter_function, - html_fetch_priority_getter_function, html_frame_border_getter_function, - html_height_getter_function, html_hreflang_getter_function, html_hspace_getter_function, - html_label_getter_function, html_long_desc_getter_function, html_lowsrc_getter_function, - html_margin_height_getter_function, html_margin_width_getter_function, - html_media_getter_function, html_name_getter_function, html_name_setter_function, - html_no_href_getter_function, html_no_resize_getter_function, html_no_resize_setter_function, - html_no_shade_getter_function, html_no_shade_setter_function, html_ping_getter_function, - html_ping_setter_function, html_rel_getter_function, html_rel_setter_function, + canonical_preload_value, dom_string_reflection_getter_function, + dom_string_reflection_setter_function, html_align_getter_function, html_align_setter_function, + html_alt_getter_function, html_as_getter_function, html_bg_color_getter_function, + html_border_getter_function, html_charset_getter_function, html_cite_getter_function, + html_color_getter_function, html_compact_getter_function, html_compact_setter_function, + html_coords_getter_function, html_date_time_getter_function, html_decoding_getter_function, + html_download_getter_function, html_fetch_priority_getter_function, + html_frame_border_getter_function, html_height_getter_function, html_hreflang_getter_function, + html_hspace_getter_function, html_label_getter_function, html_long_desc_getter_function, + html_lowsrc_getter_function, html_margin_height_getter_function, + html_margin_width_getter_function, html_media_getter_function, html_name_getter_function, + html_name_setter_function, html_no_href_getter_function, html_no_resize_getter_function, + html_no_resize_setter_function, html_no_shade_getter_function, html_no_shade_setter_function, + html_ping_getter_function, html_ping_setter_function, html_rel_getter_function, html_rel_setter_function, html_scrolling_getter_function, html_shape_getter_function, html_size_getter_function, html_sizes_getter_function, html_true_speed_getter_function, html_true_speed_setter_function, html_type_getter_function, html_use_map_getter_function, html_value_getter_function, @@ -559,6 +557,7 @@ pub(super) use global_attributes::{ table_v_align_getter_function, unsigned_long_reflection_setter_function, usv_string_reflection_getter_function, usv_string_reflection_setter_function, }; +pub(crate) use global_attributes::{canonical_cross_origin_value, canonical_referrer_policy_value}; use html_elements::{ body_background_getter_function, body_background_setter_function, li_value_getter_function, li_value_setter_function, meta_content_getter_function, meta_content_setter_function, diff --git a/moli-renderer-v8/src/native_bridge/element/global_attributes.rs b/moli-renderer-v8/src/native_bridge/element/global_attributes.rs index b7989b85d8b..b6ee17d9294 100644 --- a/moli-renderer-v8/src/native_bridge/element/global_attributes.rs +++ b/moli-renderer-v8/src/native_bridge/element/global_attributes.rs @@ -987,7 +987,7 @@ pub(in crate::native_bridge) fn node_dir_setter_function<'s>( rv.set_undefined(); } -pub(in crate::native_bridge) fn canonical_referrer_policy_value(raw: &str) -> &'static str { +pub(crate) fn canonical_referrer_policy_value(raw: &str) -> &'static str { const KEYWORDS: &[&str] = &[ "no-referrer", "no-referrer-when-downgrade", diff --git a/moli-renderer-v8/src/native_bridge/element/images/src.rs b/moli-renderer-v8/src/native_bridge/element/images/src.rs index 2ec789cdb24..ed3a04d49f1 100644 --- a/moli-renderer-v8/src/native_bridge/element/images/src.rs +++ b/moli-renderer-v8/src/native_bridge/element/images/src.rs @@ -15,7 +15,10 @@ use crate::style_engine::media_list::evaluate_media_query_list; use super::super::super::node::node_runtime_and_handle_from_object_or_detached; use super::super::geometry::compute_mock_client_rect; -use super::super::{construct_simple_event, dispatch_public_event, resolve_url_like_attribute}; +use super::super::{ + canonical_referrer_policy_value, construct_simple_event, dispatch_public_event, + resolve_url_like_attribute, +}; use super::lazy::{image_load_is_deferred, revealed_lazy_image_handles}; const IMAGE_UPDATE_HANDLE_INDEX: u32 = 0; @@ -635,8 +638,15 @@ pub(crate) fn plan_image_attribute_ns_mutation( return ImageAttributeMutationPlan::default(); } if element.is_html_element("img") { - let reloads_image = - matches!(local_name, "src" | "srcset" | "sizes") || changes_cross_origin; + let changes_referrer_policy = local_name == "referrerpolicy" + && canonical_referrer_policy_value( + element + .attribute_ns("", "referrerpolicy") + .unwrap_or_default(), + ) != canonical_referrer_policy_value(next_value.unwrap_or_default()); + let reloads_image = matches!(local_name, "src" | "srcset" | "sizes") + || changes_cross_origin + || changes_referrer_policy; return ImageAttributeMutationPlan { targets: reloads_image.then_some(handle).into_iter().collect(), }; diff --git a/moli-renderer-v8/src/network_host/image.rs b/moli-renderer-v8/src/network_host/image.rs index 613d39ae1d2..f19610c6d4b 100644 --- a/moli-renderer-v8/src/network_host/image.rs +++ b/moli-renderer-v8/src/network_host/image.rs @@ -13,7 +13,7 @@ use crate::types::{ }; use moli_fetch::{ BrowserRequestMetadata, FetchCancelHandle, FetchPriorityHint, RequestCredentialsMode, - RequestMode, RequestRedirectMode, RequestResourceType, + RequestMode, RequestRedirectMode, RequestResourceType, SubresourceRequestMetadata, }; #[derive(Debug)] @@ -236,6 +236,16 @@ pub(crate) fn start_image_element_resource_fetch( let request_initiator_type = pending.request_initiator_type(); let (request_mode, credentials_mode) = image_cross_origin_request_modes(element); let fetch_priority = FetchPriorityHint::from_attribute(element.attribute("fetchpriority")); + let request_metadata = SubresourceRequestMetadata { + referrer_policy: element + .attribute_ns("", "referrerpolicy") + .filter(|_| element.is_html_element("img")) + .map(crate::native_bridge::element::canonical_referrer_policy_value) + .filter(|policy| !policy.is_empty()) + .map(str::to_owned), + document_referrer_policy: effective_subresource_referrer_policy(host, owner), + integrity: None, + }; if let Some(response) = local_url_response(&request_url) { let mut response: crate::protocol_types::NavigationResponse = response.into(); @@ -310,6 +320,7 @@ pub(crate) fn start_image_element_resource_fetch( sequence, owner, request_initiator_type, + request_metadata, credentials_mode, request_mode, network_partition_key, @@ -326,6 +337,7 @@ pub(crate) fn start_image_element_resource_fetch( .with_initiator_url(&document_url) .with_request_origin(request_origin.clone()) .with_resource_type(RequestResourceType::Image) + .with_subresource_request_metadata(request_metadata.clone()) .with_page_network_policy() .with_request_mode(request_mode) .with_credentials_mode(credentials_mode) @@ -352,6 +364,7 @@ pub(crate) fn start_image_element_resource_fetch( sequence, owner, request_initiator_type, + request_metadata, cancel_handle.clone(), credentials_mode, request_mode, 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 3c2e9f561fd..7330d69bac5 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 @@ -66,6 +66,9 @@ pub(super) fn request_for_pending_subresource( request.request_headers = request_headers; let request = request.with_redirect_headers(pending.redirect_headers.clone()); return match &pending.continuation { + PendingSubresourceContinuation::Image { + request_metadata, .. + } => request.with_subresource_request_metadata(request_metadata.clone()), PendingSubresourceContinuation::ResponsePreload(preload) => { crate::network_host::apply_response_preload_request_metadata(request, preload) .with_network_partition_key(pending.network_partition_key.clone()) @@ -148,6 +151,9 @@ pub(super) fn request_for_pending_subresource( SubresourceResourceType::WebSocket | SubresourceResourceType::Document => request, }; let request = match &pending.continuation { + PendingSubresourceContinuation::Image { + request_metadata, .. + } => request.with_subresource_request_metadata(request_metadata.clone()), PendingSubresourceContinuation::ResponsePreload(preload) => { crate::network_host::apply_response_preload_request_metadata(request, preload) .with_network_partition_key(pending.network_partition_key.clone()) diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch/interception.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch/interception.rs index 615ab0b2f2c..dabaca536aa 100644 --- a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch/interception.rs +++ b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch/interception.rs @@ -481,6 +481,13 @@ impl ScriptVm { .and_then(|_| pending_fetch.info.request_body_bytes.clone()), ); for redirect in &response.redirect_chain { + if matches!( + &pending_fetch.continuation, + PendingSubresourceContinuation::Image { .. } + ) { + // Authentication must not restore referrer data stripped before the challenge. + request.update_referrer_for_redirect(&redirect.from_url, &redirect.headers); + } request.apply_redirect_status(redirect.status); } request.url = response.final_url.clone(); diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/images.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/images.rs index cc8f4bd768b..3622858f8bf 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/images.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/images.rs @@ -694,6 +694,238 @@ async fn image_attribute_updates_ignore_unrelated_attributes_and_unchanged_cors_ } } +#[tokio::test] +async fn image_referrer_policy_state_changes_use_shared_attribute_mutation_paths() { + for assignment in [ + "__policyImage.referrerPolicy = 'origin'", + "__policyImage.setAttribute('referrerpolicy', 'origin')", + "__policyImage.setAttributeNS(null, 'referrerpolicy', 'origin')", + "__policyImage.getAttributeNode('referrerpolicy').value = 'origin'", + "__policyImage.getAttributeNode('referrerpolicy').nodeValue = 'origin'", + "__policyImage.getAttributeNode('referrerpolicy').textContent = 'origin'", + "{ const attr = document.createAttribute('referrerpolicy'); attr.value = 'origin'; __policyImage.setAttributeNode(attr); }", + "{ const attr = document.createAttribute('referrerpolicy'); attr.value = 'origin'; __policyImage.attributes.setNamedItem(attr); }", + ] { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + loader.set_image_fetch_enabled(true); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://image-referrer-state.test/page.html", + &loader, + ); + vm.set_layout_policy(moli_page_types::LayoutPolicy::Mock); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Image, + ), + ); + vm.eval( + r#" + globalThis.__policyImage = new Image(); + globalThis.__policyEvents = []; + __policyImage.onload = () => __policyEvents.push('load'); + __policyImage.onerror = () => __policyEvents.push('error'); + __policyImage.referrerPolicy = 'no-referrer'; + __policyImage.src = '/available.gif'; + "#, + ) + .unwrap(); + let requests = vm.take_pending_subresource_fetch_infos(); + assert_eq!(requests.len(), 1, "{assignment}: initial request"); + vm.fulfill_pending_subresource_fetch( + requests[0].internal_id, + 200, + vec![("Content-Type".into(), b"image/gif".to_vec())], + one_by_one_gif_response_body(), + ) + .unwrap(); + run_next_image_event_task(&mut vm, &loader, "initial referrer policy image").await; + assert_eq!(vm.eval("__policyEvents.join('|')").unwrap(), "load"); + assert_eq!( + vm.eval(&format!( + "__policyEvents.length = 0; {assignment}; __policyEvents.length" + )) + .unwrap(), + "0" + ); + assert!( + vm.take_pending_subresource_fetch_infos().is_empty(), + "reuse the available image" + ); + run_next_image_event_task(&mut vm, &loader, assignment).await; + assert_eq!( + vm.eval("__policyEvents.join('|')").unwrap(), + "load", + "{assignment}" + ); + assert_eq!(vm.eval("[__policyImage.referrerPolicy, __policyImage.complete, __policyImage.naturalWidth].join(':')").unwrap(), "origin:true:1", "{assignment}"); + } +} + +#[tokio::test] +async fn unchanged_image_referrer_policy_states_do_not_queue_load_events() { + for (initial, mutation) in [ + (None, "__policyImage.referrerPolicy = 'invalid'"), + (None, "__policyImage.referrerPolicy = ''"), + (Some(""), "__policyImage.referrerPolicy = 'invalid'"), + ( + Some("no-referrer"), + "__policyImage.referrerPolicy = 'NO-REFERRER'", + ), + ( + Some(" origin "), + "__policyImage.referrerPolicy = 'other-invalid'", + ), + ( + Some("no-referrer, unsafe-url"), + "__policyImage.removeAttribute('referrerpolicy')", + ), + ( + Some("no-referrer"), + "__policyImage.setAttributeNS('urn:example', 'p:referrerpolicy', 'origin')", + ), + ] { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + loader.set_image_fetch_enabled(true); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://image-referrer-noop.test/page.html", + &loader, + ); + vm.set_layout_policy(moli_page_types::LayoutPolicy::Mock); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::for_resource_type( + crate::types::SubresourceResourceType::Image, + ), + ); + vm.eval("globalThis.__policyImage = new Image(); globalThis.__policyEvents = []; __policyImage.onload = () => __policyEvents.push('load'); __policyImage.onerror = () => __policyEvents.push('error');").unwrap(); + if let Some(initial) = initial { + vm.eval(&format!( + "__policyImage.setAttribute('referrerpolicy', {initial:?})" + )) + .unwrap(); + } + vm.eval("__policyImage.src = '/ready.gif'").unwrap(); + let requests = vm.take_pending_subresource_fetch_infos(); + assert_eq!(requests.len(), 1); + vm.fulfill_pending_subresource_fetch( + requests[0].internal_id, + 200, + vec![("Content-Type".into(), b"image/gif".to_vec())], + one_by_one_gif_response_body(), + ) + .unwrap(); + run_next_image_event_task(&mut vm, &loader, "referrer policy no-op setup").await; + vm.eval(&format!("__policyEvents.length = 0; {mutation}")) + .unwrap(); + assert!( + !vm.run_one_dom_manipulation_task_executor_turn( + PageDomManipulationTestFamily::ImageLoadEvent, + &loader, + ) + .await + .unwrap(), + "{initial:?}: {mutation}" + ); + assert_eq!(vm.eval("__policyEvents.length").unwrap(), "0"); + assert!(vm.take_pending_subresource_fetch_infos().is_empty()); + } +} + +#[tokio::test] +async fn image_requests_retain_element_and_document_referrer_policy_at_dispatch() { + for (intercepted, element_policy, document_policy, expected) in [ + (false, Some("no-referrer"), Some("unsafe-url"), "none"), + (false, Some("origin"), None, "origin"), + (false, Some("ORIGIN"), None, "origin"), + (false, Some(" no-referrer "), Some("no-referrer"), "none"), + ( + false, + Some("no-referrer, unsafe-url"), + Some("no-referrer"), + "none", + ), + (false, Some("unsafe-url"), Some("no-referrer"), "full"), + (false, None, Some("origin"), "origin"), + (false, None, None, "full"), + (true, Some("no-referrer"), Some("unsafe-url"), "none"), + (true, None, Some("origin"), "origin"), + ] { + let (base, request_rx, server) = + spawn_image_response_server("200 OK", "image/gif", ONE_BY_ONE_GIF).await; + let source = format!("{base}/folder/page.html?query=1#fragment"); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + loader.set_image_fetch_enabled(true); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(&source, &loader); + vm.set_layout_policy(moli_page_types::LayoutPolicy::Mock); + vm.set_fetch_subresource_interception(if intercepted { + crate::types::SubresourceInterceptionClasses::IMAGE + } else { + crate::types::SubresourceInterceptionClasses::NONE + }); + vm.eval("globalThis.__policyImage = new Image(); globalThis.__policyEvents = []; __policyImage.onload = () => __policyEvents.push('load'); __policyImage.onerror = () => __policyEvents.push('error');").unwrap(); + if let Some(policy) = document_policy { + vm.eval(&format!("globalThis.__policyMeta = document.createElement('meta'); __policyMeta.name = 'referrer'; __policyMeta.content = {policy:?}; document.head.appendChild(__policyMeta)")).unwrap(); + } + if let Some(policy) = element_policy { + vm.eval(&format!("__policyImage.referrerPolicy = {policy:?}")) + .unwrap(); + } + vm.eval("__policyImage.src = '/image.gif'").unwrap(); + if intercepted { + let requests = vm.take_pending_subresource_fetch_infos(); + assert_eq!(requests.len(), 1); + vm.eval( + "__policyImage.referrerPolicy = 'unsafe-url'; __policyMeta.content = 'unsafe-url'", + ) + .unwrap(); + assert!( + vm.take_pending_subresource_fetch_infos().is_empty(), + "policy mutations must retain the in-flight selected request" + ); + vm.set_fetch_subresource_interception( + crate::types::SubresourceInterceptionClasses::NONE, + ); + vm.continue_pending_subresource_fetch( + requests[0].internal_id, + None, + None, + None, + None, + false, + false, + ) + .unwrap(); + } + let request = tokio::time::timeout(std::time::Duration::from_secs(2), request_rx) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + let referrer = request.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("referer").then(|| value.trim()) + }); + let expected = match expected { + "none" => None, + "origin" => Some(format!("{base}/")), + "full" => Some(format!("{base}/folder/page.html?query=1")), + _ => unreachable!(), + }; + assert_eq!( + referrer, + expected.as_deref(), + "{element_policy:?}/{document_policy:?}/intercepted={intercepted}" + ); + wait_for_and_apply_image_completions(&mut vm).await; + run_next_image_event_task(&mut vm, &loader, "referrer policy network image").await; + assert_eq!(vm.eval("__policyEvents.join('|')").unwrap(), "load"); + assert_eq!( + vm.eval("[__policyImage.complete, __policyImage.naturalWidth].join(':')") + .unwrap(), + "true:1" + ); + } +} + #[tokio::test] async fn render_image_decode_requires_both_real_layout_and_image_fetch() { let cases = [ diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs index aa616e09aad..a8e8487bbba 100644 --- a/moli-renderer-v8/src/types.rs +++ b/moli-renderer-v8/src/types.rs @@ -125,6 +125,7 @@ pub(super) enum PendingSubresourceContinuation { image_handle: crate::document_runtime::DomHandle, sequence: crate::native_bridge::ImageLoadEventId, request_initiator_type: SubresourceRequestInitiatorType, + request_metadata: moli_fetch::SubresourceRequestMetadata, }, Media { media_handle: crate::document_runtime::DomHandle, @@ -2212,6 +2213,7 @@ mod tests { image_handle: crate::document_runtime::DomHandle::new(1), sequence: crate::native_bridge::ImageLoadEventId::new(1), request_initiator_type: crate::types::SubresourceRequestInitiatorType::Parser, + request_metadata: moli_fetch::SubresourceRequestMetadata::default(), }; let media = PendingSubresourceContinuation::Media { media_handle: crate::document_runtime::DomHandle::new(2),