fix(dom): route popup document streams through shared bindings

Popup Documents installed their own open/write/writeln/close methods, bypassing
Document receiver checks, XML preconditions, and Trusted Types conversion.
Borrowing Document.prototype methods could instead enter the main document's
replacement path and clear the opener.

Inherit the existing Document bindings and route operations by the receiver's
current popup owner. Select its Window policy even when the wrapper shares the
opener's V8 realm, and convert write arguments before mutating content.

Snapshot delivered meta CSP when window.open or a hyperlink creates a popup,
and seed inherited policies before importing its markup. This keeps receiver
policy checks independent of later opener changes without losing inherited
requirements or the popup's own meta policies.

Cover native receiver checks, XML receivers, borrowed methods, opener ownership,
Trusted Types isolation and inheritance, and load callback conversion ordering.
This commit is contained in:
ldm0
2026-11-22 02:01:53 +08:00
parent 6473a4a6c6
commit 064a28fc7a
9 changed files with 411 additions and 153 deletions
@@ -576,21 +576,18 @@ fn window_open_entered_policy_container<'s>(
host: &crate::native_bridge::PageScriptHost,
entered_window: v8::Local<'s, v8::Object>,
) -> DocumentPolicyContainer {
// Use the same creator Window that supplies the opener and its origin;
// ambient child markers can be absent in a child Document's native realm.
if let Some(handle) = window_receiver_child_handle(scope, entered_window)
&& let Some(policy_container) =
host.child_browsing_context_policy_container_snapshot(handle)
{
return policy_container;
}
if let Some(popup_id) =
// Policy inheritance follows the same concrete creator Window as opener/origin.
let owner = if let Some(handle) = window_receiver_child_handle(scope, entered_window) {
crate::native_bridge::OwnerDispatchScope::Child(handle)
} else if let Some(popup_id) =
crate::native_bridge::lightweight_popup_id_from_window(scope, entered_window)
&& let Some(policy_container) = host.lightweight_popup_policy_container(popup_id)
{
return policy_container.clone();
}
host.document_policy_container().clone()
crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id)
} else {
crate::native_bridge::OwnerDispatchScope::Top
};
host.document_policy_container_for_inheritance(owner)
.unwrap_or_else(|| host.document_policy_container().clone())
}
fn window_open_entered_window<'s>(
+4
View File
@@ -373,6 +373,7 @@ pub(crate) fn parse_browsing_context_document_projection_from_source<'s>(
content_type: Option<&str>,
character_set: Option<&str>,
html_parser: HtmlParser,
inherited_meta_policies: &[String],
) -> Option<v8::Local<'s, v8::Object>> {
let source = preserve_decoded_bom_only_browsing_context_body(source, content_type);
let (parsed, kind) =
@@ -384,6 +385,7 @@ pub(crate) fn parse_browsing_context_document_projection_from_source<'s>(
content_type,
character_set,
true,
Some(inherited_meta_policies),
)
}
@@ -451,6 +453,7 @@ fn build_detached_document_with_content_type<'s>(
content_type,
None,
false,
None,
)
}
@@ -480,6 +483,7 @@ fn build_detached_document_from_dom_host_with_content_type<'s>(
content_type,
character_set,
false,
None,
)
}
@@ -132,36 +132,6 @@ enum PopupDomContentLoadedState {
Dispatched,
}
#[derive(WebApiObject)]
#[webapi(plain)]
struct LightweightPopupDocumentStreamMethodsDeclaration<'scope> {
popup_id: v8::Local<'scope, v8::BigInt>,
#[webapi(
method,
callback = lightweight_popup_document_open_callback,
data = self.popup_id
)]
open: (),
#[webapi(
method,
callback = lightweight_popup_document_write_callback,
data = self.popup_id
)]
write: (),
#[webapi(
method,
callback = lightweight_popup_document_writeln_callback,
data = self.popup_id
)]
writeln: (),
#[webapi(
method,
callback = lightweight_popup_document_close_callback,
data = self.popup_id
)]
close: (),
}
#[derive(Default, WebApiObject)]
#[webapi(plain)]
struct LightweightPopupWindowMethodsDeclaration {
@@ -1161,6 +1131,9 @@ impl PageScriptHost {
crate::parser::HtmlParser::with_scripting_enabled(
self.lightweight_popup_scripting_enabled(popup_id),
),
&initial_document_state
.policy_container
.inherited_meta_content_security_policies,
)
{
if let Some(document_handle) =
@@ -2665,6 +2638,9 @@ impl PageScriptHost {
crate::parser::HtmlParser::with_scripting_enabled(
self.lightweight_popup_scripting_enabled(popup_id),
),
self.lightweight_popup_policy_container(popup_id)
.map(|policy| policy.inherited_meta_content_security_policies.as_slice())
.unwrap_or(&[]),
)
else {
return;
@@ -3618,6 +3594,9 @@ impl PageScriptHost {
crate::parser::HtmlParser::with_scripting_enabled(
self.lightweight_popup_scripting_enabled(popup_id),
),
&source
.policy_container
.inherited_meta_content_security_policies,
)?;
let host_ptr = self as *mut PageScriptHost;
let document_base_url = lightweight_popup_parsed_document_base_url(
@@ -5545,19 +5524,6 @@ fn sync_lightweight_popup_document_window_slots<'s>(
set_object_slot(scope, document, "referrer", referrer.into());
}
set_document_associated_window(scope, document, window);
install_lightweight_popup_document_stream_methods(scope, document, window);
}
fn install_lightweight_popup_document_stream_methods<'s>(
scope: &mut v8::PinScope<'s, '_>,
document: v8::Local<'s, v8::Object>,
window: v8::Local<'s, v8::Object>,
) {
let Some(popup_id) = lightweight_popup_id_from_window(scope, window) else {
return;
};
let data = v8::BigInt::new_from_u64(scope, popup_id);
let _ = LightweightPopupDocumentStreamMethodsDeclaration::new(data).initialize(scope, document);
}
fn install_lightweight_popup_get_computed_style<'s>(
@@ -5709,17 +5675,6 @@ fn lightweight_popup_location_href<'s>(
Url::parse(&href).ok()
}
fn lightweight_popup_document_handle_for_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
document: v8::Local<'s, v8::Object>,
) -> Option<(*mut PageScriptHost, DomHandle)> {
let host_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = crate::native_bridge::document::detached_native_handle_for_runtime(
scope, host_ptr, document,
)?;
Some((host_ptr, handle))
}
fn lightweight_popup_document_write_session_active<'s>(
scope: &mut v8::PinScope<'s, '_>,
document: v8::Local<'s, v8::Object>,
@@ -5746,15 +5701,15 @@ fn set_lightweight_popup_document_write_session<'s>(
);
}
fn lightweight_popup_document_open_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let document = args.this();
if let Some((host_ptr, document_handle)) =
lightweight_popup_document_handle_for_callback(scope, document)
{
impl PageScriptHost {
pub(in crate::native_bridge) fn open_lightweight_popup_document_stream<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
host_ptr: *mut PageScriptHost,
document_handle: DomHandle,
document: v8::Local<'s, v8::Object>,
) {
debug_assert!(std::ptr::eq(host_ptr, self));
crate::native_bridge::document::set_detached_html_document_body_html(
scope,
host_ptr,
@@ -5765,80 +5720,37 @@ fn lightweight_popup_document_open_callback<'s>(
.reset_meta_content_security_policy_processing_for_document(document_handle);
set_lightweight_popup_document_write_session(scope, document, true);
}
rv.set(document.into());
}
fn lightweight_popup_document_write_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
rv: v8::ReturnValue<'_, v8::Value>,
) {
lightweight_popup_document_write_or_writeln_callback(scope, args, rv, false);
}
fn lightweight_popup_document_writeln_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
rv: v8::ReturnValue<'_, v8::Value>,
) {
lightweight_popup_document_write_or_writeln_callback(scope, args, rv, true);
}
fn lightweight_popup_document_write_or_writeln_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
append_newline: bool,
) {
let document = args.this();
let Some((host_ptr, document_handle)) =
lightweight_popup_document_handle_for_callback(scope, document)
else {
rv.set_undefined();
return;
};
let popup_id = lightweight_popup_id_from_value(scope, args.data());
let writing_during_load = popup_id.is_some_and(|popup_id| {
active_lightweight_popup_id(scope) == Some(popup_id)
&& !lightweight_popup_document_write_session_active(scope, document)
});
if writing_during_load {
crate::native_bridge::document::set_detached_html_document_body_html(
pub(in crate::native_bridge) fn write_lightweight_popup_document_stream<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
host_ptr: *mut PageScriptHost,
popup_id: u64,
document_handle: DomHandle,
document: v8::Local<'s, v8::Object>,
html: &str,
) {
debug_assert!(std::ptr::eq(host_ptr, self));
let writing_during_load = active_lightweight_popup_id(scope) == Some(popup_id)
&& !lightweight_popup_document_write_session_active(scope, document);
if writing_during_load {
self.open_lightweight_popup_document_stream(scope, host_ptr, document_handle, document);
}
crate::native_bridge::document::append_detached_html_document_body_html(
scope,
host_ptr,
document_handle,
"",
html,
);
unsafe { &*host_ptr }
.reset_meta_content_security_policy_processing_for_document(document_handle);
set_lightweight_popup_document_write_session(scope, document, true);
}
let mut html = String::new();
for index in 0..args.length() {
let Some(value) = args.get(index).to_string(scope) else {
return;
};
html.push_str(&value.to_rust_string_lossy(scope));
}
if append_newline {
html.push('\n');
}
crate::native_bridge::document::append_detached_html_document_body_html(
scope,
host_ptr,
document_handle,
&html,
);
rv.set_undefined();
}
fn lightweight_popup_document_close_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
set_lightweight_popup_document_write_session(scope, args.this(), false);
rv.set_undefined();
pub(in crate::native_bridge) fn close_lightweight_popup_document_stream<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
document: v8::Local<'s, v8::Object>,
) {
set_lightweight_popup_document_write_session(scope, document, false);
}
}
fn lightweight_popup_javascript_url_callback<'s>(
@@ -189,16 +189,23 @@ impl PageScriptHost {
pub(crate) fn document_policy_container_for_inheritance(
&self,
owner: OwnerDispatchScope,
) -> Option<crate::document_runtime::DocumentPolicyContainer> {
) -> Option<DocumentPolicyContainer> {
let snapshot = self.owner_document_policy_snapshot(owner)?;
let mut policy = snapshot.policy_container;
policy
.content_security_policy_self_url
.get_or_insert(snapshot.document_url);
if let Some(document) = snapshot.document_handle {
// Capture the creator's effective meta policy at Document creation.
// Subsequent mutations of the creator must not change the child.
// Capture the creator policy before its later mutations.
policy.referrer_policy =
crate::context_bootstrap::document_referrer_policy_for_native_document(
self, document,
);
// Meta policies are delivered separately from response headers.
// Capture their current list so later creator mutations cannot
// change the new Document's policy container.
policy.inherited_meta_content_security_policies = unsafe { &*self.runtime }
.meta_content_security_policy_strings_for_document(document);
}
Some(policy)
}
@@ -301,7 +301,7 @@ pub(crate) fn build_detached_document_object_from_dom_host<'s>(
parsed: DomHost,
) -> Option<v8::Local<'s, v8::Object>> {
build_detached_document_object_from_dom_host_with_content_type(
scope, kind, parsed, None, None, false,
scope, kind, parsed, None, None, false, None,
)
}
@@ -312,6 +312,7 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
content_type: Option<&str>,
character_set: Option<&str>,
preserve_parser_frames: bool,
inherited_meta_policies: Option<&[String]>,
) -> Option<v8::Local<'s, v8::Object>> {
let url = detached_document_url(&parsed);
let quirks_mode = parsed.dom().document()?.quirks_mode();
@@ -320,6 +321,14 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
let character_set = character_set.unwrap_or(parsed.dom().document()?.character_set());
let allow_declarative_shadow_roots = parsed.dom().document()?.allow_declarative_shadow_roots();
let document = new_detached_document_shell(scope, kind, content_type, url, scripting_enabled)?;
if let Some(policies) = inherited_meta_policies {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let document_handle = detached_native_handle(scope, document)?;
// Importing the parsed tree can deliver its own meta policies. Seed
// inherited policies first so both sets retain their delivery order.
unsafe { &*runtime_ptr }
.initialize_inherited_meta_content_security_policies(document_handle, policies);
}
set_detached_document_parse_metadata(
scope,
document,
@@ -85,7 +85,13 @@ fn node_document_write_or_writeln_callback<'s>(
};
let context = crate::native_bridge::node_relevant_context(scope, args.this())
.unwrap_or_else(|| scope.get_current_context());
let global = context.global(scope);
let runtime = unsafe { &*runtime_ptr };
// Lightweight popup wrappers share a V8 realm with their opener, but
// their Window owns an independent policy container.
let global = runtime
.lightweight_popup_id_for_document_handle(handle)
.and_then(|popup_id| runtime.lightweight_popup_window(scope, popup_id))
.unwrap_or_else(|| context.global(scope));
let requirements = unsafe { &*runtime_ptr }
.trusted_types_for_script_requirements_for_global(scope, global);
let Some(compliant) = crate::context_bootstrap::trusted_type_string_or_throw(
@@ -122,6 +128,20 @@ fn node_document_write_or_writeln_callback<'s>(
);
return;
}
if let Some(popup_id) =
unsafe { &*runtime_ptr }.lightweight_popup_id_for_document_handle(handle)
{
unsafe { &mut *runtime_ptr }.write_lightweight_popup_document_stream(
scope,
runtime_ptr,
popup_id,
handle,
args.this(),
&html,
);
rv.set_undefined();
return;
}
if let Some(child_handle) =
unsafe { &*runtime_ptr }.child_browsing_context_host_for_document_handle(handle)
{
@@ -273,6 +293,19 @@ pub(in crate::native_bridge) fn node_document_open_callback<'s>(
rv.set(args.this().into());
return;
}
if unsafe { &*runtime_ptr }
.lightweight_popup_id_for_document_handle(handle)
.is_some()
{
unsafe { &mut *runtime_ptr }.open_lightweight_popup_document_stream(
scope,
runtime_ptr,
handle,
args.this(),
);
rv.set(args.this().into());
return;
}
if let Some(child_handle) =
unsafe { &*runtime_ptr }.child_browsing_context_host_for_document_handle(handle)
{
@@ -508,6 +541,15 @@ pub(in crate::native_bridge) fn node_document_close_callback<'s>(
);
return;
}
if unsafe { &*runtime_ptr }
.lightweight_popup_id_for_document_handle(handle)
.is_some()
{
unsafe { &mut *runtime_ptr }
.close_lightweight_popup_document_stream(scope, args.this());
rv.set_undefined();
return;
}
if let Some(child_handle) =
unsafe { &*runtime_ptr }.child_browsing_context_host_for_document_handle(handle)
{
@@ -167,11 +167,14 @@ fn element_popup_creator<'s>(
let document = runtime.dom_host().owner_document_handle(source_handle)?;
let base_url = runtime.document_base_url_for_handle(document);
let document_url = runtime.document_url_for_handle(document);
let policy_container = runtime.document_policy_container_for_inheritance(
runtime.owner_dispatch_scope_for_node(source_handle)?,
)?;
if document == runtime.document_handle() {
return Some(ElementPopupCreator {
opener: scope.get_current_context().global(scope),
base_url,
policy_container: runtime.document_policy_container().clone(),
policy_container,
document_url,
});
}
@@ -189,9 +192,7 @@ fn element_popup_creator<'s>(
return Some(ElementPopupCreator {
opener: runtime.lightweight_popup_window(scope, popup_id)?,
base_url,
policy_container: runtime
.lightweight_popup_policy_container(popup_id)?
.clone(),
policy_container,
document_url,
});
}
@@ -199,7 +200,7 @@ fn element_popup_creator<'s>(
Some(ElementPopupCreator {
opener: runtime.existing_child_browsing_context_window_wrapper(scope, frame)?,
base_url,
policy_container: runtime.child_browsing_context_policy_container_snapshot(frame)?,
policy_container,
document_url,
})
}
@@ -71,6 +71,7 @@ mod platform_identity;
mod pointer_capture;
mod pointer_lock;
mod pointing_event_init;
mod popup_document_stream;
mod popup_hyperlinks;
mod promise_rejection;
mod request_init;
@@ -0,0 +1,285 @@
use super::*;
#[test]
fn popup_document_stream_methods_use_native_document_receiver_checks() {
let mut vm = new_storage_test_vm("https://popup-document-stream-brand.test/");
let result = vm
.eval(
r#"
(() => {
const w = open();
try {
const d = w.document;
const failures = [];
for (const name of ['open','write','writeln','close']) {
if (Object.hasOwn(d, name) || d[name] !== Object.getPrototypeOf(d)[name]) {
failures.push([name, 'binding']);
}
let conversions = 0, traps = 0;
const value = {toString() { ++conversions; return 'text'; }};
const revoked = Proxy.revocable(d, {});
revoked.revoke();
const proxy = new Proxy(d, {get(target, key, receiver) {
++traps; return Reflect.get(target, key, receiver);
}});
for (const receiver of [{}, Object.create(d), proxy, revoked.proxy]) {
let error;
try { d[name].call(receiver, value); } catch (caught) { error = caught; }
if (!(error instanceof TypeError) || conversions !== 0 || traps !== 0) {
failures.push([name, String(error), conversions, traps]);
}
}
}
return JSON.stringify(failures);
} finally { w.close(); }
})()
"#,
)
.expect("popup stream methods should use the shared Document binding");
assert_eq!(result, "[]");
}
#[test]
fn popup_document_stream_methods_reject_xml_receivers_without_mutation() {
let mut vm = new_storage_test_vm("https://popup-document-stream-xml.test/");
let result = vm
.eval(
r#"
(() => {
const w = open();
try {
const failures = [];
for (const name of ['open','write','writeln','close']) {
const doc = new DOMParser().parseFromString('<root/>', 'text/xml');
let error;
try { w.document[name].call(doc, 'text'); } catch (caught) { error = caught; }
if (!(error instanceof DOMException) || error.name !== 'InvalidStateError' ||
new XMLSerializer().serializeToString(doc) !== '<root/>') {
failures.push([name, String(error)]);
}
}
return JSON.stringify(failures);
} finally { w.close(); }
})()
"#,
)
.expect("borrowed popup stream methods should apply the XML document check");
assert_eq!(result, "[]");
}
#[test]
fn borrowed_popup_document_stream_methods_preserve_the_opener_document_owner() {
let mut vm = new_storage_test_vm("https://popup-document-stream-owner.test/");
let owner = vm.current_main_document_task_owner();
let result = vm
.eval(
r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.textContent = 'opener';
const beforeReady = document.readyState;
const first = open(), second = open();
try {
first.document.body.textContent = 'first';
second.document.body.textContent = 'second';
const target = second.document;
const same = Document.prototype.open.call(target) === target;
first.document.write.call(target, '<p>replacement</p>');
first.document.writeln.call(target, 'tail');
first.document.close.call(target);
return JSON.stringify({same, sameDocument:second.document === target,
first:first.document.body.textContent, second:target.body.textContent,
openerBody:document.body === body && body.textContent,
openerRoot:document.documentElement === root,
openerReady:document.readyState === beforeReady});
} finally { first.close(); second.close(); }
})()
"#,
)
.expect("borrowed methods must dispatch to the receiver's popup Document");
assert_eq!(
result,
r#"{"same":true,"sameDocument":true,"first":"first","second":"replacementtail\n","openerBody":"opener","openerRoot":true,"openerReady":true}"#
);
assert_eq!(vm.current_main_document_task_owner(), owner);
}
#[test]
fn popup_document_write_uses_its_own_trusted_types_requirements() {
let mut vm = new_storage_test_vm("https://popup-document-stream-policy.test/");
vm.eval("globalThis.__unprotectedStreamPopup = open(); 'ready'")
.expect("create popup before the opener requires TrustedHTML");
vm.set_response_content_security_policies(&["require-trusted-types-for 'script'".to_owned()]);
let result = vm
.eval(
r#"
(() => {
const protectedPopup = open();
try {
const plain = __unprotectedStreamPopup.document;
const guarded = protectedPopup.document;
Document.prototype.write.call(plain, 'plain');
let blocked;
try { guarded.write('blocked'); } catch (error) { blocked = error.name; }
const untouched = guarded.body.textContent;
const policy = trustedTypes.createPolicy('popup-stream', {createHTML:value => value});
guarded.writeln(policy.createHTML('one'), policy.createHTML('two'));
return JSON.stringify({plain:plain.body.textContent, blocked, untouched,
trusted:guarded.body.textContent});
} finally { protectedPopup.close(); __unprotectedStreamPopup.close(); }
})()
"#,
)
.expect("popup stream policy must follow the receiver instead of its wrapper realm");
assert_eq!(
result,
r#"{"plain":"plain","blocked":"TypeError","untouched":"","trusted":"onetwo\n"}"#
);
}
#[tokio::test]
async fn popup_document_write_load_callbacks_convert_before_mutation_and_follow_the_receiver() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
let mut vm = new_parsed_page_task_executor_test_vm(
"https://popup-document-stream-load.test/",
"<!doctype html><body>opener</body>",
&loader,
);
vm.eval(
r#"
window.__streamMethodPopup = open();
window.__streamResults = [];
window.__streamPopups = ['conversion','borrowed'].map(mode => {
const html = `<!doctype html><script>
onload = () => {
if (${JSON.stringify(mode)} === 'conversion') {
const sentinel = {};
let caught;
try { document.write({toString() { throw sentinel; }}); } catch (error) { caught = error; }
opener.__streamResults.push(['conversion', caught === sentinel, document.body.textContent]);
} else {
opener.__streamMethodPopup.document.writeln.call(document, 'replacement');
opener.__streamResults.push(['borrowed', document.body.textContent]);
}
};
</script><body>original`;
return open(URL.createObjectURL(new Blob([html], {type:'text/html'})));
});
"#,
)
.expect("popup stream load fixtures should open");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(__streamResults.length)",
"2",
"popup document.write receiver and conversion",
)
.await;
assert_eq!(
vm.eval("JSON.stringify(__streamResults.sort((a,b) => a[0].localeCompare(b[0])))")
.unwrap(),
r#"[["borrowed","replacement\n"],["conversion",true,"original"]]"#
);
assert_eq!(vm.eval("document.body.textContent").unwrap(), "opener");
vm.eval("__streamPopups.forEach(w => w.close()); __streamMethodPopup.close();")
.expect("close popup stream fixtures");
}
#[test]
fn popup_document_stream_policy_inherits_delivered_meta_at_creation() {
let mut vm = new_storage_test_vm("https://popup-document-stream-meta.test/");
vm.eval(
r#"
const root = document.appendChild(document.createElement('html'));
const head = root.appendChild(document.createElement('head'));
const body = root.appendChild(document.createElement('body'));
globalThis.__beforeMetaPopup = open();
const meta = head.appendChild(document.createElement('meta'));
meta.httpEquiv = 'Content-Security-Policy';
meta.content = "require-trusted-types-for 'script'";
globalThis.__afterMetaPopup = open();
const anchor = body.appendChild(document.createElement('a'));
anchor.href = 'about:blank';
anchor.target = 'meta-anchor-popup';
anchor.click();
meta.remove();
"#,
)
.expect("create popups on either side of meta policy delivery");
let activation = vm
.take_pending_popup_activations()
.into_iter()
.find(|activation| activation.target_name() == "meta-anchor-popup")
.expect("anchor should create a popup");
let popup_id = activation.popup_id().expect("native popup id");
vm.with_default_context_scope(|scope, host_ptr| {
let popup = unsafe { &*host_ptr }
.lightweight_popup_window(scope, popup_id)
.expect("anchor popup Window");
let global = scope.get_current_context().global(scope);
let key = v8::String::new(scope, "__anchorMetaPopup").unwrap();
assert_eq!(global.set(scope, key.into(), popup.into()), Some(true));
Ok(())
})
.unwrap();
let result = vm
.eval(
r#"
(() => {
const popups = [__beforeMetaPopup, __afterMetaPopup, __anchorMetaPopup];
try {
return JSON.stringify(popups.map(w => {
let error = null;
try { w.document.write('plain'); } catch (caught) { error = caught.name; }
return [error, w.document.body.textContent];
}));
} finally { popups.forEach(w => w.close()); }
})()
"#,
)
.expect("meta inheritance should preserve each popup's own policy snapshot");
assert_eq!(
result,
r#"[[null,"plain"],["TypeError",""],["TypeError",""]]"#
);
}
#[tokio::test]
async fn nested_popup_document_stream_inherits_its_creator_meta_policy() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
let mut vm = new_parsed_page_task_executor_test_vm(
"https://popup-document-stream-nested-meta.test/",
"<!doctype html><body>opener</body>",
&loader,
);
vm.eval(
r#"
window.__nestedMetaResult = 'pending';
const html = `<!doctype html><head>
<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
<script>
onload = () => {
const child = open();
let error = null;
try { child.document.write('blocked'); } catch (caught) { error = caught.name; }
opener.__nestedMetaResult = JSON.stringify([error, child.document.body.textContent]);
child.close();
};
</script></head><body>popup`;
window.__nestedMetaCreator = open(URL.createObjectURL(new Blob([html], {type:'text/html'})));
"#,
)
.expect("create popup with its own meta policy");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"__nestedMetaResult",
r#"["TypeError",""]"#,
"nested popup meta policy inheritance",
)
.await;
assert_eq!(vm.eval("document.body.textContent").unwrap(), "opener");
vm.eval("__nestedMetaCreator.close();").unwrap();
}