Truly independent web browser
LibWebView+LibWeb: Read the local files of navigations in the UI process
Andreas Klingb7e59542fe7d
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 68ed200398b..f1aba85aa2f 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -1709,8 +1709,8 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParauto origin_is_allowed = [&] {// Only a client that itself came from a file:// URL may reach the local file system. Traversing back to a- // file:// entry fetches it with the client of the document it replaces, though, which the UI process lets- // read the file of an entry that held local file content.+ // file:// entry fetches it with the client of the document it replaces, though, and the UI process reads+ // the file of an entry that held local file content.if (request->current_url().scheme() == "file"sv)return origin->is_file_origin() || (request->mode() == Infrastructure::Request::Mode::Navigate && request->history_navigation());@@ -1723,6 +1723,16 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParif (!browser_initiated_navigation && !origin_is_allowed())return error;+ // NB: A navigation's population steps run in the process with its source document, which can host web content.+ // That process does not read the file a navigation names: the UI process reads it, and hands it to the+ // process creating the document, with the response's headers. A navigation's request has the reserved+ // client its document is to have; an object element's own fetch, also in "navigate" mode, has none.+ if (request->current_url().scheme() == "file"sv && request->mode() == Infrastructure::Request::Mode::Navigate && request->reserved_client_snapshot()) {+ auto response = Infrastructure::Response::create();+ response->set_status_message("OK"sv);+ return PendingResponse::create(fetch_params, response);+ }+// Allow file:// pages to load subresources (scripts, styles, fonts, etc.) from other file:// URLs,// but block the fetch() API and other requests without a destination from reading arbitrary files.// Requests made via fetch() have an empty destination, so we use that to distinguish betweendiff --git a/Libraries/LibWebView/CanonicalSessionHistoryEntry.h b/Libraries/LibWebView/CanonicalSessionHistoryEntry.hindex ff6e6a041de..869464e6f95 100644--- a/Libraries/LibWebView/CanonicalSessionHistoryEntry.h+++ b/Libraries/LibWebView/CanonicalSessionHistoryEntry.h@@ -75,8 +75,8 @@ public:Utf16String navigable_target_name;Vector<CanonicalNestedHistory> nested_histories;- // Whether the UI process populated local file content for this document state. Only then may the process populating- // it again read the file its entry names: a process reports an entry's URL, but not this.+ // Whether the UI process populated local file content for this document state. Only then does the UI process read+ // the file its entry names when populating it again: a process reports an entry's URL, but not this.bool held_local_file_content { false };private:diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cppindex c14aadcb76e..ab08ab924e6 100644--- a/Libraries/LibWebView/CanonicalTraversable.cpp+++ b/Libraries/LibWebView/CanonicalTraversable.cpp@@ -1410,7 +1410,13 @@ void CanonicalTraversable::did_receive_changing_navigable_history_job_reached_po.user_involvement = operation->algorithm->user_involvement(),.navigation_id = finalized_navigation_id(*operation, navigable_id).value_or(Utf16String {}),};- auto loader = NavigationLoader::create(move(request));+ // NB: The process running the job need not have hosted local file content. The UI process reads the local file of+ // an entry whose document state held local file content for the process creating the document, as it does that+ // of any entry for a process running the job that may read local files itself.+ auto may_read_local_file = changing_navigable->target_entry->document_state->held_local_file_content || source_page.client().may_read_local_files()+ ? NavigationLoader::MayReadLocalFile::Yes+ : NavigationLoader::MayReadLocalFile::No;+ auto loader = NavigationLoader::create(move(request), may_read_local_file);changing_navigable->population = ChangingNavigable::CreatingNavigationParams { loader };source_page.owe_reply({ OwedReply::Kind::ChangingJob, operation_id, navigable_id });source_page.async_create_history_navigation_params(operation_id, loader->request(), allow_POST);@@ -1909,28 +1915,6 @@ bool CanonicalTraversable::client_populates_a_history_entry_for_site(WebContentCreturn false;}-// A history step's changing job populates its target entry's document in the process hosting the navigable, which need-// not have hosted local file content. For an entry whose document state held local file content, that process reads the-// file the entry's file: URL names.-bool CanonicalTraversable::page_populates_a_history_entry_for_local_file(WebContentPage const& page, ByteString const& path) const-{- for (auto const& [operation_id, operation] : m_history_operations) {- if (!operation->algorithm)- continue;- for (auto const& changing_navigable : operation->algorithm->changing_navigables()) {- if (!changing_navigable->has_pending_job())- continue;- auto const& target_entry = *changing_navigable->target_entry;- if (target_entry.document_state->held_local_file_content- && target_entry.url.scheme() == "file"sv- && target_entry.url.file_path() == path- && changing_job_endpoint(*changing_navigable) == &page)- return true;- }- }- return false;-}-RefPtr<WebContentPage> CanonicalTraversable::changing_job_endpoint(CanonicalNavigable const& navigable, CanonicalDocumentState const& target_document_state) const{if (auto const& populated_document = target_document_state.populated_document; populated_document.has_value() && populated_document->document->host())diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.hindex 9c136f472f3..f2fb9db7794 100644--- a/Libraries/LibWebView/CanonicalTraversable.h+++ b/Libraries/LibWebView/CanonicalTraversable.h@@ -121,7 +121,6 @@ public:bool represents(CanonicalNavigable const&, WebContentPage const&) const;bool page_hosts_any(WebContentPage const&) const;bool client_populates_a_history_entry_for_site(WebContentClient const&, Utf16String const&) const;- bool page_populates_a_history_entry_for_local_file(WebContentPage const&, ByteString const& path) const;void stop_hosting_in_page(CanonicalNavigable&, NonnullRefPtr<WebContentPage>);void release_page_if_unused(NonnullRefPtr<WebContentPage>);void end_history_jobs(CanonicalNavigable const&, CanonicalDocument const* populated_document = nullptr);diff --git a/Libraries/LibWebView/NavigationLoader.cpp b/Libraries/LibWebView/NavigationLoader.cppindex bcee1928be9..e8c2ab27b32 100644--- a/Libraries/LibWebView/NavigationLoader.cpp+++ b/Libraries/LibWebView/NavigationLoader.cpp@@ -5,10 +5,14 @@*/#include <AK/AnyOf.h>+#include <LibCore/Directory.h>+#include <LibCore/EventLoop.h>+#include <LibCore/File.h>#include <LibHTTP/HeaderList.h>#include <LibRequests/Request.h>#include <LibRequests/RequestClient.h>#include <LibRequests/RequestControlClient.h>+#include <LibThreading/ThreadPool.h>#include <LibURL/Parser.h>#include <LibURL/Site.h>#include <LibWebCommon/Fetch/Infrastructure/URL.h>@@ -16,6 +20,7 @@#include <LibWebCommon/HTML/CrossOrigin/OpenerPolicyEnforcement.h>#include <LibWebCommon/HTML/EmbedderPolicy.h>#include <LibWebCommon/HTML/NavigationParamsDescriptor.h>+#include <LibWebCommon/Loader/FileResponseHeaders.h>#include <LibWebCommon/SecureContexts/AbstractOperations.h>#include <LibWebView/Application.h>#include <LibWebView/CanonicalBrowsingContext.h>@@ -28,6 +33,7 @@#include <LibWebView/NavigationLoader.h>#include <LibWebView/RequestServerManager.h>#include <LibWebView/RequestServerSiteBindings.h>+#include <LibWebView/Utilities.h>#include <LibWebView/WebContentClient.h>#include <LibWebView/WebContentPage.h>#include <LibWebView/WorkerAgentManager.h>@@ -170,21 +176,23 @@ NavigationLoader::~NavigationLoader()}// NB: The process that fetched the response reports the URLs it reached. Fetching never redirects a request to a-// file: URL, so one among them on a navigation the UI process did not admit to a file: URL is made up: the-// document it would create could read local files. Such a navigation creates an error document instead.+// file: URL, so one among them other than the file: URL of a navigation the UI process admitted is made up: the+// document it would create could read local files, and the UI process would read the file it names. Such a+// navigation creates an error document instead.void NavigationLoader::refuse_made_up_local_file_urls(WebContentClient const& population_worker, Web::HTML::NavigationPopulationResult& result) const{- if (m_request.history_entry.url.scheme() == "file"sv)- return;-- auto is_file_url = [](URL::URL const& url) { return url.scheme() == "file"sv; };- auto names_a_local_file = result.redirected_url.has_value() && is_file_url(*result.redirected_url);+ auto is_made_up_file_url = [&](URL::URL const& url) {+ if (url.scheme() != "file"sv)+ return false;+ return m_requested_url.scheme() != "file"sv || !url.equals(m_requested_url, URL::ExcludeFragment::Yes);+ };+ auto names_a_made_up_local_file = result.redirected_url.has_value() && is_made_up_file_url(*result.redirected_url);if (auto const* navigation_params = result.navigation_params.get_pointer<Web::HTML::NavigationParamsDescriptor>()) {- names_a_local_file |= any_of(navigation_params->response.url_list, is_file_url);+ names_a_made_up_local_file |= any_of(navigation_params->response.url_list, is_made_up_file_url);if (navigation_params->request.has_value())- names_a_local_file |= any_of(navigation_params->request->url_list, is_file_url);+ names_a_made_up_local_file |= any_of(navigation_params->request->url_list, is_made_up_file_url);}- if (names_a_local_file) {+ if (names_a_made_up_local_file) {discard(population_worker, result);result.navigation_params = Web::HTML::NavigationParamsNullOrError {};result.redirected_url.clear();@@ -390,6 +398,18 @@ void NavigationLoader::acquire_response_body(WebContentClient const& population_m_completion_steps = move(completion_steps);auto const* body_handle = response_body_handle(*m_result);+ if (auto const* navigation_params = m_result->navigation_params.get_pointer<Web::HTML::NavigationParamsDescriptor>()) {+ auto const& response_url = navigation_params->response.url_list.is_empty() ? m_request.history_entry.url : navigation_params->response.url_list.last();+ if (response_url.scheme() == "file"sv) {+ // NB: Only the UI process reads the file, so a response for it that names a body is made up.+ if (body_handle) {+ did_acquire(false);+ return;+ }+ read_local_file_for_response();+ return;+ }+ }if (!body_handle) {did_acquire(!reports_an_http_response_of_its_own());return;@@ -419,6 +439,55 @@ void NavigationLoader::acquire_response_body(WebContentClient const& population_m_response_body_request = request;}+// NB: The process that fetched a navigation's response to a file: URL ran the navigation's population steps for a+// source document that can be web content, so it did not read the file. The UI process reads the file the admitted+// URL names, off its main thread, and the process creating the document, which may read local files, takes it.+void NavigationLoader::read_local_file_for_response()+{+ if (m_may_read_local_file == MayReadLocalFile::No || m_requested_url.scheme() != "file"sv) {+ did_read_local_file_for_response(Error::from_errno(EACCES));+ return;+ }++ Threading::ThreadPool::the().submit([weak_this = make_weak_ptr(), path = m_requested_url.file_path(), event_loop = Core::EventLoop::current_weak()] mutable {+ auto read_local_file = [&] -> ErrorOr<LocalFile> {+ auto file = TRY(Core::File::adopt_fd(TRY(open_local_file_for_renderer(path)).take_fd(), Core::File::OpenMode::Read));+ if (TRY(Core::Directory::is_valid_directory(file->fd())))+ return Error::from_errno(EISDIR);+ auto stat = TRY(file->stat());+ return LocalFile { TRY(file->read_until_eof()), stat.st_mtime };+ };+ auto local_file = read_local_file();++ auto origin_event_loop = event_loop->take();+ if (!origin_event_loop.is_alive())+ return;+ origin_event_loop->deferred_invoke([weak_this = move(weak_this), local_file = move(local_file)] mutable {+ if (auto* loader = weak_this.ptr())+ loader->did_read_local_file_for_response(move(local_file));+ });+ });+}++void NavigationLoader::did_read_local_file_for_response(ErrorOr<LocalFile> local_file)+{+ if (!m_completion_steps)+ return;++ // NB: A file the UI process cannot read creates an error document, as a network error does.+ if (local_file.is_error()) {+ m_result->navigation_params = Web::HTML::NavigationParamsNullOrError { Utf16String::formatted("{}", local_file.error()) };+ did_acquire(true);+ return;+ }++ auto& response = m_result->navigation_params.get<Web::HTML::NavigationParamsDescriptor>().response;+ auto header_list = Web::response_headers_for_file(m_requested_url.file_path(), local_file.value().contents.size(), local_file.value().modified_time);+ response.headers = header_list->headers();+ response.body = move(local_file.value().contents);+ did_acquire(true);+}+// NB: The process that fetched a navigation's response reports the URLs it reached: the history entry's URL, and the// last URLs of the response's and the request's URL lists.template<typename Callback>diff --git a/Libraries/LibWebView/NavigationLoader.h b/Libraries/LibWebView/NavigationLoader.hindex cd07d913788..250dc0eee93 100644--- a/Libraries/LibWebView/NavigationLoader.h+++ b/Libraries/LibWebView/NavigationLoader.h@@ -6,6 +6,8 @@#pragma once+#include <AK/ByteBuffer.h>+#include <AK/Error.h>#include <AK/Function.h>#include <AK/Optional.h>#include <AK/OwnPtr.h>@@ -23,6 +25,7 @@#include <LibWebView/Export.h>#include <LibWebView/Forward.h>#include <LibWebView/RequestServerManager.h>+#include <time.h>namespace WebView {@@ -34,9 +37,16 @@ class WEBVIEW_API NavigationLoader finalpublic:AK_ALLOC_WITH_KMALLOC;- static NonnullRefPtr<NavigationLoader> create(Web::HTML::NavigationPopulationRequest request)+ // Whether the UI process may read the local file that the request's file: URL names, for the process creating the+ // document: the UI process admitted a navigation to the URL, or its entry's document state held local file content.+ enum class MayReadLocalFile : bool {+ No,+ Yes,+ };++ static NonnullRefPtr<NavigationLoader> create(Web::HTML::NavigationPopulationRequest request, MayReadLocalFile may_read_local_file = MayReadLocalFile::No){- return adopt_ref(*new NavigationLoader(move(request)));+ return adopt_ref(*new NavigationLoader(move(request), may_read_local_file));}~NavigationLoader();@@ -107,11 +117,20 @@ public:static void discard(WebContentClient const& population_worker, Web::HTML::NavigationPopulationResult&);private:- explicit NavigationLoader(Web::HTML::NavigationPopulationRequest request)+ NavigationLoader(Web::HTML::NavigationPopulationRequest request, MayReadLocalFile may_read_local_file): m_request(move(request))+ , m_requested_url(m_request.history_entry.url)+ , m_may_read_local_file(may_read_local_file){}+ struct LocalFile {+ ByteBuffer contents;+ time_t modified_time { 0 };+ };+ void read_local_file_for_response();+ void did_read_local_file_for_response(ErrorOr<LocalFile>);+void determine_the_origin_of_the_response();bool reported_urls_match_the_response_url(URL::URL const&) const;bool reports_an_http_response_of_its_own() const;@@ -121,6 +140,9 @@ private:void release_response_body();Web::HTML::NavigationPopulationRequest m_request;+ // The URL the request was made for, before the process that fetched the response reported where it ended up.+ URL::URL m_requested_url;+ MayReadLocalFile m_may_read_local_file { MayReadLocalFile::No };Optional<Web::HTML::NavigationPopulationResult> m_result;RefPtr<Requests::Request> m_response_body_request;RefPtr<HTTP::HeaderList> m_response_header_list;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 79302fb20c6..c5fff94d689 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -1661,37 +1661,17 @@ void WebContentPage::did_change_picture_in_picture_player_controls_visibility(boview().did_change_picture_in_picture_player_controls_visibility({}, shown);}-// A navigation's population steps run in the process with its source document, which need not have hosted local file-// content. For a navigation to a file: URL the UI process admitted, that process reads the file the URL names, as it does-// for a history step to an entry of one.-bool WebContentPage::populates_a_navigation_to_local_file(ByteString const& path) const-{- if (traversable().page_populates_a_history_entry_for_local_file(*this, path))- return true;-- bool result = false;- traversable().for_each_in_inclusive_subtree([&](CanonicalNavigable const& navigable) {- auto navigation = navigable.uncommitted_navigation();- result = navigation- && navigation->worker() == this- && navigation->url.scheme() == "file"sv- && navigation->url.file_path() == path;- return result ? IterationDecision::Break : IterationDecision::Continue;- });- return result;-}-void WebContentPage::did_request_file(ByteString path, i32 request_id){// NB: The renderer's sandbox keeps it out of the local file system, so this is the only way it can read a file.- // Answer only a process that has hosted local file content, one reading the file a navigation it populates- // names, or one selecting a file that WebDriver's Element Send Keys command it runs names: any other could- // read every file the user can.+ // Answer only a process that has hosted local file content, or one selecting a file that WebDriver's Element+ // Send Keys command it runs names: any other could read every file the user can. The UI process reads the+ // file a navigation names itself, for the process creating the document.auto selects_file_for_webdriver = [&] {auto view = traversable().view();return view.has_value() && view->is_running_webdriver_command_to_select_file(*this, path);};- if (!client().may_read_local_files() && !populates_a_navigation_to_local_file(path) && !selects_file_for_webdriver()) {+ if (!client().may_read_local_files() && !selects_file_for_webdriver()) {async_handle_file_return(EACCES, {}, request_id);return;}@@ -2743,7 +2723,8 @@ void WebContentPage::did_complete_navigation_unload_check(Web::HTML::CrossProcesApplication::the().allocate_ui_process_cross_process_id());population_request.target_snapshot_params.sandboxing_flags |= navigable->snapshot_target_snapshot_params().sandboxing_flags;ongoing_navigation->history_entry = MUST(CanonicalSessionHistoryEntry::create_from_descriptor(Web::HTML::create_session_history_entry_descriptor(population_request.history_entry, 0)));- ongoing_navigation->state = CanonicalNavigation::CreatingNavigationParams { NavigationLoader::create(move(population_request)) };+ // NB: The UI process admitted the navigation, so it reads the local file a file: URL names.+ ongoing_navigation->state = CanonicalNavigation::CreatingNavigationParams { NavigationLoader::create(move(population_request), NavigationLoader::MayReadLocalFile::Yes) };async_create_navigation_params(ongoing_navigation->loader()->request());// Requesting navigation params starts the fetch, so a view's top-level population begins its recordeddiff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 1ed293402fb..1faf0d71779 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -192,7 +192,6 @@ private:bool holds_container_of(CanonicalNavigable const& child_frame, StringView message_name);bool continue_navigation_population_in_selected_process(Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id);void for_each_hosted_document(Function<IterationDecision(CanonicalDocument&)> const&) const;- bool populates_a_navigation_to_local_file(ByteString const& path) const;Optional<CanonicalDocument&> document_with_hosted_environment(Web::HTML::EnvironmentId const& environment_id) const;StorageJar* storage_jar(Web::StorageAPI::StorageEndpointType) const;Optional<String> canonical_storage_key(Web::HTML::EnvironmentId const&) const;diff --git a/Tests/LibWebView/TestRendererResponseBodyClaims.cpp b/Tests/LibWebView/TestRendererResponseBodyClaims.cppindex 068001229ad..8c415b17ceb 100644--- a/Tests/LibWebView/TestRendererResponseBodyClaims.cpp+++ b/Tests/LibWebView/TestRendererResponseBodyClaims.cpp@@ -13,6 +13,7 @@#include <LibCore/Socket.h>#include <LibCore/TCPServer.h>#include <LibGfx/SystemTheme.h>+#include <LibHTTP/HeaderList.h>#include <LibRequests/Request.h>#include <LibRequests/RequestClient.h>#include <LibTest/TestCase.h>@@ -611,6 +612,57 @@ TEST_CASE(made_up_file_url_does_not_reach_a_navigation)EXPECT_NE(navigation->url.scheme(), "file"sv);}+// The process running a navigation's population steps can host web content, so it does not read the local file that a+// file: URL names. The UI process reads the file of a navigation it admitted, or of an entry whose document state held+// local file content, for the process creating the document. It reads no other file, and ignores any body the process+// reports.+TEST_CASE(ui_process_reads_the_local_file_of_a_navigation)+{+ TestFixture fixture;+ auto view = fixture.create_view();++ auto write_file = [&](StringView name, StringView contents) {+ auto path = LexicalPath::join(fixture.directory(), name).string();+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write));+ MUST(file->write_until_depleted(contents.bytes()));+ return URL::create_with_file_scheme(path).release_value();+ };+ auto local_file_url = write_file("local.html"sv, "<p>The local file.</p>"sv);+ auto other_local_file_url = write_file("other.html"sv, "<p>Another local file.</p>"sv);++ auto acquire = [&](WebView::NavigationLoader::MayReadLocalFile may_read_local_file, Function<void(Web::HTML::NavigationParamsDescriptor&)> report) {+ auto loader = WebView::NavigationLoader::create(population_request_for(*view, local_file_url, Utf16String::from_utf8(generate_random_uuid())), may_read_local_file);+ auto result = result_with_response_body_of(0, 0);+ auto& navigation_params = result.navigation_params.get<Web::HTML::NavigationParamsDescriptor>();+ navigation_params.response.url_list = { local_file_url };+ navigation_params.response.body = MUST(ByteBuffer::copy("Made up by the process."sv.bytes()));+ report(navigation_params);+ loader->refuse_made_up_local_file_urls(view->page().client(), result);+ loader->did_finish_navigation_params_creation(move(result));++ Optional<bool> acquired;+ loader->acquire_response_body(view->page().client(), [&](bool succeeded) { acquired = succeeded; });+ Core::EventLoop::current().spin_until([&] { return acquired.has_value(); });+ EXPECT(*acquired);+ return loader->take_result().navigation_params;+ };++ auto navigation_params = acquire(WebView::NavigationLoader::MayReadLocalFile::Yes, [](auto&) { });+ VERIFY(navigation_params.has<Web::HTML::NavigationParamsDescriptor>());+ auto const& response = navigation_params.get<Web::HTML::NavigationParamsDescriptor>().response;+ EXPECT_EQ(StringView { response.body.get<ByteBuffer>() }, "<p>The local file.</p>"sv);+ EXPECT_EQ(HTTP::HeaderList::create(response.headers)->get("Content-Type"sv).value_or({}), "text/html"sv);++ // An entry whose document state held no local file content gets an error document.+ EXPECT(acquire(WebView::NavigationLoader::MayReadLocalFile::No, [](auto&) { }).has<Web::HTML::NavigationParamsNullOrError>());++ // So does a navigation whose response the process reports for another local file.+ EXPECT(acquire(WebView::NavigationLoader::MayReadLocalFile::Yes, [&](auto& navigation_params) {+ navigation_params.response.url_list = { other_local_file_url };+ }).has<Web::HTML::NavigationParamsNullOrError>());+ EXPECT(view->page().client().is_open());+}+// The URLs a process reports for a navigation's response name its document and the process that hosts it. The UI// process acquires the response body only if they are the URL that RequestServer fetched, apart from the fragment.TEST_CASE(reported_response_url_is_the_url_requestserver_fetched)