From 1728ea47c19ef854aa7c48fa88f2cc4aeaefaa40 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Fri, 23 Oct 2026 04:32:34 +0800 Subject: [PATCH] fix(fonts): bind FontFace requests to the creation Window Capture the relevant Window identity before constructor conversions. Use it for URL resolution, request security and network dispatch, and reject loads whose creation Window has retired instead of borrowing a caller frame. Add an HTTP-CSP cross-frame message regression covering both parent and child FontFaces. Validation: cargo fmt --all; strict workspace Clippy; full Nextest (20,587 passed, 18 skipped). --- .../css_fontface_runtime/font_face.rs | 8 ++- .../css_fontface_runtime/loading.rs | 18 ++++- .../css_fontface_runtime/state.rs | 19 ++++- moli-renderer-v8/src/network_host.rs | 5 +- .../src/network_host/font_face.rs | 24 +++++-- .../src/script_vm/tests/browser_api/fonts.rs | 1 + .../tests/browser_api/fonts/ownership.rs | 69 +++++++++++++++++++ 7 files changed, 133 insertions(+), 11 deletions(-) create mode 100644 moli-renderer-v8/src/script_vm/tests/browser_api/fonts/ownership.rs diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs index 9b36fe91161..fbd243aaed5 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs @@ -289,6 +289,7 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>( throw_type_error(scope, "Constructor must be called with new"); return; } + let request_context = crate::network_host::capture_font_face_request_context(scope); let Some(parsed) = webidl::parse_args::(scope, &args) else { return; }; @@ -313,8 +314,9 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>( let this = args.this(); let (source, sources, binary) = match parsed.source { FontFaceConstructorSource::Css(source) => { - let sources = moli_css_parse::parse_font_face_sources(&source) - .map(|sources| crate::network_host::resolve_font_face_sources(scope, sources)); + let sources = moli_css_parse::parse_font_face_sources(&source).map(|sources| { + crate::network_host::resolve_font_face_sources(scope, request_context, sources) + }); (source, sources, None) } FontFaceConstructorSource::Binary(value) => { @@ -372,7 +374,7 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>( } else if let Some(bytes) = binary { resource.borrow_mut().initialize_binary(&bytes); } - super::loading::initialize_resolver(scope, this, resolver, resource); + super::loading::initialize_resolver(scope, this, resolver, resource, request_context); rv.set(this.into()); } diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs index 30fa432dc6a..300c83ae5eb 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs @@ -166,6 +166,7 @@ pub(super) fn initialize_resolver<'s>( face: v8::Local<'s, v8::Object>, resolver: v8::Local<'s, v8::PromiseResolver>, resource: FontFaceLoad, + request_context: Option, ) { set_private_value(scope, face, RESOLVER, resolver.into()); // A retained pending .loaded promise must retain its settlement endpoint, @@ -178,7 +179,7 @@ pub(super) fn initialize_resolver<'s>( PROMISE_OWNER, face.into(), ); - super::state::initialize(scope, face, resource); + super::state::initialize(scope, face, resource, request_context); publish_state(scope, face); } @@ -275,12 +276,25 @@ fn advance_sources<'s>( face: v8::Local<'s, v8::Object>, load: &FontFaceLoad, ) { + let request_context = super::state::request_context(scope, face); + if let Some(host_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) + && !request_context.is_some_and(|identity| { + unsafe { &*host_ptr }.window_execution_context_identity_is_current(identity) + }) + { + load.borrow_mut().fail( + "NetworkError", + "FontFace creation Window is no longer available.", + ); + publish_font_face_load_changes(scope); + return; + } loop { let url = with_font_services(scope, |services| load.borrow_mut().next_url(services)); let Some(url) = url else { break; }; - match crate::network_host::start_font_face_fetch(scope, face, &url) { + match crate::network_host::start_font_face_fetch(scope, face, request_context, &url) { Ok(crate::network_host::FontFaceFetchStart::Pending) => return, Ok(crate::network_host::FontFaceFetchStart::Local(bytes)) => { let _ = load.borrow_mut().accept_response(Some(&bytes)); diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs index 2e5eef1a535..5db03817f8a 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs @@ -21,12 +21,14 @@ struct Observer { wrapper: v8::Weak, load: FontFaceLoad, published: FontFaceStatus, + request_context: Option, } pub(super) fn initialize<'s>( scope: &mut v8::PinScope<'s, '_>, face: v8::Local<'s, v8::Object>, load: FontFaceLoad, + request_context: Option, ) { let store = if let Some(store) = scope.get_slot::() { store.clone() @@ -59,6 +61,7 @@ pub(super) fn initialize<'s>( wrapper, load, published: FontFaceStatus::Unloaded, + request_context, }, ); set_private_value( @@ -91,6 +94,19 @@ pub(super) fn get<'s>( ) } +pub(super) fn request_context<'s>( + scope: &mut v8::PinScope<'s, '_>, + face: v8::Local<'s, v8::Object>, +) -> Option { + let id = id(scope, face)?; + scope + .get_slot::()? + .borrow() + .entries + .get(&id)? + .request_context +} + pub(super) fn bind<'s>( scope: &mut v8::PinScope<'s, '_>, face: v8::Local<'s, v8::Object>, @@ -164,7 +180,7 @@ mod tests { let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); let css_face = v8::Object::new(scope); - initialize(scope, css_face, css_load.clone()); + initialize(scope, css_face, css_load.clone(), None); let js_face = v8::Object::new(scope); initialize( scope, @@ -175,6 +191,7 @@ mod tests { Vec::new(), false, ), + None, ); Rc::downgrade(&get(scope, js_face).unwrap()) }; diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs index ba8fe0a6637..b4383b04b31 100644 --- a/moli-renderer-v8/src/network_host.rs +++ b/moli-renderer-v8/src/network_host.rs @@ -23,7 +23,10 @@ mod text_track; mod url_helpers; mod xhr; -pub(crate) use font_face::{FontFaceFetchStart, resolve_font_face_sources, start_font_face_fetch}; +pub(crate) use font_face::{ + FontFaceFetchStart, capture_font_face_request_context, resolve_font_face_sources, + start_font_face_fetch, +}; use moli_fetch::{Request, Response, observe_cookie_access_report_for_request}; use crate::network::ResourceRequestClient; diff --git a/moli-renderer-v8/src/network_host/font_face.rs b/moli-renderer-v8/src/network_host/font_face.rs index f13578e040c..47017ae4bc6 100644 --- a/moli-renderer-v8/src/network_host/font_face.rs +++ b/moli-renderer-v8/src/network_host/font_face.rs @@ -1,7 +1,7 @@ use super::subresource::{PreparedSubresourceFetch, SubresourceFetchOptions}; use super::*; use crate::{ - native_bridge::JsContextHost, + native_bridge::{JsContextHost, WindowExecutionContextIdentity}, types::{SubresourceRequestInitiatorType, SubresourceResourceType}, }; @@ -10,19 +10,31 @@ pub(crate) enum FontFaceFetchStart { Pending, } +/// Freeze the constructor's relevant Window, independently of an enclosing +/// child request callback. The identity contains no strong V8 handles. +pub(crate) fn capture_font_face_request_context( + scope: &mut v8::PinScope<'_, '_>, +) -> Option { + let host_ptr = crate::util::context_host_ptr_from_global_bridge(scope)?; + let context = scope.get_current_context(); + unsafe { &*host_ptr }.window_execution_context_identity_for_v8_context(scope, context) +} + /// Resolve URL sources at construction, before a later base mutation or source /// fallback. Invalid URLs remain unavailable sources, not CSS syntax errors; /// source exhaustion is reported only when loading is requested. pub(crate) fn resolve_font_face_sources( scope: &mut v8::PinScope<'_, '_>, + request_context: Option, sources: Vec, ) -> Vec { use moli_css_parse::CssFontSource; let base = crate::util::context_host_ptr_from_global_bridge(scope).and_then(|host_ptr| { let host = unsafe { &*host_ptr }; - let owner = effective_subresource_request_owner(scope, host); - subresource_api_base_url(scope, host, owner) + let identity = request_context + .filter(|identity| host.window_execution_context_identity_is_current(*identity))?; + subresource_api_base_url(scope, host, identity.dispatch_scope()) }); sources .into_iter() @@ -42,6 +54,7 @@ pub(crate) fn resolve_font_face_sources( pub(crate) fn start_font_face_fetch( scope: &mut v8::PinScope<'_, '_>, face: v8::Local<'_, v8::Object>, + request_context: Option, source: &str, ) -> Result { let host_ptr = crate::util::context_host_ptr_from_global_bridge(scope) @@ -49,7 +62,10 @@ pub(crate) fn start_font_face_fetch( // SAFETY: the current live realm owns the bridge. No author callback runs // while the host is used except its existing CSP notification boundary. let host: &mut JsContextHost = unsafe { &mut *host_ptr }; - let owner = effective_subresource_request_owner(scope, host); + let identity = request_context + .filter(|identity| host.window_execution_context_identity_is_current(*identity)) + .ok_or_else(|| "FontFace creation Window is no longer available".to_owned())?; + let owner = identity.dispatch_scope(); let resource_loader = host .document_resource_loader_for_dispatch_scope(owner) .ok_or_else(|| "Font request has no live document resource loader".to_owned())?; diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs index 9f709fa2283..09403e8484d 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs @@ -3,6 +3,7 @@ use base64::Engine; use std::time::Duration; mod matching; +mod ownership; mod readiness; mod selection_order; mod unicode_ranges; diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/ownership.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/ownership.rs new file mode 100644 index 00000000000..3f245ad05d8 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/ownership.rs @@ -0,0 +1,69 @@ +use super::*; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +#[tokio::test] +async fn font_face_cross_frame_message_uses_creation_window_csp() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let child = r#""#; + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut bytes = [0; 1024]; + while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") { + let count = socket.read(&mut bytes).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&bytes[..count]); + } + assert!(request.starts_with(b"GET /child.html ")); + socket.write_all(format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Security-Policy: font-src 'none'\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{child}", + child.len() + ).as_bytes()).await.unwrap(); + }); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + &format!("{origin}/parent.html"), + &loader, + ); + vm.set_response_content_security_policies(&["font-src data:".into()]); + let source = serde_json::to_string(&format!("url(\"{}\")", fixture_font_url())).unwrap(); + vm.eval(&format!( + r#" + globalThis.ownerResults=[]; + globalThis.parentFace=new FontFace('ParentOwner', {source}); + document.fonts.add(parentFace); + globalThis.frame=document.createElement('iframe'); + frame.src='{origin}/child.html'; + addEventListener('message',event=>{{ + if(event.data==='ready') frame.contentWindow.postMessage('load','*'); + else ownerResults.push(event.data); + }}); + (document.body||document.documentElement||document).append(frame); + "# + )) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(ownerResults.length)", + "1", + "cross-frame FontFace load result", + ) + .await; + assert_eq!(vm.eval("ownerResults[0]").unwrap(), "parent:loaded"); + assert_eq!( + vm.eval("frame.contentWindow.childFace.load();frame.contentWindow.childFace.status") + .unwrap(), + "error", + "the child FontFace must still use its own blocking CSP" + ); + server.await.unwrap(); +}