diff --git a/moli-renderer-v8/src/dom_parser.rs b/moli-renderer-v8/src/dom_parser.rs index 563467c94dc..70aca4cf51d 100644 --- a/moli-renderer-v8/src/dom_parser.rs +++ b/moli-renderer-v8/src/dom_parser.rs @@ -188,6 +188,13 @@ pub(super) fn dom_parser_parse_from_string_callback<'s>( unsafe { &mut *runtime_ptr } .set_inert_document_execution_context(handle, execution_context); } + if let Some(source_document) = crate::util::node_wrapper_from_handle(scope, document_handle) { + crate::native_bridge::document::inherit_detached_document_origin( + scope, + obj, + source_document, + ); + } rv.set(obj.into()); } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs index 94aaaeac401..96599a2f9fd 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs @@ -349,12 +349,13 @@ fn initialize_child_document_context<'s>( } impl PageScriptHost { - pub(in crate::native_bridge) fn write_child_document_stream( + pub(in crate::native_bridge) fn write_child_document_stream<'s>( &mut self, - scope: &mut v8::PinScope<'_, '_>, + scope: &mut v8::PinScope<'s, '_>, host_ptr: *mut PageScriptHost, child_handle: DomHandle, document_handle: DomHandle, + document: v8::Local<'s, v8::Object>, chunk: String, ) { debug_assert!(std::ptr::eq(host_ptr, self)); @@ -386,6 +387,11 @@ impl PageScriptHost { } } } else { + if host.has_document_unload_counter(document_handle) + || !host.check_document_open_origin(scope, document) + { + return; + } let entry_document = host.document_open_entry_document(scope); let Some(context) = host.begin_child_document_stream_replacement( scope, diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs index 9c9277f2515..32c47dff9a7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -612,6 +612,7 @@ impl PageScriptHost { next_lightweight_popup_classic_script_load_id: 0, lightweight_popup_browsing_contexts: HashMap::new(), lightweight_popup_document_handles: HashMap::new(), + lightweight_popup_document_origins: HashMap::new(), pending_lightweight_popup_document_loads: HashMap::new(), pending_lightweight_popup_classic_script_loads: HashMap::new(), completed_popup_javascript_url_parsers: Vec::new(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index c3a2864129e..ce27c9c2b17 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -1138,6 +1138,10 @@ pub(crate) struct PageScriptHost { lightweight_popup_browsing_contexts: HashMap, lightweight_popup_document_handles: HashMap, + // Popup Documents share a concrete realm with the opener. Keep their own + // origins for as long as their native Document handles can be retained. + lightweight_popup_document_origins: + HashMap, pending_lightweight_popup_document_loads: HashMap, pending_lightweight_popup_classic_script_loads: diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index 9fe0048edab..7cf593c5ff2 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -3285,6 +3285,10 @@ impl PageScriptHost { .mark_subtree_connected_preserving_owner_document(document_handle); self.lightweight_popup_document_handles .insert(document_handle, popup_id); + if let Some(origin) = self.lightweight_popup_access_origin(popup_id) { + self.lightweight_popup_document_origins + .insert(document_handle, origin); + } if let Some(current_document) = self.lightweight_popup_document_record_mut(popup_id) { current_document.handle = Some(document_handle); } diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups/document_stream.rs b/moli-renderer-v8/src/native_bridge/context_host/popups/document_stream.rs index 31ad0a3a144..53fbdf5d93a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups/document_stream.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups/document_stream.rs @@ -231,21 +231,22 @@ impl PageScriptHost { }); } - pub(in crate::native_bridge) fn write_lightweight_popup_document_stream( + pub(in crate::native_bridge) fn write_lightweight_popup_document_stream<'s>( &mut self, - scope: &mut v8::PinScope<'_, '_>, + scope: &mut v8::PinScope<'s, '_>, host_ptr: *mut PageScriptHost, document_handle: DomHandle, + document: v8::Local<'s, v8::Object>, html: &str, ) { let Some(popup_id) = self.lightweight_popup_id_for_document_handle(document_handle) else { return; }; - if self.has_ignore_destructive_writes_counter(document_handle) { - return; - } if self.popup_document_stream_insertion(popup_id).is_none() { - if self.has_document_unload_counter(document_handle) { + if self.has_document_unload_counter(document_handle) + || self.has_ignore_destructive_writes_counter(document_handle) + || !self.check_document_open_origin(scope, document) + { return; } self.open_lightweight_popup_document_stream(scope, host_ptr, document_handle); diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs index 92b0d7a427a..69c78eeb868 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs @@ -198,6 +198,61 @@ impl PageScriptHost { )) } + pub(in crate::native_bridge) fn document_has_same_origin_as_entry<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + document: v8::Local<'s, v8::Object>, + ) -> bool { + let document = + crate::native_bridge::document::document_origin_source_object(scope, document); + let Ok((host, handle)) = + crate::native_bridge::node::node_runtime_and_handle_from_object_or_detached( + scope, document, + ) + else { + return false; + }; + if !std::ptr::eq(host, self) { + return false; + } + let origin = self + .lightweight_popup_document_origins + .get(&handle) + .cloned() + .or_else(|| { + let dispatch = if handle == self.document_handle() { + OwnerDispatchScope::Top + } else { + OwnerDispatchScope::Child( + self.child_browsing_context_host_for_document_handle(handle)?, + ) + }; + self.window_access_origin_for_dispatch_scope(dispatch) + }) + .or_else(|| { + // Windowless and retained Documents keep their creating realm's + // origin even after its execution registration has retired. + let context = document.get_creation_context(scope)?; + context + .get_slot::() + .map(|security| security.origin.clone()) + }); + let entry_origin = match crate::native_bridge::active_lightweight_popup_id(scope) { + Some(popup_id) => self.lightweight_popup_window_access_origin(popup_id), + None => { + // Borrowed functions run in their callee realm, but HTML checks + // the entry global's Document, including when entered by a microtask. + let context = scope.get_entered_or_microtask_context(); + context + .get_slot::() + .map(|security| security.origin.clone()) + } + }; + origin + .zip(entry_origin) + .is_some_and(|(origin, entry)| origin.has_same_origin(&entry)) + } + pub(crate) fn install_window_context_security_origin( &self, scope: &mut v8::PinScope<'_, '_, ()>, diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rs index 0a1b7bfb16e..937926ed365 100644 --- a/moli-renderer-v8/src/native_bridge/document.rs +++ b/moli-renderer-v8/src/native_bridge/document.rs @@ -714,7 +714,7 @@ fn document_receiver_runtime_and_handle<'s>( Some((runtime_ptr, handle)) } -fn document_origin_source_object<'s>( +pub(in crate::native_bridge) fn document_origin_source_object<'s>( scope: &mut v8::PinScope<'s, '_>, document: v8::Local<'s, v8::Object>, ) -> v8::Local<'s, v8::Object> { diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs index 955d359f9b2..3f44ee371d9 100644 --- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs @@ -145,6 +145,7 @@ fn node_document_write_or_writeln_callback<'s>( scope, runtime_ptr, handle, + args.this(), &html, ); rv.set_undefined(); @@ -158,6 +159,7 @@ fn node_document_write_or_writeln_callback<'s>( runtime_ptr, child_handle, handle, + args.this(), html, ); rv.set_undefined(); @@ -165,11 +167,17 @@ fn node_document_write_or_writeln_callback<'s>( } if !document_has_browsing_context(unsafe { &*runtime_ptr }, handle) { let stream_was_open = unsafe { &*runtime_ptr }.has_windowless_document_parser(handle); - if !stream_was_open && unsafe { &*runtime_ptr }.has_document_unload_counter(handle) { + if !stream_was_open + && (unsafe { &*runtime_ptr }.has_document_unload_counter(handle) + || unsafe { &*runtime_ptr }.has_ignore_destructive_writes_counter(handle)) + { rv.set_undefined(); return; } if !stream_was_open { + if !unsafe { &*runtime_ptr }.check_document_open_origin(scope, args.this()) { + return; + } unsafe { &mut *runtime_ptr }.prepare_windowless_document_replacement( scope, runtime_ptr, @@ -197,6 +205,9 @@ fn node_document_write_or_writeln_callback<'s>( return; } if implicit_replacement_session { + if !runtime.check_document_open_origin(scope, args.this()) { + return; + } let entry_document = runtime.document_open_entry_document(scope); PageScriptHost::prepare_root_document_replacement( scope, @@ -297,6 +308,9 @@ pub(in crate::native_bridge) fn node_document_open_callback<'s>( ); return; } + if !unsafe { &*runtime_ptr }.check_document_open_origin(scope, args.this()) { + return; + } if unsafe { &*runtime_ptr }.has_document_unload_counter(handle) { rv.set(args.this().into()); return; @@ -360,6 +374,23 @@ pub(in crate::native_bridge) fn node_document_open_callback<'s>( } impl PageScriptHost { + pub(in crate::native_bridge) fn check_document_open_origin<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + document: v8::Local<'s, v8::Object>, + ) -> bool { + if self.document_has_same_origin_as_entry(scope, document) { + return true; + } + throw_dom_exception( + scope, + "SecurityError", + 18, + "The document is not same-origin with the entry document.", + ); + false + } + pub(in crate::native_bridge) fn document_open_entry_document( &self, scope: &mut v8::PinScope<'_, '_>, diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/document_open_origin.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/document_open_origin.rs new file mode 100644 index 00000000000..733f93bf501 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/document_open_origin.rs @@ -0,0 +1,155 @@ +use super::*; + +#[tokio::test(flavor = "current_thread")] +async fn document_open_checks_entry_origin_without_document_domain_relaxation() { + const HOST: &str = "document-open-origin.test"; + let child = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/document-open-origin-child.html" + )); + let same = StaticHttpServer::spawn_with_bodies(vec![child.to_owned()]).await; + let cross = StaticHttpServer::spawn_with_bodies(vec![child.to_owned()]).await; + let loader = static_http_loader([same.resolve_entry(HOST), cross.resolve_entry(HOST)]); + let mut vm = new_parsed_page_task_executor_test_vm( + same.url_for_host(HOST, "/entry.html").as_str(), + "parent", + &loader, + ); + let script = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/document-open-origin.js" + )); + vm.exec( + &format!( + r#" +globalThis.__documentOpenOriginResult = null; +({script})({{sameURL:{same_url:?},crossURL:{cross_url:?}}}).then( + result => {{__documentOpenOriginResult = result}}, + error => {{__documentOpenOriginResult = {{error:String(error)}}}} +); +"#, + same_url = same.url_for_host(HOST, "/child.html").as_str(), + cross_url = cross.url_for_host(HOST, "/child.html").as_str(), + ), + None, + ) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(__documentOpenOriginResult !== null)", + "true", + "document.open origin checks should finish", + ) + .await; + let result: serde_json::Value = serde_json::from_str( + &vm.eval("JSON.stringify(__documentOpenOriginResult)") + .unwrap(), + ) + .unwrap(); + assert!( + result["checks"].as_u64().is_some_and(|count| count > 100), + "{result}" + ); + assert_eq!(result["failures"], serde_json::json!([]), "{result}"); + assert_eq!(same.finish_targets().await, ["/child.html"]); + assert_eq!(cross.finish_targets().await, ["/child.html"]); +} + +#[test] +fn document_open_accepts_inherited_opaque_origins() { + let mut vm = new_parsed_test_vm("about:blank", "opaque"); + assert_eq!( + vm.eval( + r#" +(() => { + const frame = document.body.appendChild(document.createElement('iframe')); + const documents = [frame.contentDocument, + document.implementation.createHTMLDocument('opaque'), + new DOMParser().parseFromString('

opaque

', 'text/html')]; + for (const doc of documents) { + if (doc.open() !== doc) throw new Error('open return value'); + doc.write('

allowed

'); doc.close(); + if (doc.body.textContent !== 'allowed') throw new Error('inherited opaque origin rejected'); + } + return 'ok'; +})() +"#, + ) + .unwrap(), + "ok" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn document_open_keeps_popup_origins_after_the_popup_closes() { + const HOST: &str = "popup-open-origin.test"; + let server = StaticHttpServer::spawn_with_bodies(vec![ + r#"popup"# + .to_owned(), + ]) + .await; + let loader = static_http_loader([server.resolve_entry(HOST)]); + let mut vm = new_parsed_page_task_executor_test_vm( + "http://popup-open-origin.test:8443/entry.html", + "parent", + &loader, + ); + vm.exec( + &format!( + r#" +document.domain = location.hostname; +globalThis.__popupOriginReady = false; +addEventListener('message', event => {{ + if (event.data === 'popup-origin-ready') __popupOriginReady = true; +}}); +globalThis.__originPopup = open({url:?}); +"#, + url = server.url_for_host(HOST, "/popup.html").as_str(), + ), + None, + ) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(__popupOriginReady)", + "true", + "cross-origin popup should finish initializing", + ) + .await; + assert_eq!( + vm.eval( + r#" +(() => { + const popup = __originPopup; + const documents = [popup.document, popup.originDocument, + DOMParser.prototype.parseFromString.call(popup.originParser, '

parsed

', 'text/html')]; + for (const close of [false, true]) { + if (close) popup.close(); + for (const doc of documents) { + const original = doc.documentElement; + for (const method of ['open', 'write', 'writeln']) { + let caught; + try { Document.prototype[method].call(doc, 'replacement'); } + catch (error) { caught = error; } + if (!(caught instanceof DOMException) || caught.name !== 'SecurityError' || caught.code !== 18) + throw new Error('popup origin was lost: ' + close + '/' + method + '/' + caught); + if (doc.documentElement !== original) throw new Error('rejected write changed popup document'); + } + } + } + return 'ok'; +})() +"#, + ) + .unwrap(), + "ok" + ); + assert_eq!(server.finish_targets().await, ["/popup.html"]); +} diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs index 4d643d437d8..4a60503193c 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs @@ -1,6 +1,8 @@ mod document_node_factory_realms; mod form_event_realms; +mod event_constructor_type; mod insert_adjacent_element_conversion; + use super::*; mod media_attribute_namespaces; @@ -31,7 +33,7 @@ mod crypto_subtle_x25519; mod date_locale; mod details; mod document_open_navigation_abort; -mod event_constructor_type; +mod document_open_origin; mod event_handlers; mod event_listener_options; mod events_selection_storage; diff --git a/moli-renderer-v8/tests/fixtures/document-open-origin-child.html b/moli-renderer-v8/tests/fixtures/document-open-origin-child.html new file mode 100644 index 00000000000..69952e32b2b --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/document-open-origin-child.html @@ -0,0 +1,18 @@ +

original

diff --git a/moli-renderer-v8/tests/fixtures/document-open-origin.js b/moli-renderer-v8/tests/fixtures/document-open-origin.js new file mode 100644 index 00000000000..b74c129acf0 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/document-open-origin.js @@ -0,0 +1,99 @@ +async ({sameURL, crossURL}) => { + const failures = []; + let checks = 0; + const equal = (actual, expected, label) => { + checks++; + if (JSON.stringify(actual) !== JSON.stringify(expected)) + failures.push({label, actual, expected}); + }; + const throws = (callback, Constructor, name, label) => { + try { callback(); equal('returned', name, label); } + catch (error) { + equal([error.name, error instanceof Constructor], [name, true], label); + if (name === 'SecurityError') equal(error.code, 18, label + ' code'); + } + }; + document.domain = location.hostname; + const create = async url => { + const frame = document.createElement('iframe'); + const loaded = new Promise(resolve => frame.onload = resolve); + frame.src = url; document.body.append(frame); + await loaded; + return frame; + }; + const same = await create(sameURL); + const remote = await create(crossURL); + const w = remote.contentWindow, d = remote.contentDocument; + equal(d !== null, true, 'domain relaxation permits DOM access'); + const childException = w.DOMException; + const originDocuments = [ + ['live', d], + ['constructed', d.implementation.createHTMLDocument('child')], + ['parsed', new w.DOMParser().parseFromString('

parsed

', 'text/html')], + ['borrowed parser', DOMParser.prototype.parseFromString.call(new w.DOMParser(), '

parsed

', 'text/html')], + ['cloned', d.cloneNode(true)] + ]; + for (const [kind, doc] of originDocuments) { + const original = doc.documentElement, url = doc.URL; + for (const method of ['open', 'write', 'writeln']) { + throws(() => doc[method]('

replacement

'), + doc.open === Document.prototype.open ? DOMException : childException, + 'SecurityError', kind + '/' + method); + throws(() => Document.prototype[method].call(doc, '

replacement

'), + DOMException, 'SecurityError', kind + '/borrowed ' + method); + equal(doc.documentElement === original, true, kind + '/' + method + ' keeps tree'); + equal(doc.URL, url, kind + '/' + method + ' keeps URL'); + } + } + // The function's realm is not the entry realm of this synchronous call. + throws(() => w.Function('doc', 'return doc.open()')(d), childException, + 'SecurityError', 'foreign JS function does not change entry document'); + const xml = new w.DOMParser().parseFromString('', 'application/xml'); + for (const method of ['open', 'write', 'writeln']) + throws(() => xml[method]('text'), childException, 'InvalidStateError', 'XML precedes origin/' + method); + let converted = 0; + throws(() => d.write({toString() {converted++; return 'text'}}), childException, + 'SecurityError', 'write converts before origin check'); + equal(converted, 1, 'write conversion count'); + const conversionError = {}; + try { d.write({toString() {throw conversionError}}); equal('returned', 'threw', 'conversion error'); } + catch (error) { equal(error === conversionError, true, 'conversion exception precedes origin'); } + + // Same-origin borrowed methods and inherited about:blank origins remain valid. + for (const method of ['open', 'write', 'writeln']) { + const doc = same.contentDocument.implementation.createHTMLDocument('allowed'); + try { w.Document.prototype[method].call(doc, 'allowed'); equal(true, true, 'same-origin/' + method); } + catch (error) { equal(error.name, 'allowed', 'same-origin/' + method); } + doc.close(); + } + const blank = document.body.appendChild(document.createElement('iframe')); + equal(blank.contentDocument.open() === blank.contentDocument, true, 'inherited about:blank open'); + blank.contentDocument.close(); + blank.remove(); + + const root = document.documentElement; + const response = new Promise(resolve => { + const listener = event => { + if (event.source !== w || event.data?.token !== 'document-open-origin') return; + removeEventListener('message', listener); resolve(event.data); + }; + addEventListener('message', listener); + }); + w.postMessage('document-open-origin', '*'); + const observed = await response; + equal(observed.attempts, [['SecurityError',18,true],['SecurityError',18,true]], 'child entry rejects parent document'); + equal(observed.own, true, 'child entry can open its own document'); + equal(document.documentElement === root, true, 'rejected parent open keeps root'); + const stream = d.getElementById('stream'); + try { d.write('parent'); d.writeln(' tail'); } + catch (error) { equal(error.name, 'allowed', 'existing insertion point does not run open steps'); } + equal(d.getElementById('stream') === stream, true, 'existing stream is not replaced'); + equal(stream.textContent, 'childparent tail\n', 'cross-origin write into existing stream'); + throws(() => d.open(), childException, 'SecurityError', 'explicit open still rejects existing stream'); + d.close(); + throws(() => d.write('closed'), childException, 'SecurityError', 'closed stream requires new origin check'); + same.remove(); remote.remove(); + for (const [kind, doc] of originDocuments) + throws(() => Document.prototype.open.call(doc), DOMException, 'SecurityError', 'retained origin/' + kind); + return {checks, failures}; +}