Truly independent web browser
LibWeb: Stop cached cross-origin descriptors keeping callers alive
Shannon Boothea3dc927bdb3
diff --git a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cppindex 6704e69f380..b420612d5f1 100644--- a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp+++ b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp@@ -8,6 +8,7 @@#include <AK/Variant.h>#include <AK/Vector.h>#include <LibGC/CellAllocator.h>+#include <LibGC/HeapBlock.h>#include <LibJS/Runtime/AbstractOperations.h>#include <LibJS/Runtime/Completion.h>#include <LibJS/Runtime/Error.h>@@ -180,40 +181,57 @@ bool is_platform_object_same_origin(RemoteWindow const&)return false;}-class CrossOriginPropertyDescriptorMapCell final : public GC::Cell {- GC_CELL(CrossOriginPropertyDescriptorMapCell, GC::Cell);- GC_DECLARE_ALLOCATOR(CrossOriginPropertyDescriptorMapCell);+GC_DEFINE_ALLOCATOR(CrossOriginPropertyDescriptorMap);-public:- using JSValueConversionIsForbidden = void;+CrossOriginPropertyDescriptorMap::CrossOriginPropertyDescriptorMap()+ : GC::WeakContainer(heap())+{+}- CrossOriginPropertyDescriptorMap& map() { return m_map; }+Optional<JS::PropertyDescriptor> CrossOriginPropertyDescriptorMap::get(CrossOriginKey const& key) const+{+ return m_descriptors.get(key).copy();+}-private:- CrossOriginPropertyDescriptorMapCell() = default;+void CrossOriginPropertyDescriptorMap::set(CrossOriginKey const& key, JS::PropertyDescriptor descriptor)+{+ m_descriptors.set(key, move(descriptor));+}- virtual void visit_edges(Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(m_map);+void CrossOriginPropertyDescriptorMap::visit_edges(Visitor& visitor)+{+ Base::visit_edges(visitor);+ for (auto const& [key, descriptor] : m_descriptors) {+ auto& current_settings_object = *key.current_settings_object;+ if (descriptor.value.has_value())+ visitor.visit_ephemeron(current_settings_object, *descriptor.value);+ if (descriptor.get.has_value() && *descriptor.get)+ visitor.visit_ephemeron(current_settings_object, JS::Value { descriptor.get->ptr() });+ if (descriptor.set.has_value() && *descriptor.set)+ visitor.visit_ephemeron(current_settings_object, JS::Value { descriptor.set->ptr() });}+}- CrossOriginPropertyDescriptorMap m_map;-};--GC_DEFINE_ALLOCATOR(CrossOriginPropertyDescriptorMapCell);+void CrossOriginPropertyDescriptorMap::remove_dead_cells(Badge<GC::Heap>)+{+ m_descriptors.remove_all_matching([&](CrossOriginKey const& key, JS::PropertyDescriptor const&) {+ auto const& current_settings_object = *key.current_settings_object;+ auto* block = GC::HeapBlock::from_cell(¤t_settings_object);+ return !heap().is_live_heap_block(block) || current_settings_object.state() != Cell::State::Live || !current_settings_object.is_marked();+ });+}CrossOriginPropertyDescriptorMap& cross_origin_property_descriptor_map(JS::HostObject& location_or_window_wrapper){- if (auto* cell = JS::host_data_if<CrossOriginPropertyDescriptorMapCell>(location_or_window_wrapper))- return cell->map();+ if (auto* map = JS::host_data_if<CrossOriginPropertyDescriptorMap>(location_or_window_wrapper))+ return *map;VERIFY(JS::is_host_instance_of(location_or_window_wrapper, Bindings::location_wrapper_host_class)|| JS::is_host_instance_of(location_or_window_wrapper, Bindings::window_wrapper_host_class));VERIFY(!location_or_window_wrapper.host_data());- auto cell = location_or_window_wrapper.heap().allocate<CrossOriginPropertyDescriptorMapCell>();- location_or_window_wrapper.set_host_data(cell);- return cell->map();+ auto map = location_or_window_wrapper.heap().allocate<CrossOriginPropertyDescriptorMap>();+ location_or_window_wrapper.set_host_data(map);+ return *map;}// 7.2.3.4 CrossOriginGetOwnPropertyHelper ( O, P ), https://html.spec.whatwg.org/multipage/nav-history-apis.html#crossorigingetownpropertyhelper-(-o,-p-)@@ -230,7 +248,7 @@ static Optional<JS::PropertyDescriptor> cross_origin_get_own_property_helper_imp// entry of the RemoteWindow's map.auto relevant_settings_object = platform_object.has<HTML::RemoteWindow*>() ? 0 : (FlatPtr)&HTML::relevant_settings_object(*object_ptr);auto cross_origin_key = CrossOriginKey {- .current_settings_object = (FlatPtr)&HTML::current_settings_object(),+ .current_settings_object = HTML::current_settings_object(),.relevant_settings_object = relevant_settings_object,.property_key = property_key,};@@ -251,9 +269,8 @@ static Optional<JS::PropertyDescriptor> cross_origin_get_own_property_helper_impcontinue;// 1. If the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O contains an entry whose key is crossOriginKey, then return that entry's value.- auto it = cross_origin_property_descriptor_map.find(cross_origin_key);- if (it != cross_origin_property_descriptor_map.end())- return it->value.descriptor;+ if (auto descriptor = cross_origin_property_descriptor_map.get(cross_origin_key); descriptor.has_value())+ return descriptor;// 2. Let originalDesc be OrdinaryGetOwnProperty(O, P).// NB: originalDesc might have been replaced by page script, for example via [Replaceable], so the functions@@ -307,7 +324,7 @@ static Optional<JS::PropertyDescriptor> cross_origin_get_own_property_helper_imp}// 6. Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O with key crossOriginKey and value crossOriginDesc.- cross_origin_property_descriptor_map.set(cross_origin_key, CrossOriginCachedPropertyDescriptor { cross_origin_descriptor });+ cross_origin_property_descriptor_map.set(cross_origin_key, cross_origin_descriptor);// 7. Return crossOriginDesc.return cross_origin_descriptor;diff --git a/Libraries/LibWeb/HTML/CrossOrigin/CrossOriginPropertyDescriptorMap.h b/Libraries/LibWeb/HTML/CrossOrigin/CrossOriginPropertyDescriptorMap.hindex e28d74e6433..86f08d795e0 100644--- a/Libraries/LibWeb/HTML/CrossOrigin/CrossOriginPropertyDescriptorMap.h+++ b/Libraries/LibWeb/HTML/CrossOrigin/CrossOriginPropertyDescriptorMap.h@@ -7,13 +7,19 @@#pragma once#include <AK/Forward.h>+#include <AK/HashMap.h>#include <AK/Optional.h>#include <AK/Traits.h>#include <AK/Utf16FlyString.h>#include <LibGC/Cell.h>+#include <LibGC/CellAllocator.h>+#include <LibGC/Ptr.h>+#include <LibGC/WeakContainer.h>#include <LibJS/Forward.h>#include <LibJS/Runtime/PropertyDescriptor.h>#include <LibJS/Runtime/PropertyKey.h>+#include <LibWeb/Export.h>+#include <LibWeb/Forward.h>namespace Web::HTML {@@ -24,23 +30,36 @@ struct CrossOriginProperty {};struct CrossOriginKey {- FlatPtr current_settings_object;+ GC::RawRef<EnvironmentSettingsObject> current_settings_object;FlatPtr relevant_settings_object;JS::PropertyKey property_key;};-struct CrossOriginCachedPropertyDescriptor {- explicit CrossOriginCachedPropertyDescriptor(JS::PropertyDescriptor descriptor)- : descriptor(move(descriptor))- {- }+// The [[CrossOriginPropertyDescriptorMap]] internal slot of a Location or Window object.+// AD-HOC: The functions of a descriptor are of the realm of its key's current settings object, which they keep alive.+// An entry lives only while something else keeps that settings object alive, so that the map does not keep+// alive the document of every script that ever read a cross-origin property of the object.+class WEB_API CrossOriginPropertyDescriptorMap final+ : public GC::Cell+ , public GC::WeakContainer {+ GC_CELL(CrossOriginPropertyDescriptorMap, GC::Cell);+ GC_DECLARE_ALLOCATOR(CrossOriginPropertyDescriptorMap);- void visit_edges(GC::Cell::Visitor& visitor) { descriptor.visit_edges(visitor); }+public:+ using JSValueConversionIsForbidden = void;- JS::PropertyDescriptor descriptor;-};+ Optional<JS::PropertyDescriptor> get(CrossOriginKey const&) const;+ void set(CrossOriginKey const&, JS::PropertyDescriptor);-using CrossOriginPropertyDescriptorMap = HashMap<CrossOriginKey, CrossOriginCachedPropertyDescriptor>;+private:+ CrossOriginPropertyDescriptorMap();++ virtual void visit_edges(Visitor&) override;+ virtual GC::Cell const& owner_cell(Badge<GC::Heap>) const override { return *this; }+ virtual void remove_dead_cells(Badge<GC::Heap>) override;++ HashMap<CrossOriginKey, JS::PropertyDescriptor> m_descriptors;+};}@@ -52,7 +71,7 @@ struct Traits<Web::HTML::CrossOriginKey> : public DefaultTraits<Web::HTML::Cross{return pair_int_hash(Traits<JS::PropertyKey>::hash(key.property_key),- pair_int_hash(ptr_hash(key.current_settings_object), ptr_hash(key.relevant_settings_object)));+ pair_int_hash(ptr_hash(key.current_settings_object.ptr()), ptr_hash(key.relevant_settings_object)));}static bool equals(Web::HTML::CrossOriginKey const& a, Web::HTML::CrossOriginKey const& b)diff --git a/Libraries/LibWeb/HTML/RemoteWindow.cpp b/Libraries/LibWeb/HTML/RemoteWindow.cppindex 09e649f0236..fb0cbeb903e 100644--- a/Libraries/LibWeb/HTML/RemoteWindow.cpp+++ b/Libraries/LibWeb/HTML/RemoteWindow.cpp@@ -41,6 +41,13 @@ void RemoteWindow::visit_edges(Cell::Visitor& visitor)visitor.visit(m_cross_origin_property_descriptor_map);}+CrossOriginPropertyDescriptorMap& RemoteWindow::cross_origin_property_descriptor_map()+{+ if (!m_cross_origin_property_descriptor_map)+ m_cross_origin_property_descriptor_map = heap().allocate<CrossOriginPropertyDescriptorMap>();+ return *m_cross_origin_property_descriptor_map;+}+// https://html.spec.whatwg.org/multipage/nav-history-apis.html#window-navigableGC::Ptr<RemoteNavigable> RemoteWindow::navigable() const{diff --git a/Libraries/LibWeb/HTML/RemoteWindow.h b/Libraries/LibWeb/HTML/RemoteWindow.hindex 7ff5f1caacc..55b502f2a30 100644--- a/Libraries/LibWeb/HTML/RemoteWindow.h+++ b/Libraries/LibWeb/HTML/RemoteWindow.h@@ -50,7 +50,7 @@ public:Vector<GC::Root<Navigable>> document_tree_child_navigables();GC::OrderedRootHashMap<Utf16FlyString, GC::Ref<Navigable>> document_tree_child_navigable_target_name_property_set();- CrossOriginPropertyDescriptorMap& cross_origin_property_descriptor_map() { return m_cross_origin_property_descriptor_map; }+ CrossOriginPropertyDescriptorMap& cross_origin_property_descriptor_map();private:explicit RemoteWindow(RemoteNavigable&);@@ -62,7 +62,7 @@ private:// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-locationGC::Ptr<Location> m_location;- CrossOriginPropertyDescriptorMap m_cross_origin_property_descriptor_map;+ GC::Ptr<CrossOriginPropertyDescriptorMap> m_cross_origin_property_descriptor_map;};}diff --git a/Tests/LibWeb/TestWrapperWorld.cpp b/Tests/LibWeb/TestWrapperWorld.cppindex 937d9ac9999..e76f64f745b 100644--- a/Tests/LibWeb/TestWrapperWorld.cpp+++ b/Tests/LibWeb/TestWrapperWorld.cpp@@ -30,6 +30,7 @@#include <LibWeb/HTML/BarProp.h>#include <LibWeb/HTML/CrossOrigin/AbstractOperations.h>#include <LibWeb/HTML/LocalTraversableNavigable.h>+#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>@@ -824,7 +825,7 @@ TEST_CASE(window_cross_origin_descriptor_cache_lives_on_wrapper)auto window = Web::HTML::Window::create();auto wrapper = Web::Bindings::wrap(wrapper_world, extension_realm.realm(), window);auto key = Web::HTML::CrossOriginKey {- .current_settings_object = 1,+ .current_settings_object = Web::HTML::principal_realm_settings_object(extension_realm.realm()),.relevant_settings_object = 2,.property_key = JS::PropertyKey { "closed"_utf16_fly_string },};@@ -832,10 +833,10 @@ TEST_CASE(window_cross_origin_descriptor_cache_lives_on_wrapper)EXPECT(!wrapper->host_data());JS::PropertyDescriptor descriptor;descriptor.value = JS::Value(false);- Web::HTML::cross_origin_property_descriptor_map(*wrapper).set(key, Web::HTML::CrossOriginCachedPropertyDescriptor { descriptor });+ Web::HTML::cross_origin_property_descriptor_map(*wrapper).set(key, descriptor);EXPECT(wrapper->host_data());- EXPECT(Web::HTML::cross_origin_property_descriptor_map(*wrapper).contains(key));+ EXPECT(Web::HTML::cross_origin_property_descriptor_map(*wrapper).get(key).has_value());EXPECT(wrapper_world.wrapper_for(*window, extension_realm.realm()) == wrapper);wrapper_world.detach();EXPECT(!wrapper_world.wrapper_for(*window, extension_realm.realm()));@@ -853,14 +854,14 @@ TEST_CASE(cross_origin_descriptor_cache_does_not_root_realm_after_wrapper_dies)auto wrapper = Web::Bindings::wrap(wrapper_world, realm.realm(), window);auto accessor = JS::NativeFunction::create(realm.realm(), [](JS::VM&) -> JS::ThrowCompletionOr<JS::Value> { return JS::js_undefined(); }, 0);auto key = Web::HTML::CrossOriginKey {- .current_settings_object = 1,+ .current_settings_object = Web::HTML::principal_realm_settings_object(realm.realm()),.relevant_settings_object = 2,.property_key = JS::PropertyKey { "closed"_utf16_fly_string },};JS::PropertyDescriptor descriptor;descriptor.get = accessor;- Web::HTML::cross_origin_property_descriptor_map(*wrapper).set(key, Web::HTML::CrossOriginCachedPropertyDescriptor { descriptor });+ Web::HTML::cross_origin_property_descriptor_map(*wrapper).set(key, descriptor);weak_realm = GC::Weak<JS::Realm> { realm.realm() };}diff --git a/Tests/LibWeb/Text/expected/HTML/document-reading-a-cross-origin-property-is-collectable.txt b/Tests/LibWeb/Text/expected/HTML/document-reading-a-cross-origin-property-is-collectable.txtnew file mode 100644index 00000000000..5a9123971a2--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/document-reading-a-cross-origin-property-is-collectable.txt@@ -0,0 +1,2 @@+messages: first, second+first document collected: truediff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.txtindex 9465d2acdf8..6b38972909e 100644--- a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.txt+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.txt@@ -1,5 +1,4 @@WebContent#0iframe#0: remote WebContent#1iframe#0: remote WebContent#0-first grandchild reached the isolated iframe: truefirst grandchild's document collected: truediff --git a/Tests/LibWeb/Text/input/HTML/document-reading-a-cross-origin-property-is-collectable.html b/Tests/LibWeb/Text/input/HTML/document-reading-a-cross-origin-property-is-collectable.htmlnew file mode 100644index 00000000000..19dd5ad7b52--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/document-reading-a-cross-origin-property-is-collectable.html@@ -0,0 +1,50 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A cross-origin iframe that reads a property of this page's Window caches a descriptor whose function is of the+ // iframe's realm. Once the iframe navigates to another document, that descriptor must not keep the iframe's first+ // document alive.+ // This page is served over HTTP so that the iframe can be cross-origin with it.+ promiseTest(async () => {+ const httpServer = httpTestServer();+ const hostname = uniqueLocalhostHostname("document-reading-a-cross-origin-property");++ const secondUrl = new URL(+ await httpServer.createEcho("GET", "/document-reading-a-cross-origin-property-second", {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>top.postMessage("second", "*");<\/script>`,+ })+ );+ secondUrl.hostname = hostname;++ const firstUrl = new URL(+ await httpServer.createEcho("GET", "/document-reading-a-cross-origin-property-first", {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ top.postMessage("first", "*");+ location.replace(${JSON.stringify(secondUrl.href)});+ <\/script>`,+ })+ );+ firstUrl.hostname = hostname;++ const messages = [];+ const secondLoaded = new Promise(resolve => {+ addEventListener("message", event => {+ messages.push(event.data);+ if (event.data === "second") resolve();+ });+ });+ const iframe = document.createElement("iframe");+ iframe.src = firstUrl;+ document.body.appendChild(iframe);+ await secondLoaded;+ println(`messages: ${messages.join(", ")}`);++ const firstDocumentIsHere = () => internals.documentsInThisProcess().includes(firstUrl.href);+ await collectGarbageUntil(() => !firstDocumentIsHere());+ println(`first document collected: ${!firstDocumentIsHere()}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/document-reading-a-cross-origin-property-is-collectable.html.headers b/Tests/LibWeb/Text/input/HTML/document-reading-a-cross-origin-property-is-collectable.html.headersnew file mode 100644index 00000000000..156209f9c81--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/document-reading-a-cross-origin-property-is-collectable.html.headers@@ -0,0 +1 @@+Content-Type: text/htmldiff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.htmlindex 7a874e65592..6b2c1af568b 100644--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html@@ -3,9 +3,8 @@<script>// A grandchild same origin with this page, under an isolated iframe, is hosted in this page's process. The first// script here to reach the isolated iframe's WindowProxy is the grandchild's, through parent. Once the grandchild- // navigates to another document, that WindowProxy must not keep the grandchild's first document alive.- // The grandchild reads no property of the WindowProxy, as the descriptors cached for cross-origin property access- // keep the realm of the script that reads them alive.+ // navigates to another document, neither that WindowProxy nor the cross-origin property descriptors the grandchild+ // read through it may keep the grandchild's first document alive.// This page is served over HTTP so that the grandchild can be same origin with it.promiseTest(async () => {const httpServer = httpTestServer();@@ -23,7 +22,7 @@body: `<!DOCTYPE html><script>document.preserveWrapper = true;top.weakFirstGrandchildDocument = new top.WeakRef(document);- top.firstGrandchildReachedTheIsolatedIframe = parent === top.frames[0];+ parent.postMessage("first grandchild", "*");location.replace(${JSON.stringify(secondGrandchildUrl)});<\/script>`,});@@ -48,7 +47,6 @@await secondGrandchildLoaded;println(internals.dumpSiteIsolationProcessTree().trimEnd());- println(`first grandchild reached the isolated iframe: ${firstGrandchildReachedTheIsolatedIframe}`);await collectGarbageUntilCleared([weakFirstGrandchildDocument]);println(`first grandchild's document collected: ${weakFirstGrandchildDocument.deref() === undefined}`);});diff --git a/Tests/LibWeb/Text/input/include.js b/Tests/LibWeb/Text/input/include.jsindex f35e40cea61..1c74732caf2 100644--- a/Tests/LibWeb/Text/input/include.js+++ b/Tests/LibWeb/Text/input/include.js@@ -82,14 +82,18 @@ async function readClipboardFromPaste(target, read = clipboard => clipboard.read// Each round runs in a task of its own, so that pending tasks can drop their references and the objects that WeakRefs// kept alive for an earlier job are released.-async function collectGarbageUntilCleared(weakRefs, rounds = 100) {+async function collectGarbageUntil(condition, rounds = 100) {for (let round = 0; round < rounds; ++round) {await timeout(0);await internals.gcAsync();- if (weakRefs.every(weakRef => weakRef.deref() === undefined)) return;+ if (condition()) return;}}+async function collectGarbageUntilCleared(weakRefs, rounds = 100) {+ await collectGarbageUntil(() => weakRefs.every(weakRef => weakRef.deref() === undefined), rounds);+}+async function setSystemVisibilityState(state) {// Tests assume that the document reflects the UI process's system visibility state and that// no previous visibility state change is still pending.