Truly independent web browser
LibWebView+UI/Qt: Share ImageDecoders between the processes of a site
Andreas Kling4edc89846e07
diff --git a/Documentation/ProcessArchitecture.md b/Documentation/ProcessArchitecture.mdindex fcf7de6f7f8..18ffd19a45a 100644--- a/Documentation/ProcessArchitecture.md+++ b/Documentation/ProcessArchitecture.md@@ -26,7 +26,7 @@ For DNS lookups, **RequestServer** asks for help from the system's global **Look### Process: ImageDecoder-This process can decode images (PNG, JPEG, BMP, ICO, PBM, etc.) into bitmaps. Each image is decoded in a fresh **ImageDecoder** process. These are strongly sandboxed and can't do much except receive encoded bitmap data and return a bitmap to **WebContent** if decoding is successful.+This process can decode images (PNG, JPEG, BMP, ICO, PBM, etc.) into bitmaps. **Browser** launches one when a **WebContent** or **WebWorker** process first has an image to decode, and ends it once the last process it serves is gone. With site isolation, the processes of a site share one **ImageDecoder**, keyed by the site of the documents they host, with private browsing kept apart. Any other process gets one of its own. These are strongly sandboxed and can't do much except receive encoded bitmap data and return a bitmap to their clients if decoding is successful.### How processes are spawneddiff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cppindex 2169817dfa8..0346c2f4cf9 100644--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp@@ -38,6 +38,12 @@ ImageDecoderClient::Client* RemoteImageCodecPlugin::ensure_client()return m_client;}+void RemoteImageCodecPlugin::disconnect_client()+{+ if (auto client = m_client)+ client->shutdown();+}+RemoteImageCodecPlugin::~RemoteImageCodecPlugin() = default;NonnullRefPtr<Core::Promise<DecodedImage>> RemoteImageCodecPlugin::decode_image(ReadonlyBytes bytes, Function<ErrorOr<void>(DecodedImage&)> on_resolved, Function<void(Error&)> on_rejected)diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.hindex 39e0fc317d9..279c377057b 100644--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h@@ -32,6 +32,9 @@ public:virtual void connect_frame_client(IPC::TransportHandle) override;virtual u64 client_generation() const override { return m_client_generation; }+ // Gives up the client, as if its decoder had crashed. The next image to decode connects a new one.+ void disconnect_client();+private:ImageDecoderClient::Client* ensure_client();diff --git a/Libraries/LibWebView/CanonicalDocument.cpp b/Libraries/LibWebView/CanonicalDocument.cppindex ccfc6abacfe..8c933344256 100644--- a/Libraries/LibWebView/CanonicalDocument.cpp+++ b/Libraries/LibWebView/CanonicalDocument.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibURL/Site.h>#include <LibWebView/BlobURLStore.h>#include <LibWebView/CanonicalBrowsingContext.h>#include <LibWebView/CanonicalBrowsingContextGroup.h>@@ -74,6 +75,11 @@ void CanonicalDocument::set_host(RefPtr<WebContentPage> host)m_relevant_global_object->agent().set_hosting_process_if_unset(m_host->client());// The process makes the document's requests through the RequestServer of the document's top-level site.m_host->client().request_server_site_bindings().bind_sites_of(*this);+ // NB: The PDF viewer has an origin of its own, but it only ever replaces a document in the process of the PDF's+ // site, so it brings no second site along.+ auto is_pdf_viewer = !m_origin.is_opaque() && m_origin.scheme() == "resource"sv;+ if (auto site = URL::Site::serialize_for_partitioning(m_origin); site.has_value() && !is_pdf_viewer)+ m_host->client().did_host_document_of_site(site.release_value());}}diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex 708b38ff8a6..8dc11f72034 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -303,14 +303,16 @@ static ErrorOr<NonnullRefPtr<ClientType>> launch_server_process(return client.release_nonnull();}-// Launches a server that works for the given process alone, so that the server is listed with it.+// Launches a server that works for the given process, so that the server is listed with it, or with the site if it has one.template<typename ClientType>-static ErrorOr<NonnullRefPtr<ClientType>> launch_server_process_for(u64 owner_child_id, StringView server_name, Vector<ByteString> arguments)+static ErrorOr<NonnullRefPtr<ClientType>> launch_server_process_for(u64 owner_child_id, StringView server_name, Vector<ByteString> arguments, Optional<Utf16String> const& site = {}){RefPtr<ClientType> client;auto identity = TRY(launch_helper_process(server_name, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {auto [process, new_client] = TRY(WebView::Process::spawn<ClientType>(WebView::process_type_from_name(server_name), options, capture_output));process.set_owner_child_id(owner_child_id);+ if (site.has_value())+ process.set_site_url(URL::Parser::basic_parse(*site));client = move(new_client);return move(process);}));@@ -396,7 +398,7 @@ ErrorOr<NonnullRefPtr<WebView::WebContentClient>> launch_web_content_process(IsPreturn client;}-ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(u64 owner_child_id)+ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(u64 owner_child_id, Optional<Utf16String> const& site){auto const& browser_options = WebView::Application::browser_options();@@ -408,7 +410,7 @@ ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(uarguments.append(server.value());}- return launch_server_process_for<ImageDecoderControlClient>(owner_child_id, "ImageDecoder"sv, move(arguments));+ return launch_server_process_for<ImageDecoderControlClient>(owner_child_id, "ImageDecoder"sv, move(arguments), site);}ErrorOr<IPC::TransportHandle> launch_webrtc_client_process(WebContentClient& client)diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.hindex 60ec8b05159..3d25e8f930e 100644--- a/Libraries/LibWebView/HelperProcess.h+++ b/Libraries/LibWebView/HelperProcess.h@@ -35,8 +35,8 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebWorkerClient>> launch_web_worker_pWEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode);WEBVIEW_API void apply_dns_settings(Requests::RequestControlClient&);-// Launches an ImageDecoder, which the given process is listed with.-WEBVIEW_API ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(u64 owner_child_id);+// Launches an ImageDecoder, which is listed with the given site, or with the given process if it serves no site.+WEBVIEW_API ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(u64 owner_child_id, Optional<Utf16String> const& site);// Launches a WebRTCClient that serves the given renderer alone, which talks to it over the returned handle, and ends any// helper the renderer had before. The helper exits once that renderer's end of the transport is gone.diff --git a/Libraries/LibWebView/ImageDecoderManager.cpp b/Libraries/LibWebView/ImageDecoderManager.cppindex d455b43dffd..7a0a1ce3590 100644--- a/Libraries/LibWebView/ImageDecoderManager.cpp+++ b/Libraries/LibWebView/ImageDecoderManager.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibWebCommon/WebView/SiteIsolation.h>#include <LibWebView/Application.h>#include <LibWebView/HelperProcess.h>#include <LibWebView/ImageDecoderControlClient.h>@@ -19,17 +20,23 @@ ImageDecoderManager& ImageDecoderManager::the()ImageDecoderManager::ImageDecoderManager() = default;ImageDecoderManager::~ImageDecoderManager() = default;-ErrorOr<IPC::TransportHandle> ImageDecoderManager::connect_new_client(u64 client_child_id, IsPrivate)+ErrorOr<IPC::TransportHandle> ImageDecoderManager::connect_new_client(u64 client_child_id, RefPtr<BrowsingSession> const& session, Optional<Utf16String> site){+ if (site_isolation_mode() != SiteIsolationMode::IFrame || !session)+ site.clear();+// NB: A decoder that died is of no use to anyone, whether or not its clients have noticed yet.m_instances.remove_all_matching([](auto const& instance) { return !instance.control_client->is_open(); });auto instance = m_instances.first_matching([&](auto const& instance) {- return instance.client_child_ids.contains(client_child_id);+ if (site.has_value())+ return instance.site == site && instance.session.ptr() == session.ptr();+ return !instance.site.has_value() && instance.client_child_ids.contains(client_child_id);});auto channel = TRY(IPC::TransportHandle::create_pair());if (!instance.has_value()) {- m_instances.append({ .control_client = TRY(launch_image_decoder_process(client_child_id)), .client_child_ids = {} });+ auto control_client = TRY(launch_image_decoder_process(client_child_id, site));+ m_instances.append({ .control_client = move(control_client), .session = session, .site = move(site), .client_child_ids = {} });instance = m_instances.last();}@@ -38,14 +45,14 @@ ErrorOr<IPC::TransportHandle> ImageDecoderManager::connect_new_client(u64 clientreturn move(channel.second);}-Optional<IPC::TransportHandle> ImageDecoderManager::connect_requesting_process(u64 client_child_id, IsPrivate is_private)+Optional<IPC::TransportHandle> ImageDecoderManager::connect_requesting_process(u64 client_child_id, RefPtr<BrowsingSession> const& session, Optional<Utf16String> site){// NB: A request can still be queued when the process's exit is handled. Connecting it then would leave a client that// never exits, which would keep its decoder alive for as long as the Browser runs.if (!Application::process_manager().find_child(client_child_id).has_value())return {};- auto handle = connect_new_client(client_child_id, is_private);+ auto handle = connect_new_client(client_child_id, session, move(site));if (handle.is_error()) {warnln("Unable to connect an ImageDecoder client: {}", handle.error());return {};@@ -53,6 +60,18 @@ Optional<IPC::TransportHandle> ImageDecoderManager::connect_requesting_process(ureturn handle.release_value();}+bool ImageDecoderManager::remove_client_from_decoder_of_site(u64 client_child_id)+{+ bool was_removed = false;+ m_instances.remove_all_matching([&](auto& instance) {+ if (!instance.site.has_value() || !instance.client_child_ids.remove(client_child_id))+ return false;+ was_removed = true;+ return instance.client_child_ids.is_empty();+ });+ return was_removed;+}+void ImageDecoderManager::process_did_exit(u64 child_id){// NB: Letting go of a decoder that exited also closes the channels of any clients that were sent to it, which it can nodiff --git a/Libraries/LibWebView/ImageDecoderManager.h b/Libraries/LibWebView/ImageDecoderManager.hindex 6d60bf116dd..81e79c45c24 100644--- a/Libraries/LibWebView/ImageDecoderManager.h+++ b/Libraries/LibWebView/ImageDecoderManager.h@@ -9,7 +9,9 @@#include <AK/HashTable.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>+#include <AK/Utf16String.h>#include <AK/Vector.h>+#include <AK/WeakPtr.h>#include <LibIPC/TransportHandle.h>#include <LibWebView/BrowsingSession.h>#include <LibWebView/Export.h>@@ -18,6 +20,14 @@namespace WebView {// Launches ImageDecoders as processes first ask for them, and ends each once the last process it serves is gone.+//+// A decoder sees the images of every process it serves, so a malicious image that takes one over gets at those images. The+// processes of a site may share a decoder, because under site isolation they hold nothing of any other site's that they+// could not fetch for themselves. The site is that of the documents a process hosts, not their top-level site: a frame+// embedded in another site never shares a decoder with its embedder, unless it has an opaque origin, which keeps it in the+// process of the document that made it. Each browsing session has decoders of its own.+// Without site isolation a process may host anything, as may a process that has no site or has hosted several, so each of+// those gets a decoder of its own, and a process that comes to host a second site leaves the decoder of the first.class WEBVIEW_API ImageDecoderManager {public:AK_ALLOC_WITH_KMALLOC;@@ -27,18 +37,24 @@ public:ImageDecoderManager();~ImageDecoderManager();- // Connects a renderer or worker to its ImageDecoder, launching one if need be. A process that lost its decoder asks- // here again, and gets a new one.- ErrorOr<IPC::TransportHandle> connect_new_client(u64 client_child_id, IsPrivate);+ // Connects a renderer or worker to the ImageDecoder of its site, or to one of its own if it has no site, launching+ // one if need be. A process that lost its decoder asks here again, and gets a new one. A worker can outlive its+ // session, in which case it has none and shares with nobody.+ ErrorOr<IPC::TransportHandle> connect_new_client(u64 client_child_id, RefPtr<BrowsingSession> const&, Optional<Utf16String> site);// Answers a renderer or worker that asked for a decoder, which may have exited by the time its request is handled.- Optional<IPC::TransportHandle> connect_requesting_process(u64 client_child_id, IsPrivate);+ Optional<IPC::TransportHandle> connect_requesting_process(u64 client_child_id, RefPtr<BrowsingSession> const&, Optional<Utf16String> site);++ // Returns whether the process was served by the decoder of a site, and so has to disconnect from it.+ bool remove_client_from_decoder_of_site(u64 client_child_id);void process_did_exit(u64 child_id);private:struct Instance {NonnullRefPtr<ImageDecoderControlClient> control_client;+ WeakPtr<BrowsingSession> session;+ Optional<Utf16String> site;HashTable<u64> client_child_ids;};diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex cc045712846..f6c89740a8a 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -1155,9 +1155,24 @@ Messages::WebContentClient::RequestWebrtcClientConnectionResponse WebContentCliereturn handle.release_value();}+void WebContentClient::did_host_document_of_site(Utf16String site)+{+ if (m_has_hosted_documents_of_several_sites)+ return;+ if (m_site_of_hosted_documents.has_value() && *m_site_of_hosted_documents != site) {+ m_has_hosted_documents_of_several_sites = true;+ m_site_of_hosted_documents.clear();+ // Only the processes of one site may share a decoder, so this one asks for its own when it next needs one.+ if (ImageDecoderManager::the().remove_client_from_decoder_of_site(child_id()))+ async_disconnect_from_image_decoder();+ return;+ }+ m_site_of_hosted_documents = move(site);+}+Messages::WebContentClient::RequestImageDecoderConnectionResponse WebContentClient::request_image_decoder_connection(){- return ImageDecoderManager::the().connect_requesting_process(child_id(), m_is_private);+ return ImageDecoderManager::the().connect_requesting_process(child_id(), m_session, m_site_of_hosted_documents);}Optional<u64> WebContentClient::exclusive_performance_owner() constdiff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 38c5dc684ed..2b8d1afaf5a 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -122,6 +122,9 @@ public:static bool renderers_may_access_cookies_like_http();static bool renderers_may_synthesize_input();bool may_read_local_files() const;+ // Documents with no site, such as those of an opaque origin, come with whatever made them, so they do not count.+ void did_host_document_of_site(Utf16String site);+// A process that has hosted local file content may read local files. Site isolation gives such content processes// of its own, which host nothing else.bool has_hosted_local_file_content() const { return m_has_hosted_local_file_content; }@@ -246,6 +249,9 @@ private:RequestServerSiteBindings m_request_server_site_bindings;bool m_requested_close { false };bool m_rejected_ipc { false };+ // The site of the documents this process hosts, if it has only hosted those of one.+ Optional<Utf16String> m_site_of_hosted_documents;+ bool m_has_hosted_documents_of_several_sites { false };bool m_has_hosted_local_file_content { false };Optional<String> m_hosted_web_ui;Vector<u64> m_crashed_view_ids;diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cppindex 617e3a83d2b..c4d593ddaaa 100644--- a/Libraries/LibWebView/WebWorkerClient.cpp+++ b/Libraries/LibWebView/WebWorkerClient.cpp@@ -195,7 +195,7 @@ Messages::WebWorkerClient::RequestMediaServerConnectionResponse WebWorkerClient:Messages::WebWorkerClient::RequestImageDecoderConnectionResponse WebWorkerClient::request_image_decoder_connection(){- return ImageDecoderManager::the().connect_requesting_process(child_id(), m_is_private);+ return ImageDecoderManager::the().connect_requesting_process(child_id(), session(), m_site);}void WebWorkerClient::did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message)diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.hindex fa94d876fa9..a2925608712 100644--- a/Libraries/LibWebView/WebWorkerClient.h+++ b/Libraries/LibWebView/WebWorkerClient.h@@ -39,6 +39,9 @@ public:RefPtr<BrowsingSession> session() const { return m_session.strong_ref(); }IsPrivate is_private() const { return m_is_private; }+ // The site of the worker's origin, if it has one.+ void set_site(Optional<Utf16String> site) { m_site = move(site); }+// The sites this process asked for the permissions of: at most its worker's top-level site.Vector<URL::Origin> const& permission_origins() const { return m_permission_origins; }RequestServerSiteBindings& request_server_site_bindings() { return m_request_server_site_bindings; }@@ -76,6 +79,7 @@ private:virtual void die() override;IsPrivate m_is_private { IsPrivate::No };+ Optional<Utf16String> m_site;WeakPtr<BrowsingSession> m_session;RequestServerSiteBindings m_request_server_site_bindings;diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex 02ba8725373..58791b608e8 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -9,6 +9,7 @@#include <LibCore/Timer.h>#include <LibIPC/File.h>#include <LibURL/Parser.h>+#include <LibURL/Site.h>#include <LibWebView/Application.h>#include <LibWebView/CanonicalEnvironmentSettingsObject.h>#include <LibWebView/CanonicalNavigable.h>@@ -249,6 +250,7 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, O// settings it is created for, too.auto inside_settings = make<CanonicalWorkerEnvironmentSettingsObject>(move(origin), outside_settings->top_level_origin(), has_cross_site_ancestor, Web::HTML::EnvironmentId::generate());auto environment_id = inside_settings->id();+ client->set_site(URL::Site::serialize_for_partitioning(inside_settings->origin()));// NB: The task manager lists the worker's process with the process that started it, and once that one is gone,// with the site of the worker's origin.diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex cc38f8b2e53..dc3e1b2a745 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -94,6 +94,7 @@#include <LibWeb/PictureInPicture/PictureInPictureController.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/Platform/FontPlugin.h>+#include <LibWeb/Platform/RemoteImageCodecPlugin.h>#include <LibWeb/Selection/Selection.h>#include <LibWeb/UIEvents/InputTypes.h>#include <LibWebCommon/HTML/SelectedFile.h>@@ -452,6 +453,11 @@ void ConnectionFromClient::connect_to_web_ui(Web::PageId page_id, IPC::Transport}}+void ConnectionFromClient::disconnect_from_image_decoder()+{+ static_cast<Web::Platform::RemoteImageCodecPlugin&>(Web::Platform::ImageCodecPlugin::the()).disconnect_client();+}+void ConnectionFromClient::connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle){auto transport = MUST(handle.create_transport());diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex 22b6fed83b8..1db9b7e021d 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -116,6 +116,7 @@ private:virtual void connect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) override;virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) override;virtual void connect_to_test_endpoint(IPC::TransportHandle handle) override;+ virtual void disconnect_from_image_decoder() override;virtual void connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) override;virtual void set_site_compatibility_data(JsonValue data) override;virtual void set_permission_snapshot(Web::Permissions::PermissionSnapshot snapshot) override;diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex e816309aecd..6bc49eead9a 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -93,6 +93,7 @@ endpoint WebContentServer routed by Web::PageId page_idconnect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) =|connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) =|connect_to_test_endpoint(IPC::TransportHandle handle) =|+ disconnect_from_image_decoder() =|connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) =|compositor_process_reconnected() =|set_site_compatibility_data(JsonValue data) =|diff --git a/Tests/LibWebView/TestImageDecoderIsolation.cpp b/Tests/LibWebView/TestImageDecoderIsolation.cppindex 9add533d930..cca9c92bcda 100644--- a/Tests/LibWebView/TestImageDecoderIsolation.cpp+++ b/Tests/LibWebView/TestImageDecoderIsolation.cpp@@ -7,12 +7,18 @@#include "HeadlessTest.h"#include <AK/HashTable.h>#include <AK/LexicalPath.h>+#include <AK/Utf16String.h>#include <LibCore/EventLoop.h>+#include <LibCore/File.h>#include <LibCore/System.h>#include <LibGfx/SystemTheme.h>+#include <LibIPC/TransportHandle.h>#include <LibTest/TestCase.h>+#include <LibURL/URL.h>+#include <LibWebCommon/WebView/SiteIsolation.h>#include <LibWebView/Application.h>#include <LibWebView/HeadlessWebView.h>+#include <LibWebView/ImageDecoderManager.h>#include <LibWebView/ProcessManager.h>#include <LibWebView/Utilities.h>#include <signal.h>@@ -49,9 +55,9 @@ HashTable<pid_t> processes_of_type(WebView::ProcessType type)static constexpr auto page_with_image = "<!DOCTYPE html><img src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\">"sv;-// An ImageDecoder parses untrusted images, so it is launched only for a process that has some to decode. Each such process-// has one of its own, and never sees another's images. A decoder that crashes is replaced for its renderer alone, once the-// renderer next has an image to decode.+// An ImageDecoder parses untrusted images, so it is launched only for a process that has some to decode. A process with no+// site has one of its own, and never sees another's images. A decoder that crashes is replaced for its renderer alone, once+// the renderer next has an image to decode.TEST_CASE(image_decoder_isolation){@@ -103,5 +109,198 @@ TEST_CASE(image_decoder_isolation)VERIFY(decoders_after_crash.contains(decoder));}- outln("PASS: each renderer gets an image decoder of its own when it needs one, which is replaced alone when it crashes");+ outln("PASS: a renderer with no site gets an image decoder of its own when it needs one, which is replaced alone when it crashes");+}++// The renderers of one site share its decoder, however many of them there are.++TEST_CASE(renderers_of_a_site_share_an_image_decoder)+{+ Test::HeadlessTestEnvironment environment { "TestImageDecoderSharing"sv };++ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());++ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));++ auto page_path = LexicalPath::join(environment.directory(), "image.html"sv).string();+ auto page = TRY_OR_FAIL(Core::File::open(page_path, Core::File::OpenMode::Write));+ TRY_OR_FAIL(page->write_until_depleted(page_with_image.bytes()));+ page->close();+ auto page_url = URL::create_with_file_scheme(page_path).value();++ auto first_view = WebView::HeadlessWebView::create(theme, { 800, 600 });+ auto second_view = WebView::HeadlessWebView::create(theme, { 800, 600 });++ size_t first_view_loads = 0;+ size_t second_view_loads = 0;+ first_view->on_load_finish = [&](auto const&) { ++first_view_loads; };+ second_view->on_load_finish = [&](auto const&) { ++second_view_loads; };+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 1 && second_view_loads >= 1; });++ first_view->load(page_url);+ second_view->load(page_url);+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 2 && second_view_loads >= 2; });++ VERIFY(processes_of_type(WebView::ProcessType::WebContent).size() >= 2);+ auto decoders = processes_of_type(WebView::ProcessType::ImageDecoder);+ VERIFY(decoders.size() == 1);++ // A renderer that comes to host a second site leaves the decoder, which stays with the renderer that has only the one.+ first_view->page().client().did_host_document_of_site("https://other.example"_utf16);+ first_view->load(page_url);+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 3; });++ auto decoders_after_second_site = processes_of_type(WebView::ProcessType::ImageDecoder);+ VERIFY(decoders_after_second_site.size() == 2);+ VERIFY(decoders_after_second_site.contains(*decoders.begin()));++ outln("PASS: the renderers of a site share one image decoder, which a renderer leaves when it hosts a second site");+}++// The PDF viewer has an origin of its own, but it only shows what the site of its process gave it. A renderer that hosts it+// has not come to host a second site, so it stays with the decoder of its site.++TEST_CASE(pdf_viewer_does_not_make_a_renderer_leave_the_image_decoder_of_its_site)+{+ Test::HeadlessTestEnvironment environment { "TestImageDecoderPdfViewer"sv };++ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());++ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));++ auto write_file = [&](StringView name, StringView contents) {+ auto path = LexicalPath::join(environment.directory(), name).string();+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));+ MUST(file->write_until_depleted(contents.bytes()));+ file->close();+ return URL::create_with_file_scheme(path).value();+ };+ write_file("document.pdf"sv, "%PDF-1.0\n"sv);+ auto image_page_url = write_file("image.html"sv, page_with_image);+ auto pdf_page_url = write_file("pdf.html"sv, R"html(<!DOCTYPE html>+<iframe src="document.pdf"></iframe>+<script>+ window.onload = () => {+ const image = new Image();+ image.onload = () => { document.title = "decoded"; };+ image.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";+ };+</script>)html"sv);++ auto first_view = WebView::HeadlessWebView::create(theme, { 800, 600 });+ auto second_view = WebView::HeadlessWebView::create(theme, { 800, 600 });++ size_t first_view_loads = 0;+ size_t second_view_loads = 0;+ bool second_view_decoded_image = false;+ first_view->on_load_finish = [&](auto const&) { ++first_view_loads; };+ second_view->on_load_finish = [&](auto const&) { ++second_view_loads; };+ second_view->on_title_change = [&](auto const& title) { second_view_decoded_image = title == "decoded"sv; };+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 1 && second_view_loads >= 1; });++ first_view->load(image_page_url);+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 2; });+ VERIFY(processes_of_type(WebView::ProcessType::ImageDecoder).size() == 1);++ second_view->load(pdf_page_url);+ Core::EventLoop::current().spin_until([&] { return second_view_decoded_image; });+ VERIFY(processes_of_type(WebView::ProcessType::ImageDecoder).size() == 1);++ outln("PASS: a renderer that hosts the PDF viewer stays with the image decoder of its site");+}++// Who shares a decoder decides whose images a malicious image can reach, so these are the rules that keep them apart. The+// child IDs stand for processes that do not exist, which the manager has no reason to care about.++TEST_CASE(image_decoder_sharing_rules)+{+ Test::HeadlessTestEnvironment environment { "TestImageDecoderSharingRules"sv };++ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());++ auto& manager = WebView::ImageDecoderManager::the();+ auto site_a = "https://a.example"_utf16;+ auto site_b = "https://b.example"_utf16;++ Vector<IPC::TransportHandle> handles;+ RefPtr<WebView::BrowsingSession> ordinary_session = WebView::Application::session_for_new_view(WebView::IsPrivate::No);+ RefPtr<WebView::BrowsingSession> private_session = WebView::Application::session_for_new_view(WebView::IsPrivate::Yes);+ auto connect = [&](u64 child_id, RefPtr<WebView::BrowsingSession> const& session, Optional<Utf16String> site) {+ handles.append(MUST(manager.connect_new_client(child_id, session, move(site))));+ };+ auto decoder_count = [] { return processes_of_type(WebView::ProcessType::ImageDecoder).size(); };+ auto decoder_of_site = [](StringView site) {+ pid_t pid = 0;+ WebView::Application::process_manager().for_each_process([&](WebView::Process& process) {+ if (process.type() == WebView::ProcessType::ImageDecoder && process.site_url().has_value() && process.site_url()->serialize().contains(site))+ pid = process.pid();+ });+ return pid;+ };++ // The processes of a site share a decoder, and those of another site do not.+ connect(1'000'001, ordinary_session, site_a);+ connect(1'000'002, ordinary_session, site_a);+ VERIFY(decoder_count() == 1);+ connect(1'000'003, ordinary_session, site_b);+ VERIFY(decoder_count() == 2);++ // Private browsing shares nothing with the same site outside it.+ connect(1'000'004, private_session, site_a);+ VERIFY(decoder_count() == 3);++ // A process with no site shares with nobody, and asking again launches nothing more.+ connect(1'000'005, ordinary_session, {});+ VERIFY(decoder_count() == 4);+ connect(1'000'005, ordinary_session, {});+ VERIFY(decoder_count() == 4);+ connect(1'000'006, ordinary_session, {});+ VERIFY(decoder_count() == 5);++ // Without site isolation a process may host anything, so its claim to a site does not make it safe to share with.+ auto mode = WebView::site_isolation_mode();+ WebView::set_site_isolation_mode(WebView::SiteIsolationMode::TopLevel);+ connect(1'000'007, ordinary_session, site_a);+ connect(1'000'008, ordinary_session, site_a);+ WebView::set_site_isolation_mode(mode);+ VERIFY(decoder_count() == 7);++ // A session that has ended shares nothing with the next, nor does a worker that outlived its session.+ private_session = nullptr;+ connect(1'000'009, WebView::Application::session_for_new_view(WebView::IsPrivate::Yes), site_a);+ VERIFY(decoder_count() == 8);+ connect(1'000'010, nullptr, site_a);+ VERIFY(decoder_count() == 9);++ // Only a process served by the decoder of a site has one to leave.+ VERIFY(manager.remove_client_from_decoder_of_site(1'000'002));+ VERIFY(!manager.remove_client_from_decoder_of_site(1'000'002));+ VERIFY(!manager.remove_client_from_decoder_of_site(1'000'005));++ // A site that loses its decoder gets a new one, and no other site notices.+ auto decoder_of_a = decoder_of_site("a.example"sv);+ auto crashed_decoder = decoder_of_site("b.example"sv);+ VERIFY(crashed_decoder != 0);+ TRY_OR_FAIL(Core::System::kill(crashed_decoder, SIGKILL));+ Core::EventLoop::current().spin_until([&] {+ return !processes_of_type(WebView::ProcessType::ImageDecoder).contains(crashed_decoder);+ });+ connect(1'000'003, ordinary_session, site_b);+ VERIFY(decoder_count() == 9);+ VERIFY(decoder_of_site("b.example"sv) != crashed_decoder);+ VERIFY(processes_of_type(WebView::ProcessType::ImageDecoder).contains(decoder_of_a));++ // A decoder ends with the last process it serves, and not before.+ handles.clear();+ manager.process_did_exit(1'000'003);+ Core::EventLoop::current().spin_until([&] { return decoder_count() == 8; });+ manager.process_did_exit(1'000'005);+ Core::EventLoop::current().spin_until([&] { return decoder_count() == 7; });+ for (u64 child_id = 1'000'001; child_id <= 1'000'010; ++child_id)+ manager.process_did_exit(child_id);+ Core::EventLoop::current().spin_until([&] { return decoder_count() == 0; });++ outln("PASS: image decoders are shared within a site and nowhere else, and end with the last process they serve");}diff --git a/UI/Qt/ProcessManagerWindow.cpp b/UI/Qt/ProcessManagerWindow.cppindex 62ecf909666..3169353f060 100644--- a/UI/Qt/ProcessManagerWindow.cpp+++ b/UI/Qt/ProcessManagerWindow.cpp@@ -617,17 +617,17 @@ void ProcessManagerWindow::refresh()processes_by_child_id.set(process.child_id, &process);// Each process is listed with the browser's own processes, with a site, or with the spare processes. A process- // that works for another, such as a page's image decoder or a worker's media server, is listed with it.+ // that works for another, such as a renderer's media server, is listed with it.auto is_spare = [](WebView::ProcessSnapshot const& process) {return process.type == WebView::ProcessType::WebContent && process.title.has_value() && *process.title == "(spare)"_utf16;};- // NB: A page's process, a worker's process, and a request server bound to a site, belong to that site.+ // NB: A page's process, a worker's process, and a request server or image decoder bound to a site, belong to that site.auto site_of = [](WebView::ProcessSnapshot const& process) -> QString {- if (!first_is_one_of(process.type, WebView::ProcessType::WebContent, WebView::ProcessType::WebWorker, WebView::ProcessType::RequestServer) || !process.site_url.has_value())+ if (!first_is_one_of(process.type, WebView::ProcessType::WebContent, WebView::ProcessType::WebWorker, WebView::ProcessType::RequestServer, WebView::ProcessType::ImageDecoder) || !process.site_url.has_value())return {};return task_manager_site_label(*process.site_url);};- // NB: A process that works for another may itself work for a third, as a worker's image decoder works for the+ // NB: A process that works for another may itself work for a third, as a worker's media server works for the// worker. A worker with its own site stays with that site; an opaque-origin worker follows its owner.auto section_process = [&](WebView::ProcessSnapshot const& process) -> WebView::ProcessSnapshot const& {auto const* section = &process;