Truly independent web browser
LibWeb: Reject binding failures in the current realm
Shannon Booth80c91d43b8fb
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rsindex b122b5de39a..64603bc410a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rs@@ -171,16 +171,6 @@ fn default_async_iterator_of<T: DefaultAsyncIteratorClasses>(object: Gc<Object>)unsafe { T::ASYNC_ITERATOR_CELL_CLASS.downcast(host_data) }}-/// The realm that the "next" and "return" methods create their promise in, as LibWeb's C++ bindings do: the realm of-/// the this value, or the current realm for a this value that is not an object.-fn this_value_realm(vm: &Vm) -> Gc<Realm> {- let this_value = vm.this_value();- if this_value.is_object() {- return this_value.as_object().shape().realm();- }- vm.current_realm().expect("a native function runs in a realm")-}-/// The steps of a built-in function that the iterator creates, given its captures.type BuiltinSteps<C> = fn(&Vm, C) -> ThrowCompletionOr<Value>;@@ -250,7 +240,8 @@ fn promise_of(object: Gc<Object>) -> Gc<Promise> {pub(crate) fn async_iterator_next<T: DefaultAsyncIteratorClasses>(vm: &Vm) -> ThrowCompletionOr<Value> {// 1. Let interface be the interface for which the asynchronous iterator prototype object exists.// 2. Let thisValidationPromiseCapability be ! NewPromiseCapability(%Promise%).- let this_validation_promise_capability = create_promise(vm, this_value_realm(vm));+ let this_validation_promise_capability =+ create_promise(vm, vm.current_realm().expect("a native function runs in a realm"));// 3. Let thisValue be the this value.// 4. Let object be Completion(ToObject(thisValue)).@@ -379,7 +370,7 @@ pub(crate) fn async_iterator_return<T: DefaultAsyncIteratorClasses>(vm: &Vm) ->// 1. Let interface be the interface for which the asynchronous iterator prototype object exists.// 2. Let returnPromiseCapability be ! NewPromiseCapability(%Promise%).- let return_promise_capability = create_promise(vm, this_value_realm(vm));+ let return_promise_capability = create_promise(vm, vm.current_realm().expect("a native function runs in a realm"));// 3. Let thisValue be the this value.// 4. Let object be Completion(ToObject(thisValue)).diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex d49313429b6..d8b150f0997 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -24,7 +24,7 @@ use ak::Utf16FlyString;use libjs_rust::api::{Attribute, DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, ExternalMemorySize,FunctionObject, Gc, HostObject, JSHostClass, Object, PrimitiveString, PropertyAttributes, PropertyKey,- RawNativeFunction, RawNativeFunctionPointer, Realm, Throw, ThrowCompletionOr, Trace, Value, Vm, get_function_realm,+ RawNativeFunction, RawNativeFunctionPointer, Realm, ThrowCompletionOr, Trace, Value, Vm, get_function_realm,host_class_of, host_data_of, is_host_instance_of,};@@ -32,8 +32,8 @@ use crate::bindings::CallContext;use crate::bindings::realm_data::wrapper_world_of;use crate::bindings::services::{web_bindings_define_unforgeable_attributes, web_bindings_ensure_web_constructor, web_bindings_ensure_web_prototype,- web_bindings_realm_is_secure_context, web_bindings_realm_is_window, web_bindings_rejected_promise,- web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper, web_bindings_with_temporary_execution_context,+ web_bindings_realm_is_secure_context, web_bindings_realm_is_window, web_bindings_rust_wrapper_for,+ web_bindings_set_rust_wrapper, web_bindings_with_temporary_execution_context,};/// What an implementation can tell the bindings about its objects, as a C++ implementation object does by overriding@@ -436,23 +436,6 @@ fn run_with_temporary_execution_context<F: FnOnce() -> R, R>(realm: Gc<Realm>, ccontext.1.expect("LibWeb runs the steps")}-/// What an operation that returns a promise type returns in place of throwing: a promise rejected with what its-/// steps threw, https://webidl.spec.whatwg.org/#dfn-create-operation-function-pub(crate) fn rejected_promise(vm: &Vm, throw: Throw) -> Value {- let current_realm = vm.current_realm().expect("a native function runs in a realm");- // SAFETY: The realm is live, and the values are live while the native function runs.- let promise = unsafe {- web_bindings_rejected_promise(- current_realm.as_ptr().cast(),- vm.this_value().to_raw(),- throw.value().to_raw(),- )- };- let promise = NonNull::new(promise.cast::<Object>()).expect("LibWeb returns the promise");- // SAFETY: LibWeb returns a live promise.- Value::from_object(unsafe { Gc::from_non_null(promise) })-}-/// The interface prototype object of the interface in the realm.pub(crate) fn interface_prototype_object(realm: Gc<Realm>, interface_name: u16) -> Gc<Object> {// SAFETY: The realm is live, and the interface is implemented in Rust.diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rsindex 49ecc22dfb7..5b3f2f08e2d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs@@ -78,12 +78,4 @@ unsafe extern "C" {name: ak::Span<'_, u8>,message: usize,) -> *mut c_void;-- /// A promise rejected with the reason, in the realm of the this value of an operation that ran in the current- /// realm: the realm of the object, or the current realm for a value that is not an object.- pub(crate) fn web_bindings_rejected_promise(- current_realm: *mut c_void,- this_value: u64,- reason: u64,- ) -> *mut c_void;}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 8af342bca37..751cdd70972 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -79,7 +79,6 @@ extern "C" {void* web_bindings_wrapper_world(void* realm, bool* is_main_world);JSObject* web_bindings_rust_wrapper_for(void* realm, void* cell);void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper);-JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason);void web_bindings_queue_a_microtask(void* realm, JSObject* function);void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*));void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*));@@ -277,17 +276,6 @@ bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origireturn true;}-JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason)-{- auto& realm = *static_cast<JS::Realm*>(current_realm);- auto promise_realm_this_value = JS::HostABI::value_from_abi(this_value);- if (promise_realm_this_value.is_nullish())- promise_realm_this_value = &realm.global_object();- auto& promise_realm = this_value_realm(realm, promise_realm_this_value);- auto promise = WebIDL::create_rejected_promise(promise_realm, JS::HostABI::value_from_abi(reason));- return JS::HostABI::object_to_abi(promise->promise().ptr());-}-void web_bindings_queue_a_microtask(void* realm, JSObject* function){GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);diff --git a/Meta/Generators/libweb_bindings/REALM_POLICY.md b/Meta/Generators/libweb_bindings/REALM_POLICY.mdindex 494f294cd66..fa36836459f 100644--- a/Meta/Generators/libweb_bindings/REALM_POLICY.md+++ b/Meta/Generators/libweb_bindings/REALM_POLICY.md@@ -5,7 +5,8 @@ Generated bindings make one explicit realm decision per IDL member.- Instance operations and attributes default to the validated receiver realm(`this_object_realm`). This realm is used for implementation calls,DOMException wrapping, JavaScript return-value wrapping, and promise- creation/rejection for promise-typed members.+ creation for promise-typed members. A promise-typed member that throws+ rejects in the caller/current realm, as WebIDL specifies.- Generated pair-iterable, async-iterable, maplike, and setlike helpers use thereceiver realm for iterator/container creation and wrapped values.- Static operations, constructors, and namespace members use the caller/currentdiff --git a/Meta/Generators/libweb_bindings/attributes.py b/Meta/Generators/libweb_bindings/attributes.pyindex 6c8811fbd44..6909ecf9c12 100644--- a/Meta/Generators/libweb_bindings/attributes.py+++ b/Meta/Generators/libweb_bindings/attributes.py@@ -590,18 +590,10 @@ def write_attribute_getter(if attribute_type_is_promise:if getter_prelude or getter_cache_check:raise RuntimeError(f"Unsupported cached promise attribute '{attribute.name}' on '{interface.name}'")- if getter_realm_argument == "realm":- promise_realm_setup = "[[maybe_unused]] auto& promise_realm = realm;"- else:- promise_realm_setup = """auto promise_realm_this_value = vm.this_value();- if (promise_realm_this_value.is_nullish())- promise_realm_this_value = &realm.global_object();- [[maybe_unused]] auto& promise_realm = this_value_realm(realm, promise_realm_this_value);"""out.write(f"""JS_DEFINE_NATIVE_FUNCTION({receiver_class}::{attribute_getter_callback_name(attribute)}){{[[maybe_unused]] auto& realm = *vm.current_realm();- {promise_realm_setup}auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {{[[maybe_unused]] {fully_qualified_name_for_interface(interface)}* idl_object = nullptr;@@ -631,11 +623,11 @@ def write_attribute_getter(auto maybe_R = steps();if (maybe_R.is_throw_completion())- return WebIDL::create_rejected_promise(promise_realm, maybe_R.error_value())->promise();+ return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();auto R = maybe_R.release_value();- return {to_javascript_value(attribute.type, "R", includes, context, "promise_realm")};+ return {to_javascript_value(attribute.type, "R", includes, context, "realm")};}}"""diff --git a/Meta/Generators/libweb_bindings/operations.py b/Meta/Generators/libweb_bindings/operations.pyindex 21916964fed..40c843638c0 100644--- a/Meta/Generators/libweb_bindings/operations.py+++ b/Meta/Generators/libweb_bindings/operations.py@@ -464,17 +464,9 @@ def write_operation()if should_wrap_promise_rejections:includes.add("LibWeb/WebIDL/Promise.h")- if operation_invokes_as_static or interface.is_namespace or "NeedsCallerRealm" in operation.extended_attributes:- promise_realm_setup = "[[maybe_unused]] auto& promise_realm = realm;"- else:- promise_realm_setup = """auto promise_realm_this_value = vm.this_value();- if (promise_realm_this_value.is_nullish())- promise_realm_this_value = &realm.global_object();- [[maybe_unused]] auto& promise_realm = this_value_realm(realm, promise_realm_this_value);"""out.write(- f""" {promise_realm_setup}-- auto steps = [&realm, &vm]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> {{+ """+ auto steps = [&realm, &vm]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> {(void)realm;""")@@ -577,10 +569,10 @@ def write_operation(// 1. If op has a return type that is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).// 2. Otherwise, end these steps and allow the exception to propagate.if (maybe_R.is_throw_completion())- return WebIDL::create_rejected_promise(promise_realm, maybe_R.error_value())->promise();+ return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();auto R = maybe_R.release_value();- return {to_javascript_value(operation.return_type, "R", includes, context, "promise_realm")};+ return {to_javascript_value(operation.return_type, "R", includes, context, "realm")};}}"""@@ -641,7 +633,7 @@ def write_operation(// 1. If op has a return type that is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).// 2. Otherwise, end these steps and allow the exception to propagate.if (maybe_R.is_throw_completion())- return WebIDL::create_rejected_promise(promise_realm, maybe_R.error_value())->promise();+ return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();return maybe_R.release_value()->promise();}}@@ -661,9 +653,9 @@ def write_operation(// 1. If op has a return type that is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).// 2. Otherwise, end these steps and allow the exception to propagate.if (maybe_R.is_throw_completion())- return WebIDL::create_rejected_promise(promise_realm, maybe_R.error_value())->promise();+ return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();- return {to_javascript_value(operation.return_type, "maybe_R.release_value()", includes, context, "promise_realm")};+ return {to_javascript_value(operation.return_type, "maybe_R.release_value()", includes, context, "realm")};}}"""diff --git a/Meta/Generators/libweb_bindings/overload_resolution.py b/Meta/Generators/libweb_bindings/overload_resolution.pyindex 97efd8aac80..36bf68d4ee4 100644--- a/Meta/Generators/libweb_bindings/overload_resolution.py+++ b/Meta/Generators/libweb_bindings/overload_resolution.py@@ -14,7 +14,6 @@ from Generators.libweb_bindings.cpp_types import idl_identifier_cpp_namefrom Generators.libweb_bindings.cpp_types import is_numeric_typefrom Generators.libweb_bindings.cpp_types import is_string_typefrom Generators.libweb_bindings.includes import GeneratedIncludes-from Generators.libweb_bindings.realms import member_realm_exprfrom Utils.webidl_parser import Constructorfrom Utils.webidl_parser import IDLParameterizedTypefrom Utils.webidl_parser import IDLType@@ -139,21 +138,8 @@ def write_overload_arbiter(# Web IDL overload sets cannot mix promise and non-promise return types.should_wrap_promise_rejections = operation.return_type_is_promise()- promise_realm_setup = ""if should_wrap_promise_rejections:includes.add("LibWeb/WebIDL/Promise.h")- realm_argument = member_realm_expr(- operation,- interface=interface,- is_static=emit_as_static or interface.is_namespace,- )- if realm_argument == "realm":- promise_realm_setup = "[[maybe_unused]] auto& promise_realm = realm;"- else:- promise_realm_setup = """auto promise_realm_this_value = vm.this_value();- if (promise_realm_this_value.is_nullish())- promise_realm_this_value = &realm.global_object();- [[maybe_unused]] auto& promise_realm = this_value_realm(realm, promise_realm_this_value);"""out.write(f"""JS_DEFINE_NATIVE_FUNCTION({receiver_class}::{idl_identifier_cpp_name(operation)})@@ -163,10 +149,9 @@ def write_overload_arbiter()if should_wrap_promise_rejections:out.write(- f""" [[maybe_unused]] auto& realm = *vm.current_realm();- {promise_realm_setup}+ """ [[maybe_unused]] auto& realm = *vm.current_realm();- auto steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {{+ auto steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {""")write_overload_resolution_switch(out, context, interface, operations)@@ -190,7 +175,7 @@ def write_overload_arbiter(auto maybe_result = steps();if (maybe_result.is_throw_completion())- return WebIDL::create_rejected_promise(promise_realm, maybe_result.error_value())->promise();+ return WebIDL::create_rejected_promise(realm, maybe_result.error_value())->promise();return maybe_result.release_value();""")diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 10a3216840e..dabfe77604c 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -1139,7 +1139,7 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]define_attribute, define_cached_attribute, define_constants, define_indexed_properties_iterator,define_interface_object_properties, define_operation, define_to_string_tag, define_unimplemented_property,define_value_iterator_properties, entry_point_arguments, implementation_if, implementation_of,- prototype_from_new_target, realm_is_secure_context, realm_is_window, rejected_promise, set_dictionary_member,+ prototype_from_new_target, realm_is_secure_context, realm_is_window, set_dictionary_member,set_interface_prototype_object_prototype, this_object, to_interface,};use crate::bindings::async_iterable::{@@ -1152,7 +1152,7 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]};use crate::bindings::callback::{CallbackFunction, CallbackInterface, PromiseCallbackFunction};use crate::bindings::event_target::{event_handler_attribute, set_event_handler_attribute};- use crate::bindings::promise::WebIdlPromise;+ use crate::bindings::promise::{WebIdlPromise, create_rejected_promise};use crate::bindings::{CallContext, WebIdlResult, with_custom_element_reactions};"""@@ -1191,7 +1191,10 @@ def write_rust_operation_set(fn {operation_set.function}(vm: &Vm) -> ThrowCompletionOr<Value> {{// An exception that the overload resolution of an operation with a promise type throws rejects a new promise,// https://webidl.spec.whatwg.org/#dfn-create-operation-function- {resolution}(vm).or_else(|throw| Ok(rejected_promise(vm, throw)))+ {resolution}(vm).or_else(|throw| {{+ let realm = vm.current_realm().expect("a native function runs in a realm");+ Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()))+ }})}}""")@@ -1282,7 +1285,10 @@ def write_rust_interface(Ok(this) => this,// If the attribute's type is a promise type, a this value that does not implement the interface rejects// a new promise.- Err(throw) => return Ok(rejected_promise(vm, throw)),+ Err(throw) => {+ let realm = vm.current_realm().expect("a native function runs in a realm");+ return Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()));+ }}"""receiver = "(implementation, mut cx)"caller_realm_context = ""@@ -2043,7 +2049,10 @@ def write_rust_static_operation(// https://webidl.spec.whatwg.org/#dfn-create-operation-functionlet steps = || -> ThrowCompletionOr<Value> {{{textwrap.indent(steps.getvalue(), " ")} }};- steps().or_else(|throw| Ok(rejected_promise(vm, throw)))+ steps().or_else(|throw| {{+ let realm = vm.current_realm().expect("a native function runs in a realm");+ Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()))+ }})""")else:@@ -2357,7 +2366,10 @@ def write_rust_operation(// https://webidl.spec.whatwg.org/#dfn-create-operation-functionlet steps = || -> ThrowCompletionOr<Value> {{{textwrap.indent(steps.getvalue(), " ")} }};- steps().or_else(|throw| Ok(rejected_promise(vm, throw)))+ steps().or_else(|throw| {{+ let realm = vm.current_realm().expect("a native function runs in a realm");+ Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()))+ }})""")else:diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex f1668d5260a..364f1fede61 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -4,6 +4,7 @@ Text/input/PDF/jbig2-image.html[LoadFromHttpServer]; A data: iframe stays in this process only under an http: page.+Text/input/HTML/cross-origin-rejected-promise-realm.htmlText/input/HTML/dynamic-function-foreign-prototype-realm.htmlText/input/wpt-import/web-locks/acquire.https.any.worker.htmlText/input/wpt-import/web-locks/signal.https.any.worker.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/cross-origin-rejected-promise-realm.txt b/Tests/LibWeb/Text/expected/HTML/cross-origin-rejected-promise-realm.txtnew file mode 100644index 00000000000..4c89a407b6a--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/cross-origin-rejected-promise-realm.txt@@ -0,0 +1,8 @@+cross-origin frame: true+same-process frame: true+Blob.prototype.text: true true+FontFace.prototype.load: true true+FontFace.prototype.loaded: true true+FontFaceSet.prototype.ready: true true+ReadableStream async iterator next: true true+ReadableStream async iterator return: true truediff --git a/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txt b/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txtindex ba77320fc41..aa226989b45 100644--- a/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txt+++ b/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txt@@ -1,5 +1,5 @@-decodingInfo promise is iframe realm: false-decodingInfo promise is parent realm: true+decodingInfo promise is iframe realm: true+decodingInfo promise is parent realm: falsedecodingInfo rejection is iframe realm: falsedecodingInfo rejection is parent realm: truedecodingInfo rejection message: Required property type is missing or undefineddiff --git a/Tests/LibWeb/Text/input/HTML/cross-origin-rejected-promise-realm.html b/Tests/LibWeb/Text/input/HTML/cross-origin-rejected-promise-realm.htmlnew file mode 100644index 00000000000..f499cfd24b0--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/cross-origin-rejected-promise-realm.html@@ -0,0 +1,44 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ const iframe = document.createElement("iframe");+ iframe.onload = async () => {+ const crossOriginWindow = iframe.contentWindow;++ let crossOrigin = false;+ try {+ crossOriginWindow.document;+ } catch (e) {+ crossOrigin = e instanceof DOMException;+ }+ println(`cross-origin frame: ${crossOrigin}`);++ println(`same-process frame: ${remoteFrameCount() === 0}`);++ const asyncIteratorPrototype = Object.getPrototypeOf(new ReadableStream().values());+ const members = {+ "Blob.prototype.text": Blob.prototype.text,+ "FontFace.prototype.load": FontFace.prototype.load,+ "FontFace.prototype.loaded": Object.getOwnPropertyDescriptor(FontFace.prototype, "loaded").get,+ "FontFaceSet.prototype.ready": Object.getOwnPropertyDescriptor(FontFaceSet.prototype, "ready").get,+ "ReadableStream async iterator next": asyncIteratorPrototype.next,+ "ReadableStream async iterator return": asyncIteratorPrototype.return,+ };+ for (const [name, member] of Object.entries(members)) {+ const promise = member.call(crossOriginWindow);+ const inCurrentRealm = promise.constructor === Promise && promise.constructor.constructor === Function;+ let rejectedWithTypeError = false;+ try {+ await promise;+ } catch (e) {+ rejectedWithTypeError = e instanceof TypeError;+ }+ println(`${name}: ${inCurrentRealm} ${rejectedWithTypeError}`);+ }+ done();+ };+ iframe.src = "data:text/html,<!DOCTYPE html><title>victim</title>";+ document.body.appendChild(iframe);+ });+</script>