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).
This commit is contained in:
ldm0
2026-10-24 01:03:33 +08:00
committed by Donough Liu
parent 85d5861b9e
commit 1728ea47c1
7 changed files with 133 additions and 11 deletions
@@ -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::<FontFaceConstructorArgs>(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());
}
@@ -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<crate::native_bridge::WindowExecutionContextIdentity>,
) {
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));
@@ -21,12 +21,14 @@ struct Observer {
wrapper: v8::Weak<v8::Object>,
load: FontFaceLoad,
published: FontFaceStatus,
request_context: Option<crate::native_bridge::WindowExecutionContextIdentity>,
}
pub(super) fn initialize<'s>(
scope: &mut v8::PinScope<'s, '_>,
face: v8::Local<'s, v8::Object>,
load: FontFaceLoad,
request_context: Option<crate::native_bridge::WindowExecutionContextIdentity>,
) {
let store = if let Some(store) = scope.get_slot::<Store>() {
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<crate::native_bridge::WindowExecutionContextIdentity> {
let id = id(scope, face)?;
scope
.get_slot::<Store>()?
.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())
};
+4 -1
View File
@@ -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;
+20 -4
View File
@@ -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<WindowExecutionContextIdentity> {
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<WindowExecutionContextIdentity>,
sources: Vec<moli_css_parse::CssFontSource>,
) -> Vec<moli_css_parse::CssFontSource> {
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<WindowExecutionContextIdentity>,
source: &str,
) -> Result<FontFaceFetchStart, String> {
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())?;
@@ -3,6 +3,7 @@ use base64::Engine;
use std::time::Duration;
mod matching;
mod ownership;
mod readiness;
mod selection_order;
mod unicode_ranges;
@@ -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#"<!doctype html><script>
globalThis.childFace=new FontFace('ChildOwner',parent.parentFace.source);
childFace.loaded.catch(()=>{});
onmessage=()=>parent.parentFace.load().then(
()=>parent.postMessage('parent:loaded','*'),
error=>parent.postMessage('parent:'+error.name,'*'));
parent.postMessage('ready','*');
</script>"#;
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();
}