Truly independent web browser
LibWebView+WebContent: Request WebDriver's files with their own message
Shannon Boothbbd67dba3468
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 7819bc1fd65..e7f143d139c 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -3922,13 +3922,10 @@ void ViewImplementation::run_webdriver_commands_waiting_for_a_document(Badge<Candispatch_webdriver_content_command(command_id, command.navigable_id, command.name, move(command.payload), move(command.arguments), command.protocol);}-bool ViewImplementation::is_running_webdriver_command_to_select_file(WebContentPage const& page, StringView path) const+bool ViewImplementation::is_running_webdriver_command_to_select_file(WebContentPage const& page, u64 command_id, StringView path) const{- for (auto const& [command_id, command] : m_pending_webdriver_commands) {- if (command.page.ptr() == &page && command.files_to_select.contains_slow(path))- return true;- }- return false;+ auto command = m_pending_webdriver_commands.get(command_id);+ return command.has_value() && command->page.ptr() == &page && command->files_to_select.contains_slow(path);}// NB: An input command dispatches its input in the page it runs in, until any navigation it started takes that pagediff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex a86041acdcf..8f61f42cce7 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -606,7 +606,7 @@ public:void did_open_user_prompt(Badge<WebContentPage>);// NB: Under WebDriver, a renderer has some of the browser's powers only while it runs a command that needs them.- bool is_running_webdriver_command_to_select_file(WebContentPage const&, StringView path) const;+ bool is_running_webdriver_command_to_select_file(WebContentPage const&, u64 command_id, StringView path) const;Optional<URL::URL> url_of_webdriver_cookie_command_running_in(WebContentClient const&) const;bool is_running_webdriver_input_command_in(WebContentPage const&) const;bool is_running_webdriver_window_command_in(WebContentPage const&) const;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 35137efc5b7..c28d514ca08 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -1688,14 +1688,26 @@ void WebContentPage::did_change_picture_in_picture_player_controls_visibility(bovoid 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, 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() && !selects_file_for_webdriver()) {+ // Answer only a process that has hosted local file content: 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.+ if (!client().may_read_local_files()) {+ async_handle_file_return(EACCES, {}, request_id);+ return;+ }++ auto file = open_local_file_for_renderer(path);+ if (file.is_error())+ async_handle_file_return(file.error().code(), {}, request_id);+ else+ async_handle_file_return(0, file.release_value(), request_id);+}++// NB: For a file input, Element Send Keys selects the files listed in its text. The page running the command may read+// those files and no others.+void WebContentPage::did_request_file_for_webdriver(u64 command_id, ByteString path, i32 request_id)+{+ auto view = traversable().view();+ if (!view.has_value() || !view->is_running_webdriver_command_to_select_file(*this, command_id, path)) {async_handle_file_return(EACCES, {}, request_id);return;}diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 5993cc128e4..073ef89fe2f 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -291,6 +291,7 @@ private:virtual void did_change_picture_in_picture_video_size(Gfx::IntSize video_size) override;virtual void did_change_picture_in_picture_player_controls_visibility(bool shown) override;virtual void did_request_file(ByteString path, i32 request_id) override;+ virtual void did_request_file_for_webdriver(u64 command_id, ByteString path, i32 request_id) override;virtual void did_request_color_picker(Color current_color) override;virtual void did_request_date_picker(Utf16String input_type, Utf16String value, Utf16String minimum, Utf16String maximum) override;virtual void did_request_geolocation_position(u64 request_id, Web::HTML::CrossProcessId document_id) override;diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 6ee4b083eed..d82664a42f0 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -3657,6 +3657,16 @@ void ConnectionFromClient::request_file(Web::PageId page_id, Web::FileRequest fiasync_did_request_file(page_id, path, id);}+void ConnectionFromClient::request_file_for_webdriver(Web::PageId page_id, u64 command_id, Web::FileRequest file_request)+{+ i32 const id = last_id++;++ auto path = file_request.path();+ m_requested_files.set(id, move(file_request));++ async_did_request_file_for_webdriver(page_id, command_id, path, id);+}+void ConnectionFromClient::blob_url_entry_removed(Utf16String url){if (auto url_record = Web::DOMURL::parse(url.utf16_view()); url_record.has_value())diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex 651a4efd5a3..5a422074e2c 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -65,6 +65,7 @@ public:virtual void die() override;void request_file(Web::PageId page_id, Web::FileRequest);+ void request_file_for_webdriver(Web::PageId page_id, u64 command_id, Web::FileRequest);PageHost& page_host() { return *m_page_host; }PageHost const& page_host() const { return *m_page_host; }diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex f5f5bc0db07..fd615fd61e4 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -2159,6 +2159,11 @@ void PageClient::request_file(Web::FileRequest file_request)client().request_file(m_id, move(file_request));}+void PageClient::request_file_for_webdriver(u64 command_id, Web::FileRequest file_request)+{+ client().request_file_for_webdriver(m_id, command_id, move(file_request));+}+URL::BlobURLEntry::Token PageClient::page_did_add_blob_url_entry(Web::HTML::EnvironmentSettingsObject const& environment, Utf16String const& url, Web::FileAPI::SerializedBlobURLEntry const& entry){auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidAddBlobUrlEntry>(m_id, environment.id, url, entry);diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 8f4b6bb72a7..99d4e7036ea 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -64,6 +64,7 @@ public:WebDriverConnection& ensure_webdriver_session();void run_webdriver_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments);+ void request_file_for_webdriver(u64 command_id, Web::FileRequest);void webdriver_did_set_current_browsing_context(u64 command_id, Web::HTML::CrossProcessId navigable_id);void did_handle_webdriver_mouse_event(u64 request_id);bool prepare_webdriver_input_command(u64, Optional<Web::HTML::CrossProcessId>, JsonValue&);diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 7ce57518004..ecbbd60e471 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -242,6 +242,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_change_picture_in_picture_video_size(Web::PageId page_id, Gfx::IntSize video_size) =|did_change_picture_in_picture_player_controls_visibility(Web::PageId page_id, bool shown) =|did_request_file(Web::PageId page_id, ByteString path, i32 request_id) =|+ did_request_file_for_webdriver(Web::PageId page_id, u64 command_id, ByteString path, i32 request_id) =|did_request_color_picker(Web::PageId page_id, Color current_color) =|did_request_date_picker(Web::PageId page_id, Utf16String input_type, Utf16String value, Utf16String minimum, Utf16String maximum) =|did_request_geolocation_position(Web::PageId page_id, u64 request_id, Web::HTML::CrossProcessId document_id) =|diff --git a/Services/WebContent/WebDriverConnection.cpp b/Services/WebContent/WebDriverConnection.cppindex 4c3215a9039..808654bf692 100644--- a/Services/WebContent/WebDriverConnection.cpp+++ b/Services/WebContent/WebDriverConnection.cpp@@ -1928,8 +1928,8 @@ Web::WebDriver::Response WebDriverConnection::element_send_keys_impl(StringView// 6. Complete implementation specific steps equivalent to setting the selected files on the input element. If// multiple is true files are be appended to element's selected files.// NB: Each file is opened in the unsandboxed UI process, because the WebContent sandbox blocks this- // process from opening arbitrary paths.- auto read_files_and_apply_selection = [connection = this, input_element = GC::make_root(input_element)](this auto const& self, Vector<String> paths, size_t index, Vector<Web::HTML::SelectedFile> selected_files) -> void {+ // process from opening arbitrary paths. The UI process opens only the files listed in the command's text.+ auto read_files_and_apply_selection = [connection = this, command_id = *m_current_command_id, input_element = GC::make_root(input_element)](this auto const& self, Vector<String> paths, size_t index, Vector<Web::HTML::SelectedFile> selected_files) -> void {if (index < paths.size()) {auto path = paths[index].to_byte_string();@@ -1950,7 +1950,7 @@ Web::WebDriver::Response WebDriverConnection::element_send_keys_impl(StringViewself(move(paths), index + 1, move(selected_files));});- connection->current_browsing_context().page().client().request_file(move(file_request));+ connection->m_page_client->request_file_for_webdriver(command_id, move(file_request));return;}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 43c166c4ffa..9e4de5a4437 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -30,6 +30,7 @@ if (BUILD_TESTING AND NOT WIN32)ladybird_python_test(test-webdriver-default-browser.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-delete-session.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-element-screenshot.py ARGS $<TARGET_FILE:WebDriver>)+ ladybird_python_test(test-webdriver-element-send-keys-files.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-error-keep-alive.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-force-dark.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-permissions-settings.py ARGS $<TARGET_FILE:WebDriver>)diff --git a/Tests/LibWebView/test-webdriver-element-send-keys-files.py b/Tests/LibWebView/test-webdriver-element-send-keys-files.pynew file mode 100755index 00000000000..5a3a09cce81--- /dev/null+++ b/Tests/LibWebView/test-webdriver-element-send-keys-files.py@@ -0,0 +1,89 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++# https://w3c.github.io/webdriver/#dfn-element-send-keys+# A file input selects the files Element Send Keys names, which the renderer has the UI process open one at a time for+# the command. Any other element just takes the text, and a file the renderer can't read is an invalid argument.++import runpy+import subprocess+import sys+import tempfile+import time++from pathlib import Path++helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))++PAGE = "data:text/html,<input id=text><input id=file type=file multiple>"+++def main():+ with tempfile.TemporaryDirectory() as directory:+ file_path = Path(directory) / "file.txt"+ file_path.write_text("content")++ process, port = helpers["launch_webdriver"](sys.argv[1], "--headless", "--profile-path", directory)+ session = None+ try:+ session = helpers["create_session"](port)++ def command(method, path, body=None):+ return helpers["request"](port, method, f"/session/{session}/{path}", body)++ def value_of(method, path, body=None):+ status, payload, raw = command(method, path, body)+ assert status == 200, raw+ return payload["value"]++ def script(source):+ return value_of("POST", "execute/sync", {"script": source, "args": []})++ value_of("POST", "url", {"url": PAGE})+ deadline = time.monotonic() + 30+ while script("return document.readyState") != "complete":+ assert time.monotonic() < deadline, "The page did not finish loading"+ time.sleep(0.01)++ def element(selector):+ found = value_of("POST", "element", {"using": "css selector", "value": selector})+ return next(iter(found.values()))++ text_input = element("#text")+ file_input = element("#file")++ value_of("POST", f"element/{text_input}/value", {"text": str(file_path)})+ assert script("return document.getElementById('text').value") == str(file_path)+ print("PASS: a text input takes a file's path as text")++ value_of("POST", f"element/{file_input}/value", {"text": str(file_path)})+ files = script("return Array.from(document.getElementById('file').files, file => [file.name, file.size])")+ assert files == [["file.txt", 7]], files+ print("PASS: a file input selects the file")++ for path, reason in ((Path(directory) / "missing.txt", "a missing file"), (Path(directory), "a directory")):+ status, payload, raw = command("POST", f"element/{file_input}/value", {"text": str(path)})+ assert status == 400 and payload["value"]["error"] == "invalid argument", raw+ print(f"PASS: {reason} is an invalid argument")++ # The renderer is still there to run commands.+ assert script("return 1 + 1") == 2+ print("PASS: the renderer survives a file it couldn't read")+ finally:+ try:+ if session is not None:+ helpers["request"](port, "DELETE", f"/session/{session}")+ finally:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+++if __name__ == "__main__":+ main()