fix(html): handle object fallback and dimensions

This commit is contained in:
ldm0
2026-11-19 00:16:20 +08:00
parent dbd9a463b2
commit 84ced71bbe
9 changed files with 386 additions and 112 deletions
@@ -876,6 +876,7 @@ impl DocumentRuntime {
return false;
}
let runtime = unsafe { &mut *host_ptr };
runtime.clear_object_fallback_for_attribute_change(handle, name);
let is_navigation_attribute =
runtime.frame_owner_navigation_attribute_matches(handle, name);
if is_srcdoc {
@@ -60,6 +60,7 @@ pub(super) struct PendingChildDocumentNavigation {
Option<crate::service_worker_runtime::ServiceWorkerClientId>,
pub(super) document_credentialless: bool,
pub(super) credentialless_storage_nonce: Option<OpaqueOriginNonce>,
pub(super) initiator: ChildDocumentNavigationInitiator,
pub(super) frame_owner_resource_timing: Option<PendingFrameOwnerResourceTiming>,
/// The Fetch pause holding this navigation's request, if any.
pub(super) paused_fetch: Option<u64>,
@@ -12,8 +12,11 @@ use crate::{
content_security_policy::{
ContentSecurityPolicyViolationEventFields, send_content_security_policy_reports,
},
context_bootstrap::{construct_original_event, mark_event_trusted},
document_response_decoder::decode_document_response,
document_runtime::{DocumentNavigationEmbeddingContext, DocumentPolicyContainer, DomHandle},
document_runtime::{
DocumentNavigationEmbeddingContext, DocumentPolicyContainer, DomHandle, EventTargetHandle,
},
document_script_scheduler::FrameDocumentClassicScriptSchedulerWork,
frame_owner_model::{
ChildDocumentNavigationFetchTarget, DocumentCreationKind,
@@ -199,6 +202,7 @@ impl PageScriptHost {
reserved_service_worker_client_id: service_worker_client_id,
document_credentialless,
credentialless_storage_nonce,
initiator,
frame_owner_resource_timing,
paused_fetch: None,
},
@@ -451,6 +455,9 @@ impl PageScriptHost {
);
self.finish_pending_child_document_navigation_owner_request(&pending);
let handle = target.child_handle();
let object_attribute_navigation = pending.initiator
== ChildDocumentNavigationInitiator::FrameOwnerElement
&& self.child_browsing_context_host_is_object_element(handle);
self.clear_child_browsing_context_pending_document_load_if_matches(
handle,
target.load_id(),
@@ -521,7 +528,7 @@ impl PageScriptHost {
&violation.report_to_endpoints,
);
}
if let Some(violation) = enforced_violation {
if let Some(violation) = enforced_violation.into_iter().next() {
Err(format!(
"child document response blocked by Content Security Policy `{}` for `{}`",
violation.effective_directive, violation.blocked_uri
@@ -532,6 +539,33 @@ impl PageScriptHost {
}
result => result,
};
let (result, object_fallback_required) = if object_attribute_navigation {
match result {
Ok(redirect @ ChildDocumentLoadOutcome::Redirect(_)) => (Ok(redirect), false),
Ok(ChildDocumentLoadOutcome::Loaded(loaded)) => {
let failed_status = loaded
.document_network
.as_ref()
.map(|network| network.status)
.filter(|status| !(200..300).contains(status));
if let Some(status) = failed_status {
(
Err(format!("object resource returned HTTP status {status}")),
true,
)
} else {
(Ok(ChildDocumentLoadOutcome::Loaded(loaded)), false)
}
}
Ok(ChildDocumentLoadOutcome::IgnoredNavigation) => (
Err("object resource cannot be represented as a nested document".to_owned()),
true,
),
Err(error) => (Err(error), true),
}
} else {
(result, false)
};
let document_credentialless = pending.document_credentialless;
let credentialless_storage_nonce = pending.credentialless_storage_nonce;
let replaces_existing_document = self
@@ -746,6 +780,26 @@ impl PageScriptHost {
handle,
target.navigation_load(),
);
if object_fallback_required {
self.enter_object_fallback_state(scope, handle);
if let Some(event) = construct_original_event(scope, "error") {
mark_event_trusted(scope, event);
let host_ptr: *mut PageScriptHost = self;
let runtime = unsafe { &mut *self.document_runtime };
let _ = runtime.dispatch_public_event_best_effort(
scope,
host_ptr,
EventTargetHandle::Node(handle),
event,
"object resource error event",
);
body_activity = ChildDocumentLoadBodyActivity::PageCodeOrEventDispatch;
}
return ChildDocumentLoadApplication::Applied {
followup: None,
body_activity,
};
}
None
}
};
@@ -781,7 +835,7 @@ impl PageScriptHost {
Some(pending.resource_loader.clone()),
) else {
if let Some(network) = completed_document_network {
self.record_child_document_load_network(&network_attribution, network);
self.record_child_document_network_activity(&network_attribution, network);
}
return ChildDocumentLoadApplication::Applied {
followup: None,
@@ -49,6 +49,13 @@ impl PageScriptHost {
self.child_frame_owner_element_kind(handle).is_some()
}
pub(in crate::native_bridge::context_host) fn child_browsing_context_host_is_object_element(
&self,
handle: DomHandle,
) -> bool {
self.child_frame_owner_element_kind(handle) == Some(ChildFrameOwnerElementKind::Object)
}
fn child_frame_owner_element_kind(
&self,
handle: DomHandle,
@@ -98,6 +105,20 @@ impl PageScriptHost {
.is_some_and(|kind| attribute_name.eq_ignore_ascii_case(kind.navigation_attribute()))
}
pub(crate) fn clear_object_fallback_for_attribute_change(
&mut self,
handle: DomHandle,
attribute_name: &str,
) {
if self.child_browsing_context_host_is_object_element(handle)
&& ["data", "type"]
.into_iter()
.any(|name| attribute_name.eq_ignore_ascii_case(name))
{
self.object_fallback_bootstraps.remove(&handle);
}
}
pub(crate) fn child_browsing_context_host_is_active(&self, handle: DomHandle) -> bool {
if self
.dom_host()
@@ -208,7 +229,13 @@ impl PageScriptHost {
{
return None;
}
Some(ChildBrowsingContextBootstrap::Url(url))
let bootstrap = ChildBrowsingContextBootstrap::Url(url);
if kind == ChildFrameOwnerElementKind::Object
&& self.object_fallback_bootstraps.get(&handle) == Some(&bootstrap)
{
return None;
}
Some(bootstrap)
}
fn embedded_content_is_inside_media_element(&self, handle: DomHandle) -> bool {
@@ -259,7 +286,7 @@ impl PageScriptHost {
root: DomHandle,
out: &mut Vec<DomHandle>,
) {
if self.dom_host().is_connected(root) {
if self.dom_host().is_connected(root) && !self.dom_host().has_shadow_root_in_subtree(root) {
out.extend(
self.dom_host()
.child_browsing_context_host_candidate_handles_in_subtree_in_document_order(
@@ -271,8 +298,9 @@ impl PageScriptHost {
if self.is_child_browsing_context_host_handle(root) {
out.push(root);
}
// Disconnected hosts no longer use the connected-tree candidate index.
// Their shadow trees still contain browsing contexts to unload and retire.
// The connected-tree index excludes shadow descendants. Walk their
// hosts as well as disconnected subtrees so every child context is
// discovered on insertion and retired on removal/reinsertion.
if let Some(shadow_root) = self.dom_host().shadow_root_handle(root) {
self.collect_child_browsing_context_host_handles(shadow_root, out);
}
@@ -175,6 +175,7 @@ impl PageScriptHost {
}
match self.child_browsing_context_bootstrap_for_handle(handle) {
Some(attribute_bootstrap) => {
self.object_fallback_bootstraps.remove(&handle);
let existing = self.child_browsing_contexts.get(&handle).cloned();
let is_new = existing.is_none();
let attribute_bootstrap_changed = existing
@@ -778,8 +779,33 @@ impl PageScriptHost {
self.unregister_service_worker_child_client(handle);
}
pub(in crate::native_bridge::context_host) fn enter_object_fallback_state(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
) {
let Some(attribute_bootstrap) = self
.child_browsing_contexts
.get(&handle)
.map(|entry| entry.attribute_bootstrap().clone())
else {
return;
};
Self::drop_child_browsing_context_subtree_with_window_realm(scope, self, handle);
if self.child_browsing_context_host_is_object_element(handle)
&& self
.child_browsing_context_bootstrap_for_handle(handle)
.as_ref()
== Some(&attribute_bootstrap)
{
self.object_fallback_bootstraps
.insert(handle, attribute_bootstrap);
}
}
fn drop_child_browsing_context_handles(&mut self, handles: Vec<DomHandle>) {
for handle in handles {
self.object_fallback_bootstraps.remove(&handle);
let document_handle_before_drop = self.child_browsing_context_document_handle(handle);
let frame_id = self
.child_browsing_contexts
@@ -969,6 +995,8 @@ impl PageScriptHost {
for handle in stale_child_context_handles {
let _ = self.remove_child_browsing_context_entry(handle);
}
self.object_fallback_bootstraps
.retain(|handle, _| live_handles.contains(handle));
self.retain_live_child_window_proxy_records(&live_handles);
self.child_browsing_context_document_handles
.retain(|handle, _| live_handles.contains(handle));
@@ -397,6 +397,7 @@ impl PageScriptHost {
next_scoped_custom_elements_registry_id: 1,
observers: ObserverStore::default(),
child_browsing_contexts: IndexMap::new(),
object_fallback_bootstraps: HashMap::new(),
frame_owner_store,
inert_document_execution_contexts: None,
frame_parser_classic_scripts: FrameParserClassicScriptRunnerStore::default(),
@@ -904,6 +904,10 @@ pub(crate) struct PageScriptHost {
observers: ObserverStore,
// Key order is browsing-context insertion order and therefore frame-tree sibling order.
child_browsing_contexts: IndexMap<DomHandle, ChildBrowsingContextEntry>,
// A failed `data` attribute load keeps an object in fallback until that
// resource selection is invalidated; ordinary context discovery must not
// recreate its nested browsing context in the meantime.
object_fallback_bootstraps: HashMap<DomHandle, ChildBrowsingContextBootstrap>,
frame_owner_store: FrameOwnerStore,
inert_document_execution_contexts:
Option<Box<document_execution_context::InertDocumentExecutionContexts>>,
@@ -1,3 +1,119 @@
#[test]
fn frame_owner_get_svg_document_methods_reject_html_documents_and_enforce_brands() {
let mut vm = new_storage_test_vm("https://frame-owner-get-svg-document.test/");
let result = vm
.eval(
r#"
(() => {
if (!document.documentElement) {
const html = document.createElement('html');
html.appendChild(document.createElement('body'));
document.appendChild(html);
}
const root = document.body || document.documentElement;
const iframe = document.createElement("iframe");
iframe.srcdoc = "<body>iframe child</body>";
const embed = document.createElement("embed");
embed.type = "text/html";
embed.src = "about:blank";
const object = document.createElement("object");
object.type = "text/html";
object.data = "about:blank";
root.appendChild(iframe);
root.appendChild(embed);
root.appendChild(object);
const interfaces = [
[HTMLIFrameElement.prototype, iframe, "HTMLIFrameElement"],
[HTMLEmbedElement.prototype, embed, "HTMLEmbedElement"],
[HTMLObjectElement.prototype, object, "HTMLObjectElement"]
];
const descriptors = interfaces.map(([prototype]) => {
const descriptor = Object.getOwnPropertyDescriptor(prototype, "getSVGDocument");
return {
type: typeof descriptor.value,
name: descriptor.value.name,
length: descriptor.value.length,
writable: descriptor.writable,
enumerable: descriptor.enumerable,
configurable: descriptor.configurable
};
});
const brandErrors = interfaces.map(([prototype], index) => {
try {
prototype.getSVGDocument.call(interfaces[(index + 1) % interfaces.length][1]);
return "accepted";
} catch (error) {
return error.name;
}
});
return JSON.stringify({
descriptors,
iframeIsNull: iframe.getSVGDocument() === null,
embedIsNull: embed.getSVGDocument() === null,
objectIsNull: object.getSVGDocument() === null,
brandErrors,
absentFromBase: !("getSVGDocument" in HTMLElement.prototype)
});
})()
"#,
)
.expect("frame owner getSVGDocument methods should evaluate");
assert_eq!(
result,
r#"{"descriptors":[{"type":"function","name":"getSVGDocument","length":0,"writable":true,"enumerable":true,"configurable":true},{"type":"function","name":"getSVGDocument","length":0,"writable":true,"enumerable":true,"configurable":true},{"type":"function","name":"getSVGDocument","length":0,"writable":true,"enumerable":true,"configurable":true}],"iframeIsNull":true,"embedIsNull":true,"objectIsNull":true,"brandErrors":["TypeError","TypeError","TypeError"],"absentFromBase":true}"#
);
}
#[test]
fn frame_owner_get_svg_document_uses_native_document_content_type() {
let mut vm = new_storage_html_test_vm("https://frame-owner-svg-type.test/");
vm.eval(
r#"
for (const tag of ['iframe', 'embed', 'object']) {
const owner = document.createElement(tag);
owner.id = tag;
if (tag === 'object') owner.data = 'about:blank';
else owner.src = 'about:blank';
document.body.appendChild(owner);
if (owner.getSVGDocument() !== null) throw new Error('HTML document accepted');
}
"#,
)
.expect("frame owner setup should evaluate");
// Simulate the response MIME metadata at a child document commit. Parsing
// and frame navigation are covered separately; this checks the public
// method against native metadata rather than author-visible properties.
{
let mut host = vm._context_host.borrow_mut();
for id in ["iframe", "embed", "object"] {
let owner = host.dom_host().element_handle_by_id(id).unwrap();
let document = host.child_browsing_context_document_handle(owner).unwrap();
host.set_dom_document_content_type_for_handle(document, "image/svg+xml");
}
}
assert_eq!(
vm.eval(
r#"
['iframe', 'embed', 'object'].every(id => {
const owner = document.getElementById(id);
const svg = owner.getSVGDocument();
if (svg === null || svg.contentType !== 'image/svg+xml') return false;
if (id !== 'embed' && svg !== owner.contentDocument) return false;
Object.defineProperty(svg, 'contentType', {value: 'text/html', configurable: true});
return owner.getSVGDocument() === svg;
})
"#
)
.expect("native SVG document metadata should determine the result"),
"true"
);
}
use super::*;
fn read_native_body_for_teardown_test<'s>(
@@ -62,6 +178,7 @@ fn install_pending_response_for_teardown_test(
from_cache: false,
cache_state: Default::default(),
negotiated_http_version: None,
status_text: None,
},
body_source_id,
);
@@ -3255,120 +3372,84 @@ fn same_name_isolated_worlds_are_scoped_to_devtools_session_and_detach() {
);
}
#[test]
fn frame_owner_get_svg_document_methods_reject_html_documents_and_enforce_brands() {
let mut vm = new_storage_test_vm("https://frame-owner-get-svg-document.test/");
let result = vm
.eval(
r#"
(() => {
if (!document.documentElement) {
const html = document.createElement('html');
html.appendChild(document.createElement('body'));
document.appendChild(html);
}
const root = document.body || document.documentElement;
const iframe = document.createElement("iframe");
iframe.srcdoc = "<body>iframe child</body>";
const embed = document.createElement("embed");
embed.type = "text/html";
embed.src = "about:blank";
const object = document.createElement("object");
object.type = "text/html";
object.data = "about:blank";
root.appendChild(iframe);
root.appendChild(embed);
root.appendChild(object);
const interfaces = [
[HTMLIFrameElement.prototype, iframe, "HTMLIFrameElement"],
[HTMLEmbedElement.prototype, embed, "HTMLEmbedElement"],
[HTMLObjectElement.prototype, object, "HTMLObjectElement"]
];
const descriptors = interfaces.map(([prototype]) => {
const descriptor = Object.getOwnPropertyDescriptor(prototype, "getSVGDocument");
return {
type: typeof descriptor.value,
name: descriptor.value.name,
length: descriptor.value.length,
writable: descriptor.writable,
enumerable: descriptor.enumerable,
configurable: descriptor.configurable
};
});
const brandErrors = interfaces.map(([prototype], index) => {
try {
prototype.getSVGDocument.call(interfaces[(index + 1) % interfaces.length][1]);
return "accepted";
} catch (error) {
return error.name;
}
});
return JSON.stringify({
descriptors,
iframeIsNull: iframe.getSVGDocument() === null,
embedIsNull: embed.getSVGDocument() === null,
objectIsNull: object.getSVGDocument() === null,
brandErrors,
absentFromBase: !("getSVGDocument" in HTMLElement.prototype)
});
})()
"#,
)
.expect("frame owner getSVGDocument methods should evaluate");
#[tokio::test]
async fn failed_object_attribute_navigation_enters_fallback_without_recreating_child_context() {
let (object_url, request_rx, release_tx, server) =
spawn_gated_child_document_resource_server(404).await;
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
&object_url.replace("/child.html", "/page"),
&loader,
);
assert_eq!(
result,
r#"{"descriptors":[{"type":"function","name":"getSVGDocument","length":0,"writable":true,"enumerable":true,"configurable":true},{"type":"function","name":"getSVGDocument","length":0,"writable":true,"enumerable":true,"configurable":true},{"type":"function","name":"getSVGDocument","length":0,"writable":true,"enumerable":true,"configurable":true}],"iframeIsNull":true,"embedIsNull":true,"objectIsNull":true,"brandErrors":["TypeError","TypeError","TypeError"],"absentFromBase":true}"#
vm.eval(&format!(
r#"
(() => {{
const root = document.body || document.documentElement || document;
const object = document.createElement('object');
object.type = 'text/html';
object.data = {object_url:?};
globalThis.__failedObjectEvents = [];
object.addEventListener('load', () => __failedObjectEvents.push('load'));
object.addEventListener('error', event => __failedObjectEvents.push(
`error:${{event.isTrusted}}:${{object.contentWindow === null}}`
));
const fallback = document.createElement('span');
fallback.id = 'object-fallback';
fallback.textContent = 'fallback';
object.appendChild(fallback);
root.appendChild(object);
globalThis.__failedObject = object;
return [object.contentWindow !== null, window.length].join('|');
}})()
"#
))
.expect("failed object setup should evaluate"),
"true|1",
"the object should expose its initial child browsing context while loading"
);
}
#[test]
fn frame_owner_get_svg_document_uses_native_document_content_type() {
let mut vm = new_storage_html_test_vm("https://frame-owner-svg-type.test/");
vm.eval(
r#"
for (const tag of ['iframe', 'embed', 'object']) {
const owner = document.createElement(tag);
owner.id = tag;
if (tag === 'object') owner.data = 'about:blank';
else owner.src = 'about:blank';
document.body.appendChild(owner);
if (owner.getSVGDocument() !== null) throw new Error('HTML document accepted');
}
"#,
run_page_realm_prerequisite_then_expected_child_frame_semantic_turn(
&mut vm,
&loader,
ChildFrameSemanticTurnKind::NavigationCommit,
"object attribute navigation should start from its frame-lane commit",
)
.expect("frame owner setup should evaluate");
.await;
request_rx
.await
.expect("failed object document request should arrive");
release_tx
.send(())
.expect("release failed object document response");
wait_for_one_page_resource_completion_selected_task_executor_test_turn(
&mut vm,
&loader,
"failed object document completion",
)
.await;
// Simulate the response MIME metadata at a child document commit. Parsing
// and frame navigation are covered separately; this checks the public
// method against native metadata rather than author-visible properties.
{
let mut host = vm._context_host.borrow_mut();
for id in ["iframe", "embed", "object"] {
let owner = host.dom_host().element_handle_by_id(id).unwrap();
let document = host.child_browsing_context_document_handle(owner).unwrap();
host.set_dom_document_content_type_for_handle(document, "image/svg+xml");
}
}
assert_eq!(
vm.eval(
r#"
['iframe', 'embed', 'object'].every(id => {
const owner = document.getElementById(id);
const svg = owner.getSVGDocument();
if (svg === null || svg.contentType !== 'image/svg+xml') return false;
if (id !== 'embed' && svg !== owner.contentDocument) return false;
Object.defineProperty(svg, 'contentType', {value: 'text/html', configurable: true});
return owner.getSVGDocument() === svg;
JSON.stringify({
contentWindowIsNull: __failedObject.contentWindow === null,
contentDocumentIsNull: __failedObject.contentDocument === null,
childCount: window.length,
fallbackConnected: document.getElementById('object-fallback').isConnected,
events: __failedObjectEvents
})
"#
"#,
)
.expect("native SVG document metadata should determine the result"),
"true"
.expect("failed object fallback state should evaluate"),
r#"{"contentWindowIsNull":true,"contentDocumentIsNull":true,"childCount":0,"fallbackConnected":true,"events":["error:true:true"]}"#
);
assert_eq!(
vm._context_host.borrow().child_browsing_context_count(),
0,
"contentWindow and contentDocument getters must not recreate a failed object context"
);
server.await.expect("failed object server should finish");
}
async fn commit_opaque_child_for_test(vm: &mut StandaloneScriptVmHarness, element_id: &str) -> i64 {
+78 -2
View File
@@ -1509,6 +1509,65 @@ async fn spawn_gated_media_resource_server(
)
}
async fn spawn_gated_child_document_resource_server(
status: u16,
) -> (
String,
tokio::sync::oneshot::Receiver<String>,
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<()>,
) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind gated child document resource server");
let addr = listener
.local_addr()
.expect("gated child document resource server addr");
let (request_tx, request_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut stream, _) = listener
.accept()
.await
.expect("accept gated child document resource request");
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
loop {
let read = stream
.read(&mut buffer)
.await
.expect("read gated child document resource request");
if read == 0 {
break;
}
request.extend_from_slice(&buffer[..read]);
if request.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
let _ = request_tx.send(String::from_utf8_lossy(&request).into_owned());
let _ = release_rx.await;
let (status_text, body) = if status == 200 {
("OK", "<!doctype html><p>child document</p>")
} else {
("Not Found", "<!doctype html><p>missing child document</p>")
};
let response = format!(
"HTTP/1.1 {status} {status_text}\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
});
(
format!("http://{addr}/child.html"),
request_rx,
release_tx,
server,
)
}
async fn spawn_gated_image_resource_server(
status: u16,
) -> (
@@ -2387,7 +2446,6 @@ mod webidl_fetch;
mod idb_object_store_native_receivers;
mod exception_constructor_strings;
mod webidl_receivers;
mod webidl_trusted_types;
mod websocket;
@@ -2457,7 +2515,6 @@ mod streams_sync_protocol;
mod performance_user_timing;
mod rtc_encoded_frames;
mod xml_serializer_receivers;
mod hyperlink_audit_owner;
@@ -2473,3 +2530,22 @@ mod svg_legacy_rectangle_contracts;
mod indexed_db_prototype_handlers;
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
}