Skip to content

Truly independent web browser

LibWeb: Stop remote WindowProxies from keeping documents alive

Shannon Boothb5ae89868d1e
diff --git a/Libraries/LibWeb/Bindings/HostDefined.h b/Libraries/LibWeb/Bindings/HostDefined.h
index ef81f2091d5..aba41330b82 100644
--- a/Libraries/LibWeb/Bindings/HostDefined.h
+++ b/Libraries/LibWeb/Bindings/HostDefined.h
@@ -47,12 +47,16 @@ protected:
// LibWeb is the only producer of a realm's [[HostDefined]] field, and it always stores a HostDefined there.
[[nodiscard]] inline HostDefined& host_defined_of(JS::Realm& realm)
{
- return static_cast<HostDefined&>(*realm.host_defined());
+ auto host_defined = realm.host_defined();
+ VERIFY(host_defined);
+ return static_cast<HostDefined&>(*host_defined);
}
[[nodiscard]] inline HostDefined const& host_defined_of(JS::Realm const& realm)
{
- return static_cast<HostDefined const&>(*realm.host_defined());
+ auto host_defined = realm.host_defined();
+ VERIFY(host_defined);
+ return static_cast<HostDefined const&>(*host_defined);
}
}
diff --git a/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Libraries/LibWeb/HTML/BrowsingContext.cpp
index 26a63cb7cba..12ebcf540d2 100644
--- a/Libraries/LibWeb/HTML/BrowsingContext.cpp
+++ b/Libraries/LibWeb/HTML/BrowsingContext.cpp
@@ -329,10 +329,7 @@ void BrowsingContext::set_opener_browsing_context(GC::Ptr<BrowsingContext> opene
// NB: The browsing context active in a navigable another process hosts is there, and its WindowProxy stands for it.
void BrowsingContext::set_opener_browsing_context(Navigable& navigable)
{
- if (auto* remote_navigable = as_if<RemoteNavigable>(navigable))
- m_opener_browsing_context_window_proxy = remote_navigable->active_window_proxy_in_realm_of(*m_window_proxy->window());
- else
- m_opener_browsing_context_window_proxy = navigable.active_window_proxy();
+ m_opener_browsing_context_window_proxy = navigable.active_window_proxy();
}
void BrowsingContext::visit_edges(Cell::Visitor& visitor)
diff --git a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp
index 73d8dcef298..6704e69f380 100644
--- a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp
+++ b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp
@@ -226,9 +226,12 @@ static Optional<JS::PropertyDescriptor> cross_origin_get_own_property_helper_imp
auto const* object_ptr = &object;
// 1. Let crossOriginKey be a tuple consisting of the current settings object, O's relevant settings object, and P.
+ // NB: The relevant settings object of a Window hosted by another process lives there. It is the same for every
+ // 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(),
- .relevant_settings_object = (FlatPtr)&HTML::relevant_settings_object(*object_ptr),
+ .relevant_settings_object = relevant_settings_object,
.property_key = property_key,
};
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 73dd4a07cda..1c4aee8169d 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -3701,12 +3701,8 @@ void LocalNavigable::deliver_posted_message_from_another_process(MessageDescript
// posting to its opener's tab, or the other way round, posts from a tab another page of this process holds.
GC::Ptr<WindowProxy> source;
if (message.source_navigable_id.has_value()) {
- if (auto source_navigable = navigable_with_id_in_any_page(page(), *message.source_navigable_id)) {
- if (auto* remote_source_navigable = as_if<RemoteNavigable>(*source_navigable))
- source = remote_source_navigable->active_window_proxy_in_realm_of(*window);
- else
- source = source_navigable->active_window_proxy();
- }
+ if (auto source_navigable = navigable_with_id_in_any_page(page(), *message.source_navigable_id))
+ source = source_navigable->active_window_proxy();
}
// 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
diff --git a/Libraries/LibWeb/HTML/RemoteNavigable.cpp b/Libraries/LibWeb/HTML/RemoteNavigable.cpp
index b8ccb40af04..db032ee4eeb 100644
--- a/Libraries/LibWeb/HTML/RemoteNavigable.cpp
+++ b/Libraries/LibWeb/HTML/RemoteNavigable.cpp
@@ -96,38 +96,15 @@ void RemoteNavigable::replace_child(Navigable& child, GC::Ref<Navigable> replace
m_children[*index] = replacement;
}
+// The WindowProxy of a navigable hosted by another process answers every access on the cross-origin path, so it
+// belongs to no realm.
GC::Ptr<WindowProxy> RemoteNavigable::active_window_proxy()
-{
- // The WindowProxy of a navigable hosted by another process answers every access on the cross-origin path.
- return active_window_proxy_in_realm_of(current_window());
-}
-
-// The WindowProxy lives in the realm of window_for_window_proxy(), or else of the window the caller gives, which is the
-// one it hands the WindowProxy to.
-GC::Ref<WindowProxy> RemoteNavigable::active_window_proxy_in_realm_of(Window& window)
{
if (!m_window_proxy) {
- auto window_for_proxy = window_for_window_proxy();
- m_window_proxy = WindowProxy::create(relevant_realm(window_for_proxy ? *window_for_proxy : window));
+ m_window_proxy = WindowProxy::create(vm().empty_realm());
m_window_proxy->set_window(active_window());
}
- return *m_window_proxy;
-}
-
-// The WindowProxy's shape keeps the realm it lives in alive, and with it the document of that realm's window. So it lives
-// in the realm of the window that embeds the navigable here, or its nearest ancestor embedded here, which outlives the
-// navigable. A navigable that nothing here embeds has its opener's window here, if any.
-GC::Ptr<Window> RemoteNavigable::window_for_window_proxy()
-{
- for (GC::Ptr<Navigable> navigable = this; navigable; navigable = navigable->parent()) {
- if (auto container = navigable->container())
- return container->document().window();
- }
- if (auto* opener = as_if<LocalNavigable>(active_browsing_context_opener_navigable().ptr())) {
- if (auto document = opener->active_document())
- return document->window();
- }
- return nullptr;
+ return m_window_proxy;
}
GC::Ptr<WindowProxy> RemoteNavigable::active_browsing_context_opener_window_proxy() const
diff --git a/Libraries/LibWeb/HTML/RemoteNavigable.h b/Libraries/LibWeb/HTML/RemoteNavigable.h
index 972cff14ec7..19fa3207ece 100644
--- a/Libraries/LibWeb/HTML/RemoteNavigable.h
+++ b/Libraries/LibWeb/HTML/RemoteNavigable.h
@@ -55,8 +55,6 @@ public:
Vector<GC::Root<Navigable>> document_tree_child_navigables();
virtual GC::Ptr<WindowProxy> active_window_proxy() override;
- GC::Ref<WindowProxy> active_window_proxy_in_realm_of(Window&);
- GC::Ptr<Window> window_for_window_proxy();
GC::Ref<RemoteWindow> active_window();
virtual Utf16String const& target_name() const override { return m_replicated_state.target_name; }
virtual Optional<u64> browsing_context_group_id() const override { return m_replicated_state.browsing_context_group_id; }
diff --git a/Libraries/LibWeb/HTML/WindowProxy.cpp b/Libraries/LibWeb/HTML/WindowProxy.cpp
index 635aae733b2..7ef1c49e2ed 100644
--- a/Libraries/LibWeb/HTML/WindowProxy.cpp
+++ b/Libraries/LibWeb/HTML/WindowProxy.cpp
@@ -377,7 +377,7 @@ void WindowProxy::set_window(GC::Ref<Window> window)
m_remote_window = nullptr;
m_cross_origin_window_wrapper = nullptr;
- if (!realm().host_defined() || !Bindings::host_defined_wrapper_world(realm()).is_main_world()) {
+ if (!is_of_main_world()) {
m_object->set_prototype(nullptr);
return;
}
@@ -398,23 +398,29 @@ void WindowProxy::set_window(GC::Ref<RemoteWindow> window)
{
m_window = nullptr;
set_remote_window_over_provisional_window(window);
-
- if (!realm().host_defined() || !Bindings::host_defined_wrapper_world(realm()).is_main_world())
- return;
-
- // The proxy's shape keeps its realm alive. With no Window of this process to follow, it moves to the realm its
- // navigable picks, instead of pinning the realm of the Window it followed, whose document is gone.
- auto navigable = window->navigable();
- auto window_for_proxy = navigable ? navigable->window_for_window_proxy() : nullptr;
- if (window_for_proxy && &window_for_proxy->principal_realm() != &realm())
- m_object->set_realm_and_prototype(window_for_proxy->principal_realm(), nullptr);
}
void WindowProxy::set_remote_window_over_provisional_window(GC::Ref<RemoteWindow> window)
{
m_remote_window = window;
m_cross_origin_window_wrapper = nullptr;
- m_object->set_prototype(nullptr);
+
+ if (!is_of_main_world()) {
+ m_object->set_prototype(nullptr);
+ return;
+ }
+
+ // A Window of another process has no realm here, so the proxy belongs to none instead of pinning the realm of the
+ // Window it followed.
+ m_object->set_realm_and_prototype(vm().empty_realm(), nullptr);
+}
+
+// Only a proxy of the main world stands for a Window of another process, in the empty realm.
+bool WindowProxy::is_of_main_world() const
+{
+ if (&realm() == &vm().empty_realm())
+ return true;
+ return realm().host_defined() && Bindings::host_defined_wrapper_world(realm()).is_main_world();
}
bool WindowProxy::is_platform_object_same_origin() const
diff --git a/Libraries/LibWeb/HTML/WindowProxy.h b/Libraries/LibWeb/HTML/WindowProxy.h
index c4cd5966eed..b8dcc9ab536 100644
--- a/Libraries/LibWeb/HTML/WindowProxy.h
+++ b/Libraries/LibWeb/HTML/WindowProxy.h
@@ -81,6 +81,7 @@ private:
JS::ThrowCompletionOr<GC::RootVector<JS::Value>> internal_own_property_keys() const;
JS::HostObject& cross_origin_window_wrapper() const;
+ bool is_of_main_world() const;
bool is_platform_object_same_origin() const;
Vector<GC::Root<Navigable>> document_tree_child_navigables() const;
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 6d136c11f9e..ea937d611ec 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -2386,6 +2386,11 @@ Vector<String> Internals::documents_in_this_process()
bool Internals::is_in_realm_of_destroyed_document(JS::Object& object)
{
+ // An object in the empty realm, such as the WindowProxy of a navigable that another process hosts, is in the realm
+ // of no document.
+ if (&HTML::relevant_realm(object) == &object.vm().empty_realm())
+ return false;
+
auto* window = HTML::window_from_global_object(HTML::relevant_global_object(object));
if (!window)
return false;
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-of-iframe-gone-to-another-process-is-collectable.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-of-iframe-gone-to-another-process-is-collectable.txt
new file mode 100644
index 00000000000..a33e06f2495
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-of-iframe-gone-to-another-process-is-collectable.txt
@@ -0,0 +1,2 @@
+document here collected: true
+same WindowProxy: true
diff --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.txt
new file mode 100644
index 00000000000..9465d2acdf8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.txt
@@ -0,0 +1,5 @@
+WebContent#0
+ iframe#0: remote WebContent#1
+ iframe#0: remote WebContent#0
+first grandchild reached the isolated iframe: true
+first grandchild's document collected: true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/operations-on-a-remote-window-proxy.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/operations-on-a-remote-window-proxy.txt
new file mode 100644
index 00000000000..4e33b398fcc
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/operations-on-a-remote-window-proxy.txt
@@ -0,0 +1,31 @@
+typeof: object
+Object.getPrototypeOf: null
+instanceof Window: false
+Object.isExtensible: true
+Object.preventExtensions: threw TypeError
+Object.setPrototypeOf: threw TypeError
+Reflect.ownKeys length: 17
+length: 0
+closed: false
+window is the proxy: true
+document: threw SecurityError
+'document' in: threw SecurityError
+hasOwnProperty postMessage: true
+postMessage is from this realm: true
+define a property: threw SecurityError
+set a property: threw SecurityError
+delete a property: threw SecurityError
+toString tag: [object Object]
+String: threw SecurityError
+JSON.stringify: threw SecurityError
+structuredClone: threw DataCloneError
+alert with the proxy as this: threw SecurityError
+document getter with the proxy as this: threw SecurityError
+addEventListener with the proxy as this: threw SecurityError
+MessageEvent source: true
+WeakRef: true
+Map key: 1
+postMessage to self with the proxy: threw DataCloneError
+console.log: undefined
+Promise.resolve: true
+posted a message
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-of-iframe-gone-to-another-process-is-collectable.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-of-iframe-gone-to-another-process-is-collectable.html
new file mode 100644
index 00000000000..b2695af723a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-of-iframe-gone-to-another-process-is-collectable.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ // Scripts keep the WindowProxy of an iframe whose next document another process hosts. That WindowProxy must not
+ // keep the document the iframe displayed here alive.
+ promiseTest(async () => {
+ const httpServer = httpTestServer();
+
+ const remoteUrl = new URL(
+ await httpServer.createEcho("GET", "/document-of-iframe-gone-to-another-process", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: "<!DOCTYPE html>remote",
+ })
+ );
+ remoteUrl.hostname = uniqueLocalhostHostname("document-of-iframe-gone-to-another-process");
+
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const windowProxy = iframe.contentWindow;
+
+ // An expando keeps the document's wrapper alive for as long as the document lives. No local of this function
+ // holds the document.
+ const weakDocument = (() => {
+ const documentHere = iframe.contentDocument;
+ documentHere.preserveWrapper = true;
+ return new WeakRef(documentHere);
+ })();
+
+ iframe.src = remoteUrl;
+ if (!(await waitForCondition(() => remoteFrameCount() === 1))) {
+ println("iframe did not become remote");
+ return;
+ }
+
+ await collectGarbageUntilCleared([weakDocument]);
+ println(`document here collected: ${weakDocument.deref() === undefined}`);
+ println(`same WindowProxy: ${iframe.contentWindow === windowProxy}`);
+ });
+</script>
diff --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.html
new file mode 100644
index 00000000000..7a874e65592
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<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.
+ // This page is served over HTTP so that the grandchild can be same origin with it.
+ promiseTest(async () => {
+ const httpServer = httpTestServer();
+
+ const secondGrandchildUrl = await httpServer.createEcho("GET", "/document-reaching-a-remote-parent-second", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>top.postMessage("second grandchild", "*");<\/script>`,
+ });
+
+ // The WeakRef comes from this page's realm, so that it does not keep the grandchild's realm alive itself.
+ const firstGrandchildUrl = await httpServer.createEcho("GET", "/document-reaching-a-remote-parent-first", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>
+ document.preserveWrapper = true;
+ top.weakFirstGrandchildDocument = new top.WeakRef(document);
+ top.firstGrandchildReachedTheIsolatedIframe = parent === top.frames[0];
+ location.replace(${JSON.stringify(secondGrandchildUrl)});
+ <\/script>`,
+ });
+
+ const childUrl = new URL(
+ await httpServer.createEcho("GET", "/document-reaching-a-remote-parent-child", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><iframe src="${firstGrandchildUrl}"></iframe>`,
+ })
+ );
+ childUrl.hostname = uniqueLocalhostHostname("document-reaching-a-remote-parent");
+
+ const secondGrandchildLoaded = new Promise(resolve => {
+ addEventListener("message", event => {
+ if (event.data === "second grandchild") resolve();
+ });
+ });
+ const iframe = document.createElement("iframe");
+ iframe.src = childUrl;
+ document.body.appendChild(iframe);
+ 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}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html.headers b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html.headers
new file mode 100644
index 00000000000..156209f9c81
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/document-reaching-a-remote-parent-is-collectable.html.headers
@@ -0,0 +1 @@
+Content-Type: text/html
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/operations-on-a-remote-window-proxy.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/operations-on-a-remote-window-proxy.html
new file mode 100644
index 00000000000..d7d0d2eaa33
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/operations-on-a-remote-window-proxy.html
@@ -0,0 +1,70 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ // The WindowProxy of a document another process hosts belongs to no realm here. Whatever script does with it takes
+ // the cross-origin path, and every error comes from the realm of the script.
+ promiseTest(async () => {
+ const httpServer = httpTestServer();
+
+ const remoteUrl = new URL(
+ await httpServer.createEcho("GET", "/operations-on-a-remote-window-proxy", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: "<!DOCTYPE html>remote",
+ })
+ );
+ remoteUrl.hostname = uniqueLocalhostHostname("operations-on-a-remote-window-proxy");
+
+ const iframe = document.createElement("iframe");
+ iframe.src = remoteUrl;
+ document.body.appendChild(iframe);
+ if (!(await waitForCondition(() => remoteFrameCount() === 1))) {
+ println("iframe did not become remote");
+ return;
+ }
+ const proxy = iframe.contentWindow;
+
+ const run = (name, operation) => {
+ try {
+ const result = operation();
+ println(`${name}: ${result}`);
+ } catch (e) {
+ const fromThisRealm = e instanceof DOMException || e instanceof Error;
+ println(`${name}: threw ${e.name}${fromThisRealm ? "" : " from another realm"}`);
+ }
+ };
+
+ run("typeof", () => typeof proxy);
+ run("Object.getPrototypeOf", () => Object.getPrototypeOf(proxy));
+ run("instanceof Window", () => proxy instanceof Window);
+ run("Object.isExtensible", () => Object.isExtensible(proxy));
+ run("Object.preventExtensions", () => Object.preventExtensions(proxy));
+ run("Object.setPrototypeOf", () => Object.setPrototypeOf(proxy, {}));
+ run("Reflect.ownKeys length", () => Reflect.ownKeys(proxy).length);
+ run("length", () => proxy.length);
+ run("closed", () => proxy.closed);
+ run("window is the proxy", () => proxy.window === proxy);
+ run("document", () => proxy.document);
+ run("'document' in", () => "document" in proxy);
+ run("hasOwnProperty postMessage", () => Object.prototype.hasOwnProperty.call(proxy, "postMessage"));
+ run("postMessage is from this realm", () => proxy.postMessage instanceof Function);
+ run("define a property", () => Object.defineProperty(proxy, "x", { value: 1 }));
+ run("set a property", () => (proxy.x = 1));
+ run("delete a property", () => delete proxy.x);
+ run("toString tag", () => Object.prototype.toString.call(proxy));
+ run("String", () => String(proxy));
+ run("JSON.stringify", () => JSON.stringify(proxy));
+ run("structuredClone", () => structuredClone(proxy));
+ run("alert with the proxy as this", () => window.alert.call(proxy));
+ run("document getter with the proxy as this", () => Object.getOwnPropertyDescriptor(window, "document").get.call(proxy));
+ run("addEventListener with the proxy as this", () => EventTarget.prototype.addEventListener.call(proxy, "x", () => {}));
+ run("MessageEvent source", () => new MessageEvent("message", { source: proxy }).source === proxy);
+ run("WeakRef", () => new WeakRef(proxy).deref() === proxy);
+ run("Map key", () => new Map([[proxy, 1]]).get(proxy));
+ run("postMessage to self with the proxy", () => window.postMessage(proxy, "*"));
+ run("console.log", () => console.log(proxy));
+ println(`Promise.resolve: ${(await Promise.resolve(proxy)) === proxy}`);
+ proxy.postMessage("hello", "*");
+ println("posted a message");
+ });
+</script>