diff --git a/moli-renderer-v8/src/resource_initiator.rs b/moli-renderer-v8/src/resource_initiator.rs index b0e51e82563..5105ab1c080 100644 --- a/moli-renderer-v8/src/resource_initiator.rs +++ b/moli-renderer-v8/src/resource_initiator.rs @@ -1,26 +1,31 @@ //! Immutable resource attribution carried with classic-script continuations. -//! These private values contain strings, never callback or Window authority. -use crate::util::{get_private_value, set_private_value, v8_string}; +//! Only primitive strings may survive with a reaction or registration: even a +//! prototype-free JS object can retain its creating Realm through its V8 map. +use crate::util::{v8_string, v8str}; use moli_url::WebOrigin; use url::Url; -const BASE: &str = "moli.resourceInitiatorBaseURL"; -const ANCHOR: &str = "moli.resourceInitiator"; -const SOURCE: &str = "moli.resourceInitiatorSource"; -const ORIGIN: &str = "moli.resourceInitiatorOrigin"; +// Serialized URLs and origins cannot contain a literal NUL. The continuation +// is base\0source\0origin; a registration keeps only source\0origin. A legacy +// base-only continuation has no separator, while an empty anchor is unknown. +const SEPARATOR: char = '\0'; -pub(crate) fn anchor<'s>(scope: &mut v8::PinScope<'s, '_>) -> Option> { +pub(crate) fn anchor<'s>(scope: &mut v8::PinScope<'s, '_>) -> Option> { let data = - v8::Local::::try_from(scope.get_continuation_preserved_embedder_data()).ok()?; - v8::Local::::try_from(get_private_value(scope, data, ANCHOR)?).ok() + v8::Local::::try_from(scope.get_continuation_preserved_embedder_data()).ok()?; + let data = data.to_rust_string_lossy(scope); + let (_, anchor) = data.split_once(SEPARATOR)?; + v8_string(scope, anchor) } pub(crate) fn base_url_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { let data = scope.get_continuation_preserved_embedder_data(); - if anchor(scope).is_some() - && let Ok(data) = v8::Local::::try_from(data) + if let Ok(value) = v8::Local::::try_from(data) + && let Some((base, _)) = value.to_rust_string_lossy(scope).split_once(SEPARATOR) { - return get_private_value(scope, data, BASE).unwrap_or_else(|| v8::undefined(scope).into()); + return v8_string(scope, base) + .filter(|_| !base.is_empty()) + .map_or_else(|| v8::undefined(scope).into(), Into::into); } data } @@ -28,12 +33,14 @@ pub(crate) fn base_url_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local< fn data_with_anchor<'s>( scope: &mut v8::PinScope<'s, '_>, base: v8::Local<'s, v8::Value>, - anchor: v8::Local<'s, v8::Object>, + anchor: v8::Local<'s, v8::String>, ) -> v8::Local<'s, v8::Value> { - let data = v8::Object::new(scope); - set_private_value(scope, data, BASE, base); - set_private_value(scope, data, ANCHOR, anchor.into()); - data.into() + let base = v8::Local::::try_from(base).unwrap_or_else(|_| v8::String::empty(scope)); + let base = v8::String::concat(scope, base, v8str(scope, "\0")) + .expect("continuation base URL must fit in a V8 string"); + v8::String::concat(scope, base, anchor) + .expect("continuation URLs must fit in a V8 string") + .into() } pub(crate) fn with_base_url<'s>( @@ -69,19 +76,18 @@ pub(crate) fn classic_data<'s>( .is_some_and(|origin| origin.same_origin_url(source)) }); let base = base_url_value(scope); - let anchor = v8::Object::new(scope); - if let Some(value) = v8_string(scope, source.map(Url::as_str).unwrap_or("")) { - set_private_value(scope, anchor, SOURCE, value.into()); - } - if let Some(value) = v8_string( + let anchor = v8_string( scope, - origin - .as_ref() - .map(WebOrigin::ascii_serialization) - .unwrap_or(""), - ) { - set_private_value(scope, anchor, ORIGIN, value.into()); - } + &format!( + "{}\0{}", + source.map(Url::as_str).unwrap_or(""), + origin + .as_ref() + .map(WebOrigin::ascii_serialization) + .unwrap_or(""), + ), + ) + .expect("resource initiator URLs must fit in a V8 string"); data_with_anchor(scope, base, anchor) } @@ -92,16 +98,15 @@ pub(crate) fn current_url(scope: &mut v8::PinScope<'_, '_>, origin: &WebOrigin) let Some(anchor) = anchor(scope) else { return String::new(); }; - let captured_origin = get_private_value(scope, anchor, ORIGIN) - .and_then(|value| v8::Local::::try_from(value).ok()) - .map(|value| value.to_rust_string_lossy(scope)); - if captured_origin.as_deref() != Some(origin.ascii_serialization()) { + let anchor = anchor.to_rust_string_lossy(scope); + let Some((source, captured_origin)) = anchor.split_once(SEPARATOR) else { return String::new(); + }; + if captured_origin == origin.ascii_serialization() { + source.to_owned() + } else { + String::new() } - get_private_value(scope, anchor, SOURCE) - .and_then(|value| v8::Local::::try_from(value).ok()) - .map(|value| value.to_rust_string_lossy(scope)) - .unwrap_or_default() } pub(crate) fn response_url( diff --git a/moli-renderer-v8/src/script_vm/tests/resource_initiator.rs b/moli-renderer-v8/src/script_vm/tests/resource_initiator.rs index e41e210abf9..3d98bc261e0 100644 --- a/moli-renderer-v8/src/script_vm/tests/resource_initiator.rs +++ b/moli-renderer-v8/src/script_vm/tests/resource_initiator.rs @@ -1,6 +1,8 @@ use super::*; use crate::script_provenance::CompiledStringProvenance; +mod realm_lifetime; + fn execute_with_source(vm: &mut ScriptVm, source: &str, url: &Url, base: &Url) { vm.exec_in_enclosing_script_turn_with_provenance( source, diff --git a/moli-renderer-v8/src/script_vm/tests/resource_initiator/realm_lifetime.rs b/moli-renderer-v8/src/script_vm/tests/resource_initiator/realm_lifetime.rs new file mode 100644 index 00000000000..cdbf115bfc7 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/resource_initiator/realm_lifetime.rs @@ -0,0 +1,146 @@ +use super::*; + +fn assert_pending_parent_promise_releases_removed_child(register: bool, known_source: bool) { + let mut vm = new_storage_html_test_vm("https://initiator-lifetime.test/"); + vm.eval( + r#" + globalThis.pending = new Promise(resolve => { globalThis.releasePromise = resolve; }); + globalThis.completed = 0; + globalThis.parentCallback = () => { completed++; }; + globalThis.install = () => { pending.then(parentCallback); }; + globalThis.frame = document.createElement('iframe'); + document.body.appendChild(frame); + typeof frame.contentWindow.Function; + "#, + ) + .unwrap(); + let child = vm + .prebootstrapped_child_default_contexts + .borrow() + .values() + .next() + .expect("the iframe should have a context") + .context + .clone(); + let source = Url::parse("https://initiator-lifetime.test/child.js").unwrap(); + vm.exec_in_context_ptr_runtime_turn( + &child, + if register { + "globalThis.childObject = {}; parent.install();" + } else { + "globalThis.childObject = {};" + }, + known_source.then_some(&source), + 0, + true, + false, + ) + .unwrap(); + let (context, objects) = vm + .with_context_scope_by_ptr_and_checkpoint_for_test(&child, |scope, _| { + let context = scope.get_current_context(); + let global = context.global(scope); + let object = global + .get(scope, crate::util::v8str(scope, "Object").into()) + .and_then(|value| v8::Local::::try_from(value).ok()) + .unwrap(); + let prototype = object + .get(scope, crate::util::v8str(scope, "prototype").into()) + .and_then(|value| v8::Local::::try_from(value).ok()) + .unwrap(); + let document = global + .get(scope, crate::util::v8str(scope, "document").into()) + .and_then(|value| v8::Local::::try_from(value).ok()) + .unwrap(); + let object = global + .get(scope, crate::util::v8str(scope, "childObject").into()) + .and_then(|value| v8::Local::::try_from(value).ok()) + .unwrap(); + Ok(( + v8::Weak::new(scope, context), + [prototype, global, document, object].map(|value| v8::Weak::new(scope, value)), + )) + }) + .unwrap(); + vm.eval("frame.remove(); frame = null;").unwrap(); + vm.prune_stale_child_default_execution_contexts(); + drop(child); + + // No Local or Global handle, callback, or CDP object id roots the iframe. + // The parent Promise and its parent-created reaction deliberately survive. + for _ in 0..3 { + vm.renderer_document_isolate + .with_renderer_document_isolate_mut(|isolate| { + isolate.low_memory_notification(); + isolate.low_memory_notification(); + }); + assert!( + context.is_empty(), + "continuation metadata retained the child Context" + ); + assert!( + objects.iter().all(v8::Weak::is_empty), + "continuation metadata retained child objects" + ); + } + assert_eq!(vm.eval("String(completed)").unwrap(), "0"); + vm.eval("releasePromise(); pending = releasePromise = parentCallback = install = null;") + .unwrap(); + assert_eq!( + vm.eval("String(completed)").unwrap(), + if register { "1" } else { "0" } + ); +} + +#[test] +fn resource_initiator_pending_parent_promise_does_not_retain_removed_child() { + assert_pending_parent_promise_releases_removed_child(true, true); +} + +#[test] +fn resource_initiator_unknown_continuation_does_not_retain_removed_child() { + assert_pending_parent_promise_releases_removed_child(true, false); +} + +#[test] +fn resource_initiator_removed_child_without_parent_reaction_is_collectable() { + assert_pending_parent_promise_releases_removed_child(false, true); +} + +#[test] +fn resource_initiator_continuation_preserves_base_url_and_encoded_control_characters() { + let mut vm = new_storage_test_vm("https://initiator-lifetime.test/"); + vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| { + let source = Url::parse("https://initiator-lifetime.test/a%00.js?x=%0A#%00").unwrap(); + let base = Url::parse("https://base.test/%00/%0A/").unwrap(); + let origin = moli_url::WebOrigin::from_url(&source); + let data = crate::resource_initiator::classic_data(scope, Some(&source)); + scope.set_continuation_preserved_embedder_data(data); + let data = crate::util::script_base_url_continuation_data(scope, &base).unwrap(); + scope.set_continuation_preserved_embedder_data(data); + assert_eq!( + crate::util::script_base_url_from_continuation_data(scope), + Some(base.clone()) + ); + assert_eq!( + crate::resource_initiator::current_url(scope, &origin), + source.as_str() + ); + assert_eq!( + crate::resource_initiator::current_url(scope, &moli_url::WebOrigin::from_url(&base)), + "" + ); + + let data = crate::resource_initiator::classic_data(scope, None); + scope.set_continuation_preserved_embedder_data(data); + assert!(crate::resource_initiator::anchor(scope).is_some()); + assert_eq!(crate::resource_initiator::current_url(scope, &origin), ""); + assert_eq!( + crate::util::script_base_url_from_continuation_data(scope), + Some(base) + ); + scope.set_continuation_preserved_embedder_data(v8::undefined(scope).into()); + Ok(()) + }) + .unwrap(); +}