Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(renderer): propagate intrinsic finalization failures

ldm0661e6cfd99e0
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/finalize.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/finalize.rs
index 39da7d59f..45e1de1e7 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/finalize.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/finalize.rs
@@ -1,8 +1,15 @@
-use anyhow::Result;
+use anyhow::{Context, Result, anyhow};
use super::materialize::{
ensure_intrinsic_interface_constructor, ensure_intrinsic_interface_prototype,
};
+use crate::context_bootstrap::{
+ crypto::finalize_crypto_realm_bindings, events::finalize_pointer_event_realm_bindings,
+ notification_runtime::finalize_notification_realm_bindings,
+ performance_runtime::finalize_performance_observer_realm_bindings,
+ web_audio_runtime::finalize_base_audio_context_realm_bindings,
+};
+use crate::network_host::finalize_xml_http_request_event_target_realm_bindings;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RealmDependentFinalizer {
@@ -76,58 +83,52 @@ pub(super) fn finalize_materialized_interface(
scope: &mut v8::PinScope<'_, '_>,
interface_name: &str,
) -> Result<()> {
- let prototype = ensure_intrinsic_interface_prototype(scope, interface_name)?;
-
let Some(finalizer) = realm_dependent_finalizer(interface_name) else {
return Ok(());
};
+ let prototype = ensure_intrinsic_interface_prototype(scope, interface_name)?;
match finalizer {
RealmDependentFinalizer::NodeMixinUnscopables => {
- finalize_node_mixin_unscopables(scope, prototype);
+ finalize_node_mixin_unscopables(scope, prototype)
}
RealmDependentFinalizer::BaseAudioContextSecureContextSurface => {
- crate::context_bootstrap::web_audio_runtime::finalize_base_audio_context_realm_bindings(scope, prototype)?;
+ finalize_base_audio_context_realm_bindings(scope, prototype)
}
RealmDependentFinalizer::CryptoSecureContextSurface => {
- crate::context_bootstrap::crypto::finalize_crypto_realm_bindings(scope, prototype)?;
+ finalize_crypto_realm_bindings(scope, prototype)
}
RealmDependentFinalizer::XmlHttpRequestEventTargetState => {
- crate::network_host::finalize_xml_http_request_event_target_realm_bindings(
- scope, prototype,
- );
+ finalize_xml_http_request_event_target_realm_bindings(scope, prototype)
}
RealmDependentFinalizer::NotificationPermission => {
- crate::context_bootstrap::notification_runtime::install_notification_realm_bindings(
- scope,
- );
+ let constructor = ensure_intrinsic_interface_constructor(scope, "Notification")?;
+ finalize_notification_realm_bindings(scope, constructor.into())
}
RealmDependentFinalizer::PointerEventSecureContextSurface => {
- crate::context_bootstrap::events::finalize_pointer_event_realm_bindings(
- scope, prototype,
- )?;
+ finalize_pointer_event_realm_bindings(scope, prototype)
}
RealmDependentFinalizer::PerformanceObserverSupportedEntryTypes => {
let constructor = ensure_intrinsic_interface_constructor(scope, "PerformanceObserver")?;
- crate::context_bootstrap::performance_runtime::finalize_performance_observer_realm_bindings(
- scope,
- constructor.into(),
- );
+ finalize_performance_observer_realm_bindings(scope, constructor.into())
}
}
- Ok(())
+ .with_context(|| format!("failed to finalize intrinsic interface `{interface_name}`"))
}
fn finalize_node_mixin_unscopables(
scope: &mut v8::PinScope<'_, '_>,
prototype: v8::Local<'_, v8::Object>,
-) {
- let Some(unscopables) = prototype
+) -> Result<()> {
+ let unscopables = prototype
.get(scope, v8::Symbol::get_unscopables(scope).into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return;
- };
- let _ = unscopables.set_prototype(scope, v8::null(scope).into());
+ .ok_or_else(|| anyhow!("intrinsic @@unscopables object is unavailable"))?;
+ if unscopables.set_prototype(scope, v8::null(scope).into()) != Some(true) {
+ return Err(anyhow!(
+ "failed to set intrinsic @@unscopables null prototype"
+ ));
+ }
+ Ok(())
}
#[cfg(test)]
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs
index 1d90bbb7a..c4a729246 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs
@@ -262,13 +262,22 @@ pub(crate) fn capture_eager_intrinsic_interfaces<'s>(
Ok(())
}
-fn capture_ecmascript_intrinsic<'s>(
+pub(super) fn capture_ecmascript_intrinsic<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,
name: &str,
) -> Result<()> {
- if registered_intrinsic_constructor(scope, global, name).is_some() {
- return Ok(());
+ match (
+ registered_intrinsic_constructor(scope, global, name),
+ registered_intrinsic_prototype(scope, global, name),
+ ) {
+ (Some(_), Some(_)) => return Ok(()),
+ (None, None) => {}
+ _ => {
+ return Err(anyhow!(
+ "ECMAScript intrinsic `{name}` has partial registry state"
+ ));
+ }
}
let constructor = constructor_object(scope, global, name)
.ok_or_else(|| anyhow!("missing ECMAScript intrinsic constructor `{name}`"))?;
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs
index e42668a3d..955516850 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs
@@ -317,7 +317,7 @@ fn finish_materialized_interface<'s>(
metadata.name
)
})?;
- set_interface_prototype_constructor(scope, constructor, proxy.into());
+ set_interface_prototype_constructor(scope, constructor_prototype, proxy.into())?;
v8::Local::<v8::Object>::from(proxy)
}
_ => constructor.into(),
@@ -332,6 +332,7 @@ fn finish_materialized_interface<'s>(
constructor_prototype,
public_interface,
)?;
+ realm.set_state(id, RealmInterfaceState::Finalizing)?;
finalize_materialized_interface(scope, metadata.name)?;
realm.set_state(id, RealmInterfaceState::Ready)?;
registry.record_materialization(id);
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs
index cad4f96f3..826771671 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs
@@ -114,6 +114,8 @@ impl IntrinsicInterfaceRegistry {
/// Publishes the same intrinsic identities to both registries. Mark the
/// interface in progress before either store changes, and make any failed
/// publication terminal even if V8 has retained an immutable partial pair.
+ /// Successful publication stays Materializing: eager capture then marks it
+ /// Ready, while lazy materialization exposes it only when Finalizing starts.
pub(super) fn register_intrinsic_objects<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
@@ -129,8 +131,9 @@ impl IntrinsicInterfaceRegistry {
}
self.set_state(id, RealmInterfaceState::Materializing)?;
let result = (|| {
- // Validate and retain the Rust objects before writing the immutable
- // JS entries. Accessors expose them only once publication completes.
+ // Retain the Rust objects before writing the immutable JS entries.
+ // Keep them hidden until the caller starts finalization or
+ // completes eager capture.
self.register_objects(scope, id, constructor, prototype, public_interface)?;
match (
registered_intrinsic_constructor(scope, global, name),
@@ -156,7 +159,7 @@ impl IntrinsicInterfaceRegistry {
));
}
}
- self.set_state(id, RealmInterfaceState::Finalizing)
+ Ok(())
})();
if result.is_err() {
self.set_state(id, RealmInterfaceState::Failed)?;
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs
index 5df3713fc..8496bce14 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs
@@ -5,6 +5,8 @@ use std::pin::pin;
use crate::context_bootstrap::specs::{ConstructorKind, ConstructorSpec};
use crate::util::v8str;
+mod finalization;
+
thread_local! {
static LAZY_GETTER_CALLS: Cell<u32> = const { Cell::new(0) };
}
@@ -371,6 +373,60 @@ fn uninitialized_dom_string_map_adopts_its_registered_intrinsics() {
);
}
+#[test]
+fn ecmascript_intrinsic_capture_rejects_partial_registration_on_retry() {
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let global = context.global(scope);
+ crate::util::initialize_intrinsic_interface_registry(scope, global);
+ let prototypes = crate::util::get_private_object(scope, global, "__moliIntrinsicPrototypes")
+ .expect("private prototype registry");
+ assert_eq!(
+ prototypes.set_integrity_level(scope, v8::IntegrityLevel::Frozen),
+ Some(true)
+ );
+
+ super::install::capture_ecmascript_intrinsic(scope, global, "Error")
+ .expect_err("the first capture must report its failed prototype publication");
+ assert!(crate::util::registered_intrinsic_constructor(scope, global, "Error").is_some());
+ assert!(crate::util::registered_intrinsic_prototype(scope, global, "Error").is_none());
+ let error = super::install::capture_ecmascript_intrinsic(scope, global, "Error")
+ .expect_err("retrying a partial Error pair must not report success");
+ assert!(error.to_string().contains("partial registry state"));
+}
+
+#[test]
+fn ecmascript_intrinsic_capture_rejects_prototype_without_constructor() {
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let global = context.global(scope);
+ crate::util::initialize_intrinsic_interface_registry(scope, global);
+ let prototypes = crate::util::get_private_object(scope, global, "__moliIntrinsicPrototypes")
+ .expect("private prototype registry");
+ let constructor = crate::util::constructor_object(scope, global, "Error")
+ .expect("ECMAScript Error constructor");
+ let prototype = crate::util::constructor_prototype_object(scope, constructor)
+ .expect("ECMAScript Error prototype");
+ assert_eq!(
+ prototypes.set(scope, v8str(scope, "Error").into(), prototype.into()),
+ Some(true)
+ );
+
+ let error = super::install::capture_ecmascript_intrinsic(scope, global, "Error")
+ .expect_err("a prototype-only Error registration must not be completed from the global");
+
+ assert!(error.to_string().contains("partial registry state"));
+ assert!(crate::util::registered_intrinsic_constructor(scope, global, "Error").is_none());
+}
+
#[test]
fn incomplete_intrinsic_registration_marks_materialization_failed() {
crate::ensure_v8_for_test();
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests/finalization.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests/finalization.rs
new file mode 100644
index 000000000..72c1ee56a
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests/finalization.rs
@@ -0,0 +1,384 @@
+use std::pin::pin;
+use std::rc::Rc;
+
+use super::super::materialize::{
+ ensure_intrinsic_interface_constructor, ensure_intrinsic_interface_prototype,
+ materialize_interface,
+};
+use super::super::metadata::{InterfaceId, RealmKind, TemplateBuildProfile};
+use super::super::realm_registry::{IntrinsicInterfaceRegistry, RealmInterfaceState};
+use super::super::template_registry::ExposedInterfaceTemplateRegistry;
+use super::{counting_lazy_getter, lazy_getter_calls, reset_lazy_getter_calls};
+use crate::util::{
+ constructor_prototype_object, get_private_value, register_intrinsic_interface,
+ registered_intrinsic_constructor, registered_intrinsic_prototype, v8str,
+};
+
+struct RegisteredInterface<'s> {
+ registry: Rc<ExposedInterfaceTemplateRegistry>,
+ realm: Rc<IntrinsicInterfaceRegistry>,
+ id: InterfaceId,
+ name: &'static str,
+ constructor: v8::Local<'s, v8::Function>,
+ prototype: v8::Local<'s, v8::Object>,
+}
+
+impl RegisteredInterface<'_> {
+ fn assert_failed(&self, scope: &mut v8::PinScope<'_, '_>, cause: &str) {
+ let error = materialize_interface(scope, self.id)
+ .expect_err("failed recovery must return an error without panicking");
+ assert!(format!("{error:#}").contains(cause), "{error:#}");
+ assert_eq!(self.realm.state(self.id), Some(RealmInterfaceState::Failed));
+ assert!(self.realm.constructor(scope, self.id).is_none());
+ assert!(self.realm.prototype(scope, self.id).is_none());
+ assert!(self.realm.public_interface(scope, self.id).is_none());
+ assert!(ensure_intrinsic_interface_constructor(scope, self.name).is_err());
+ assert!(ensure_intrinsic_interface_prototype(scope, self.name).is_err());
+ assert_eq!(self.registry.materialization_count(self.id), 0);
+ assert_eq!(lazy_getter_calls(), 0);
+
+ // Immutable private entries survive, but Failed prevents their reuse.
+ let global = scope.get_current_context().global(scope);
+ assert!(
+ registered_intrinsic_constructor(scope, global, self.name)
+ .is_some_and(|value| value.strict_equals(self.constructor.into()))
+ );
+ assert!(
+ registered_intrinsic_prototype(scope, global, self.name)
+ .is_some_and(|value| value.strict_equals(self.prototype.into()))
+ );
+ }
+}
+
+fn with_registered_interface(
+ name: &'static str,
+ test: impl for<'s, 'i> FnOnce(&mut v8::PinScope<'s, 'i>, RegisteredInterface<'s>),
+) {
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let registry = ExposedInterfaceTemplateRegistry::install(
+ scope,
+ crate::context_bootstrap::specs::constructor_specs(),
+ TemplateBuildProfile::Window,
+ )
+ .expect("template registry");
+ let realm = IntrinsicInterfaceRegistry::initialize_for_current_context(
+ scope,
+ registry.len(),
+ RealmKind::Window,
+ )
+ .expect("realm registry");
+ let id = registry.id_by_name(name).expect("interface metadata");
+ let constructor = registry
+ .get_or_build_template(scope, id)
+ .expect("interface template")
+ .get_function(scope)
+ .expect("interface constructor");
+ let prototype =
+ constructor_prototype_object(scope, constructor.into()).expect("interface prototype");
+ let global = context.global(scope);
+ assert!(register_intrinsic_interface(
+ scope,
+ global,
+ name,
+ constructor.into(),
+ prototype,
+ ));
+ assert_eq!(
+ global.set_lazy_data_property(scope, v8str(scope, name).into(), counting_lazy_getter),
+ Some(true)
+ );
+ reset_lazy_getter_calls();
+ test(
+ scope,
+ RegisteredInterface {
+ registry,
+ realm,
+ id,
+ name,
+ constructor,
+ prototype,
+ },
+ );
+}
+
+#[test]
+fn failed_unscopables_finalization_is_terminal() {
+ with_registered_interface("Document", |scope, interface| {
+ let unscopables = interface
+ .prototype
+ .get(scope, v8::Symbol::get_unscopables(scope).into())
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .expect("template-defined unscopables object");
+ assert!(!unscopables.get_prototype(scope).unwrap().is_null());
+ assert_eq!(
+ unscopables.set_integrity_level(scope, v8::IntegrityLevel::Frozen),
+ Some(true)
+ );
+ interface.assert_failed(scope, "@@unscopables null prototype");
+ });
+}
+
+#[test]
+fn missing_unscopables_finalization_is_terminal() {
+ with_registered_interface("DocumentFragment", |scope, interface| {
+ assert_eq!(
+ interface
+ .prototype
+ .delete(scope, v8::Symbol::get_unscopables(scope).into()),
+ Some(true)
+ );
+ interface.assert_failed(scope, "@@unscopables object is unavailable");
+ });
+}
+
+#[test]
+fn failed_notification_finalization_is_terminal() {
+ with_registered_interface("Notification", |scope, interface| {
+ assert_eq!(
+ interface
+ .constructor
+ .set_integrity_level(scope, v8::IntegrityLevel::Frozen),
+ Some(true)
+ );
+ interface.assert_failed(scope, "failed to define `permission` accessor");
+ });
+}
+
+#[test]
+fn failed_performance_observer_finalization_is_terminal() {
+ with_registered_interface("PerformanceObserver", |scope, interface| {
+ assert_eq!(
+ interface
+ .constructor
+ .set_integrity_level(scope, v8::IntegrityLevel::Frozen),
+ Some(true)
+ );
+ interface.assert_failed(scope, "failed to define `supportedEntryTypes` value");
+ });
+}
+
+#[test]
+fn failed_html_constructor_link_is_terminal() {
+ with_registered_interface("HTMLDivElement", |scope, interface| {
+ assert_eq!(
+ interface
+ .prototype
+ .set_integrity_level(scope, v8::IntegrityLevel::Frozen),
+ Some(true)
+ );
+ interface.assert_failed(scope, "intrinsic prototype constructor");
+ });
+}
+
+#[test]
+fn published_intrinsics_stay_hidden_until_the_caller_exposes_them() {
+ with_registered_interface("DOMStringMap", |scope, interface| {
+ let global = scope.get_current_context().global(scope);
+ interface
+ .realm
+ .register_intrinsic_objects(
+ scope,
+ global,
+ interface.id,
+ interface.name,
+ interface.constructor.into(),
+ interface.prototype,
+ interface.constructor.into(),
+ )
+ .expect("intrinsic publication");
+ assert_eq!(
+ interface.realm.state(interface.id),
+ Some(RealmInterfaceState::Materializing)
+ );
+ assert!(interface.realm.constructor(scope, interface.id).is_none());
+ assert!(interface.realm.prototype(scope, interface.id).is_none());
+ assert!(
+ interface
+ .realm
+ .public_interface(scope, interface.id)
+ .is_none()
+ );
+ interface
+ .realm
+ .set_state(interface.id, RealmInterfaceState::Finalizing)
+ .expect("caller starts finalization");
+ assert!(interface.realm.constructor(scope, interface.id).is_some());
+ assert!(interface.realm.prototype(scope, interface.id).is_some());
+ assert!(
+ interface
+ .realm
+ .public_interface(scope, interface.id)
+ .is_some()
+ );
+ });
+}
+
+#[test]
+fn recovered_xhr_event_target_initializes_its_private_state() {
+ with_registered_interface("XMLHttpRequestEventTarget", |scope, interface| {
+ assert!(
+ ensure_intrinsic_interface_prototype(scope, interface.name)
+ .expect("event target recovery")
+ .strict_equals(interface.prototype.into())
+ );
+ let listener_slot = get_private_value(
+ scope,
+ interface.prototype,
+ crate::context_bootstrap::SIMPLE_EVENT_TARGET_SLOT,
+ )
+ .expect("listener slot name")
+ .to_string(scope)
+ .expect("listener slot string")
+ .to_rust_string_lossy(scope);
+ assert_eq!(listener_slot, "__moliXhrEventTargetListeners");
+ for slot in [
+ crate::context_bootstrap::SIMPLE_EVENT_TARGET_ORDERED_HANDLERS_SLOT,
+ "__moliXhrUsesSimpleEventTarget",
+ ] {
+ assert!(
+ get_private_value(scope, interface.prototype, slot)
+ .expect("event target marker")
+ .is_true()
+ );
+ }
+ assert_eq!(
+ interface.realm.state(interface.id),
+ Some(RealmInterfaceState::Ready)
+ );
+ assert_eq!(lazy_getter_calls(), 0);
+ });
+}
+
+#[test]
+fn uninitialized_crypto_adopts_registered_intrinsics_and_finalizes_secure_surface() {
+ assert_registered_crypto_recovery(false);
+}
+
+#[test]
+fn uninitialized_crypto_adopts_registered_intrinsics_and_refinalizes_secure_surface() {
+ assert_registered_crypto_recovery(true);
+}
+
+fn assert_registered_crypto_recovery(already_finalized: bool) {
+ with_registered_interface("Crypto", |scope, interface| {
+ let RegisteredInterface {
+ registry,
+ realm,
+ id,
+ constructor,
+ prototype,
+ ..
+ } = interface;
+ let global = scope.get_current_context().global(scope);
+ for name in ["subtle", "randomUUID"] {
+ assert!(
+ prototype
+ .get_own_property_descriptor(scope, v8str(scope, name).into())
+ .expect("the raw template has no secure-context surface")
+ .is_undefined()
+ );
+ }
+ crate::context_bootstrap::crypto::install_window_crypto_runtime_state(scope, global, true)
+ .expect("secure-context Crypto state");
+ if already_finalized {
+ crate::context_bootstrap::crypto::finalize_crypto_realm_bindings(scope, prototype)
+ .expect("the trusted pair already has a finalized secure surface");
+ }
+ let get_random_values = prototype
+ .get(scope, v8str(scope, "getRandomValues").into())
+ .expect("template-defined getRandomValues method");
+ assert_eq!(realm.state(id), Some(RealmInterfaceState::Uninitialized));
+
+ let recovered = ensure_intrinsic_interface_prototype(scope, "Crypto")
+ .expect("adoption must allow secure-context finalization to run again");
+ assert!(recovered.strict_equals(prototype.into()));
+ assert_eq!(realm.state(id), Some(RealmInterfaceState::Ready));
+ assert!(
+ ensure_intrinsic_interface_constructor(scope, "Crypto")
+ .expect("adopted Crypto constructor")
+ .strict_equals(constructor.into())
+ );
+ assert!(
+ prototype
+ .get(scope, v8str(scope, "getRandomValues").into())
+ .expect("retained template method")
+ .strict_equals(get_random_values)
+ );
+ let subtle_descriptor = prototype
+ .get_own_property_descriptor(scope, v8str(scope, "subtle").into())
+ .expect("secure-context subtle descriptor")
+ .to_object(scope)
+ .expect("subtle descriptor object");
+ let subtle_getter = subtle_descriptor
+ .get(scope, v8str(scope, "get").into())
+ .expect("subtle getter");
+ assert!(subtle_getter.is_function());
+ assert!(
+ subtle_descriptor
+ .get(scope, v8str(scope, "set").into())
+ .expect("subtle setter field")
+ .is_undefined()
+ );
+ let uuid_descriptor = prototype
+ .get_own_property_descriptor(scope, v8str(scope, "randomUUID").into())
+ .expect("secure-context randomUUID descriptor")
+ .to_object(scope)
+ .expect("randomUUID descriptor object");
+ let random_uuid = uuid_descriptor
+ .get(scope, v8str(scope, "value").into())
+ .expect("randomUUID method");
+ assert!(random_uuid.is_function());
+ for descriptor in [subtle_descriptor, uuid_descriptor] {
+ for name in ["enumerable", "configurable"] {
+ assert!(
+ descriptor
+ .get(scope, v8str(scope, name).into())
+ .expect("Crypto descriptor attribute")
+ .is_true()
+ );
+ }
+ }
+ assert!(
+ uuid_descriptor
+ .get(scope, v8str(scope, "writable").into())
+ .expect("randomUUID writable attribute")
+ .is_true()
+ );
+
+ assert!(
+ materialize_interface(scope, id)
+ .expect("repeated Crypto materialization")
+ .strict_equals(constructor.into())
+ );
+ assert!(
+ ensure_intrinsic_interface_prototype(scope, "Crypto")
+ .expect("repeated Crypto prototype lookup")
+ .strict_equals(prototype.into())
+ );
+ let repeated_subtle_descriptor = prototype
+ .get_own_property_descriptor(scope, v8str(scope, "subtle").into())
+ .expect("retained subtle descriptor")
+ .to_object(scope)
+ .expect("subtle descriptor object");
+ assert!(
+ repeated_subtle_descriptor
+ .get(scope, v8str(scope, "get").into())
+ .expect("retained subtle getter")
+ .strict_equals(subtle_getter)
+ );
+ assert!(
+ prototype
+ .get(scope, v8str(scope, "randomUUID").into())
+ .expect("retained randomUUID method")
+ .strict_equals(random_uuid)
+ );
+ assert_eq!(registry.build_count(id), 1);
+ assert_eq!(registry.materialization_count(id), 1);
+ assert_eq!(lazy_getter_calls(), 0);
+ });
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs b/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs
index a810597e7..715701dd3 100644
--- a/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/notification_runtime.rs
@@ -276,13 +276,13 @@ pub(in crate::context_bootstrap) fn install_notification_template_bindings<'s>(
NotificationPrototypeDeclaration::initialize_prototype_template(scope, prototype);
}
-pub(in crate::context_bootstrap) fn install_notification_realm_bindings(
- scope: &mut v8::PinScope<'_, '_>,
-) {
- if let Some(constructor) = global_constructor_object(scope, "Notification") {
- let _ =
- NotificationConstructorPermissionDeclaration::default().initialize(scope, constructor);
- }
+pub(in crate::context_bootstrap) fn finalize_notification_realm_bindings<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ constructor: v8::Local<'s, v8::Object>,
+) -> anyhow::Result<()> {
+ NotificationConstructorPermissionDeclaration::default()
+ .initialize(scope, constructor)
+ .map_err(|error| anyhow::anyhow!("failed to finalize Notification: {error}"))
}
fn notification_options<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
index a857310ed..1feaa3522 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
@@ -439,10 +439,10 @@ pub(super) fn apply_pending_window_performance_state<'s>(
pub(crate) fn finalize_performance_observer_realm_bindings<'s>(
scope: &mut v8::PinScope<'s, '_>,
constructor: v8::Local<'s, v8::Object>,
-) {
+) -> anyhow::Result<()> {
PerformanceObserverConstructorDeclaration::new(PERFORMANCE_OBSERVER_SUPPORTED_ENTRY_TYPES)
.initialize(scope, constructor)
- .expect("PerformanceObserver constructor declaration should initialize");
+ .map_err(|error| anyhow::anyhow!("failed to finalize PerformanceObserver: {error}"))
}
fn performance_navigation_timing_type(navigation_type: &str) -> &'static str {
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index f929a920c..d4f3425cb 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -2046,21 +2046,19 @@ pub(crate) fn finish_context_bootstrap(
pub(crate) fn set_interface_prototype_constructor<'s>(
scope: &mut v8::PinScope<'s, '_>,
- constructor: v8::Local<'s, v8::Function>,
+ prototype: v8::Local<'s, v8::Object>,
public_constructor: v8::Local<'s, v8::Value>,
-) {
- let Some(prototype) = constructor
- .get(scope, v8str(scope, "prototype").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return;
- };
- let _ = prototype.define_own_property(
+) -> Result<()> {
+ if prototype.define_own_property(
scope,
v8str(scope, "constructor").into(),
public_constructor,
v8::PropertyAttribute::DONT_ENUM,
- );
+ ) != Some(true)
+ {
+ return Err(anyhow!("failed to set intrinsic prototype constructor"));
+ }
+ Ok(())
}
pub(crate) fn window_realm_secure_context_available<'s>(
diff --git a/moli-renderer-v8/src/network_host/xhr.rs b/moli-renderer-v8/src/network_host/xhr.rs
index 59cf9a473..b2e1dfab8 100644
--- a/moli-renderer-v8/src/network_host/xhr.rs
+++ b/moli-renderer-v8/src/network_host/xhr.rs
@@ -8,10 +8,10 @@ mod send;
use super::*;
use crate::context_bootstrap::{
- install_simple_event_target_ordered_handlers, mark_simple_event_target_slot,
+ SIMPLE_EVENT_TARGET_ORDERED_HANDLERS_SLOT, SIMPLE_EVENT_TARGET_SLOT,
};
use crate::native_bridge::throw_dom_exception;
-use crate::util::{get_private_value, set_private_value};
+use crate::util::{get_private_value, private_key};
use crate::web_api_interfaces;
use crate::worker::WORKER_STATE_SLOT;
use moli_webapi_declare::WebApiFunctionTemplate;
@@ -96,20 +96,26 @@ pub(crate) fn install_progress_event_template_bindings<'s>(
pub(crate) fn finalize_xml_http_request_event_target_realm_bindings<'s>(
scope: &mut v8::PinScope<'s, '_>,
event_target_prototype: v8::Local<'s, v8::Object>,
-) {
- mark_simple_event_target_slot(
- scope,
- event_target_prototype,
- XHR_SIMPLE_EVENT_TARGET_LISTENERS_SLOT,
- );
- install_simple_event_target_ordered_handlers(scope, event_target_prototype);
- let marker = v8::Boolean::new(scope, true);
- set_private_value(
- scope,
- event_target_prototype,
- XHR_SIMPLE_EVENT_TARGET_MARKER_SLOT,
- marker.into(),
- );
+) -> anyhow::Result<()> {
+ let marker: v8::Local<'_, v8::Value> = v8::Boolean::new(scope, true).into();
+ for (slot, value) in [
+ (
+ SIMPLE_EVENT_TARGET_SLOT,
+ v8str(scope, XHR_SIMPLE_EVENT_TARGET_LISTENERS_SLOT).into(),
+ ),
+ (SIMPLE_EVENT_TARGET_ORDERED_HANDLERS_SLOT, marker),
+ (XHR_SIMPLE_EVENT_TARGET_MARKER_SLOT, marker),
+ ] {
+ let key = private_key(scope, slot).ok_or_else(|| {
+ anyhow::anyhow!("failed to allocate XMLHttpRequestEventTarget slot `{slot}`")
+ })?;
+ if event_target_prototype.set_private(scope, key, value) != Some(true) {
+ return Err(anyhow::anyhow!(
+ "failed to finalize XMLHttpRequestEventTarget slot `{slot}`"
+ ));
+ }
+ }
+ Ok(())
}
pub(crate) fn xhr_throw_invalid_state(scope: &mut v8::PinScope<'_, '_>, message: &'static str) {
diff --git a/moli-webapi-declare/src/property.rs b/moli-webapi-declare/src/property.rs
index 0e6d1f004..9dbc784af 100644
--- a/moli-webapi-declare/src/property.rs
+++ b/moli-webapi-declare/src/property.rs
@@ -94,11 +94,13 @@ pub fn define_declared_data_property<'s, V>(
where
V: WebApiValue<'s> + ?Sized,
{
- let value = value
- .to_v8_value(scope)
- .ok_or_else(|| BindError::new(format!("failed to convert `{name}` value")))?;
- define_value_property(scope, object, name, value);
- Ok(())
+ define_declared_data_property_with_attributes(
+ scope,
+ object,
+ name,
+ value,
+ v8::PropertyAttribute::DONT_ENUM,
+ )
}
pub fn define_declared_enumerable_data_property<'s, V>(
@@ -110,11 +112,13 @@ pub fn define_declared_enumerable_data_property<'s, V>(
where
V: WebApiValue<'s> + ?Sized,
{
- let value = value
- .to_v8_value(scope)
- .ok_or_else(|| BindError::new(format!("failed to convert `{name}` value")))?;
- define_enumerable_value_property(scope, object, name, value);
- Ok(())
+ define_declared_data_property_with_attributes(
+ scope,
+ object,
+ name,
+ value,
+ v8::PropertyAttribute::NONE,
+ )
}
pub fn define_declared_data_property_with_attributes<'s, V>(
diff --git a/moli-webapi-declare/tests/declare.rs b/moli-webapi-declare/tests/declare.rs
index a1769e0b6..5d28343fa 100644
--- a/moli-webapi-declare/tests/declare.rs
+++ b/moli-webapi-declare/tests/declare.rs
@@ -289,6 +289,16 @@ struct NestedValueRecord {
count: u32,
}
+#[derive(WebApiObject)]
+#[webapi(plain)]
+struct DeclaredDataProperties {
+ #[webapi(data_property)]
+ value: Option<u32>,
+
+ #[webapi(data_property, enumerable)]
+ enumerable_value: Option<u32>,
+}
+
#[derive(WebApiObject)]
#[webapi(plain)]
struct DefaultNameObject<'scope> {
@@ -579,6 +589,48 @@ struct PrototypeBackedFallbackTagObject {}
)]
struct MissingPrototypeFallbackTagObject {}
+#[test]
+fn declared_data_properties_report_rejected_writes() {
+ ensure_v8();
+ let mut isolate = v8::Isolate::new(v8::CreateParams::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+
+ for (name, declaration) in [
+ (
+ "value",
+ DeclaredDataProperties {
+ value: Some(42),
+ enumerable_value: None,
+ },
+ ),
+ (
+ "enumerableValue",
+ DeclaredDataProperties {
+ value: None,
+ enumerable_value: Some(42),
+ },
+ ),
+ ] {
+ let target = v8::Object::new(scope);
+ assert_eq!(
+ target.set_integrity_level(scope, v8::IntegrityLevel::Frozen),
+ Some(true)
+ );
+ let error = declaration
+ .initialize(scope, target)
+ .expect_err("rejected property writes must fail initialization");
+ assert_eq!(
+ error.to_string(),
+ format!("failed to define `{name}` value")
+ );
+ let key = v8::String::new(scope, name).unwrap();
+ assert_eq!(target.has_own_property(scope, key.into()), Some(false));
+ }
+}
+
#[test]
fn declared_template_and_object_have_expected_surface() {
ensure_v8();