Truly independent web browser
LibWebView: Grant WebDriver's renderer powers only per command
Andreas Kling4739d161396f
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 76747eb3417..82a3bb5d426 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -1472,10 +1472,10 @@ void ViewImplementation::consume_user_activation_of_input_handled_by(Badge<WebCom_pending_input_events[*index].user_activation_time.clear();}-bool ViewImplementation::take_input_to_open_link_in_new_tab(Badge<WebContentPage>)+bool ViewImplementation::take_input_to_open_link_in_new_tab(Badge<WebContentPage>, WebContentPage const& page){// NB: Automation lets a renderer synthesize the input that opens a link.- if (WebContentClient::renderers_may_synthesize_input())+ if (WebContentClient::renderers_may_synthesize_input_for_testing() || is_running_webdriver_input_command_in(page))return true;// NB: Each press opens at most one link, the earliest press first, and only while a page could still be handling it.auto now = MonotonicTime::now();@@ -3521,6 +3521,31 @@ void ViewImplementation::complete_webdriver_input_command(u64 command_id, Web::WApplication::the().complete_webdriver_content_command(command_id, move(response));}+static bool is_webdriver_cookie_command(StringView name)+{+ return name.is_one_of("get_all_cookies"sv, "get_named_cookie"sv, "add_cookie"sv, "delete_cookie"sv, "delete_all_cookies"sv);+}++// https://w3c.github.io/webdriver/#dfn-element-send-keys+// NB: The renderer splits the text on newlines into the paths of the files to select, if the element is a file input.+static Vector<ByteString> files_named_by_element_send_keys(StringView name, JsonValue const& envelope)+{+ if (name != "element_send_keys"sv || !envelope.is_object())+ return {};+ auto payload = envelope.as_object().get_object("__webdriver_input_payload"sv);+ if (!payload.has_value())+ return {};+ auto text = payload->get_string("text"sv);+ if (!text.has_value())+ return {};++ Vector<ByteString> files;+ text->bytes_as_string_view().for_each_split_view('\n', SplitBehavior::KeepEmpty, [&](StringView path) {+ files.append(path);+ });+ return files;+}+void ViewImplementation::dispatch_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol protocol){if (m_crash_state.has_value() && !m_crash_state->recovery_started) {@@ -3562,8 +3587,13 @@ void ViewImplementation::dispatch_webdriver_content_command(u64 command_id, Optiif (name == "crash_current_page"sv)m_pending_webdriver_crash_commands.set(command_id, { *target, name, navigable_id });- else- m_pending_webdriver_commands.set(command_id, { *target, name, navigable_id });+ else {+ // NB: A cookie command is for the cookies of the active document of its browsing context when it starts.+ Optional<URL::URL> cookie_document_url;+ if (is_webdriver_cookie_command(name))+ cookie_document_url = navigable->active_document_url();+ m_pending_webdriver_commands.set(command_id, { *target, name, navigable_id, protocol, false, files_named_by_element_send_keys(name, payload), false, move(cookie_document_url) });+ }target->async_run_webdriver_command(command_id, navigable_id, name, move(payload), move(arguments));}@@ -3574,6 +3604,44 @@ 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+{+ 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;+}++// NB: An input command dispatches its input in the page it runs in, until any navigation it started takes that page+// away.+bool ViewImplementation::is_running_webdriver_input_command_in(WebContentPage const& page) const+{+ if (!m_webdriver_input_command_running || m_webdriver_input_commands.is_empty())+ return false;+ auto command = m_pending_webdriver_commands.get(m_webdriver_input_commands.first().command_id);+ return command.has_value() && command->page.ptr() == &page && !command->only_waits_for_navigation;+}++Optional<URL::URL> ViewImplementation::url_of_webdriver_cookie_command_running_in(WebContentClient const& client) const+{+ for (auto const& [command_id, command] : m_pending_webdriver_commands) {+ if (&command.page->client() == &client && command.cookie_document_url.has_value())+ return command.cookie_document_url;+ }+ return {};+}++bool ViewImplementation::is_running_webdriver_window_command_in(WebContentPage const& page) const+{+ for (auto const& [command_id, command] : m_pending_webdriver_commands) {+ if (command.page.ptr() == &page && command.protocol == WebDriverProtocol::Classic+ && command.name.is_one_of("set_window_rect"sv, "maximize_window"sv, "minimize_window"sv, "fullscreen_window"sv))+ return true;+ }+ return false;+}+void ViewImplementation::prepare_page_for_navigable(WebContentPage& page){page.async_set_zoom_level(m_zoom_level);@@ -3772,6 +3840,7 @@ void ViewImplementation::move_pending_webdriver_commands_to_new_host(Badge<Canoncontinue;command.page = new_host;+ command.only_waits_for_navigation = true;new_host.async_run_webdriver_command(command_id, navigable_id, "wait_for_navigation"_string, JsonValue {}, {});}}diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex 7bae5a03a4a..7d5b6389439 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -332,7 +332,7 @@ public:// Consumes the activation of the input the page is handling, if that input gives activation.void consume_user_activation_of_input_handled_by(Badge<WebContentPage>, WebContentPage const&);// Opening a link in a new tab takes one key or mouse press the view delivered.- bool take_input_to_open_link_in_new_tab(Badge<WebContentPage>);+ bool take_input_to_open_link_in_new_tab(Badge<WebContentPage>, WebContentPage const&);void did_lose_input_event_endpoint(Badge<WebContentPage>, WebContentPage&);void did_consume_input_event_in_compositor(Badge<WebContentPage>, u64 event_id);void did_not_dispatch_input_event_through_compositor(Badge<WebContentPage>, u64 event_id);@@ -569,6 +569,12 @@ public:void run_webdriver_user_prompt_handling(Function<void(Web::WebDriver::Response)> on_complete);void did_complete_webdriver_user_prompt_handling(Badge<WebContentPage>, u64 request_id, Web::WebDriver::Response);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;+ 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;static Optional<ViewImplementation&> find_view_by_handle(StringView);void did_change_background_color(Badge<WebContentPage>, Gfx::Color);Gfx::Color page_background_color() const { return m_page_background_color; }@@ -1100,6 +1106,12 @@ protected:Optional<Web::HTML::CrossProcessId> navigable_id;WebDriverProtocol protocol { WebDriverProtocol::Classic };bool stays_on_page { false };+ // The paths an Element Send Keys command names, which the renderer may open to select them as files.+ Vector<ByteString> files_to_select {};+ // A command whose page went away while it waited for a navigation, which its new page only waits for.+ bool only_waits_for_navigation { false };+ // The URL of the document a cookie command is for, whose cookies alone the renderer may reach.+ Optional<URL::URL> cookie_document_url {};};HashMap<u64, PendingWebDriverCommand> m_pending_webdriver_commands;HashMap<u64, PendingWebDriverCommand> m_pending_webdriver_crash_commands;diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 34a9789a2ba..14433cac897 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -683,33 +683,55 @@ void WebContentClient::cancel_navigation_transactions()// Seeing HttpOnly cookies, storing cookies the way an HTTP response does, and changing a cookie by its identity are for// WebDriver and the test harness. RequestServer handles the cookies of HTTP responses and requests itself, so a renderer// serving an ordinary browsing session never needs any of it.-bool WebContentClient::renderers_may_access_cookies_like_http()+// NB: Under WebDriver, the renderer may do so only while it runs a cookie command, and only for the document the+// command is for. Otherwise any renderer of an automated browser could take the cookies of every site.+static Optional<URL::URL> url_of_webdriver_cookie_command_running_in(WebContentClient const& client){- return Application::browser_options().webdriver_browser_endpoint.has_value()- || Application::web_content_options().is_test_mode == IsTestMode::Yes;+ if (!Application::browser_options().webdriver_browser_endpoint.has_value())+ return {};++ Optional<URL::URL> url;+ ViewImplementation::for_each_view([&](ViewImplementation& view) {+ url = view.url_of_webdriver_cookie_command_running_in(client);+ return url.has_value() ? IterationDecision::Break : IterationDecision::Continue;+ });+ return url;}-bool WebContentClient::renderers_may_synthesize_input()+WebContentClient::HTTPCookieAccess WebContentClient::http_cookie_access_for(URL::URL const& url) const{- // WebDriver's actions and the internals object dispatch input as though the user produced it.- return Application::browser_options().webdriver_browser_endpoint.has_value()- || Application::web_content_options().is_test_mode == IsTestMode::Yes+ if (Application::web_content_options().is_test_mode == IsTestMode::Yes)+ return HTTPCookieAccess::Allowed;++ auto command_url = url_of_webdriver_cookie_command_running_in(*this);+ if (!command_url.has_value())+ return HTTPCookieAccess::Refused;+ return command_url->equals(url, URL::ExcludeFragment::Yes) ? HTTPCookieAccess::Allowed : HTTPCookieAccess::RefusedForURL;+}++bool WebContentClient::renderers_may_synthesize_input_for_testing()+{+ // The internals object dispatches input as though the user produced it.+ return Application::web_content_options().is_test_mode == IsTestMode::Yes|| Application::web_content_options().expose_internals_object == ExposeInternalsObject::Yes;}bool WebContentClient::may_read_local_files() const{- // WebDriver's Element Send Keys selects the files it names by path through the process hosting the file input.- if (Application::browser_options().webdriver_browser_endpoint.has_value())- return true;-return m_has_hosted_local_file_content;}Messages::WebContentClient::DidRequestAllCookiesWebdriverResponse WebContentClient::did_request_all_cookies_webdriver(URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context){- if (!renderers_may_access_cookies_like_http()) {- did_misbehave("did_request_all_cookies_webdriver"sv, "not driven by WebDriver"sv);+ if (auto access = http_cookie_access_for(url); access != HTTPCookieAccess::Allowed) {+ if (access == HTTPCookieAccess::Refused)+ did_misbehave("did_request_all_cookies_webdriver"sv, "not running a WebDriver cookie command"sv);+ return Vector<HTTP::Cookie::Cookie> {};+ }+ // NB: Only the internals object of a test asks for the cookies of a partition. WebDriver asks for the unpartitioned+ // cookies of the document its command is for.+ if (partition_context.has_value() && Application::web_content_options().is_test_mode != IsTestMode::Yes) {+ did_misbehave("did_request_all_cookies_webdriver"sv, "partition context outside of a test"sv);return Vector<HTTP::Cookie::Cookie> {};}return m_session->cookie_jar->get_all_cookies_webdriver(url, partition_context);@@ -732,8 +754,9 @@ Messages::WebContentClient::DidRequestNotificationsStateForTestingResponse WebCoMessages::WebContentClient::DidRequestNamedCookieResponse WebContentClient::did_request_named_cookie(URL::URL url, String name){- if (!renderers_may_access_cookies_like_http()) {- did_misbehave("did_request_named_cookie"sv, "not driven by WebDriver"sv);+ if (auto access = http_cookie_access_for(url); access != HTTPCookieAccess::Allowed) {+ if (access == HTTPCookieAccess::Refused)+ did_misbehave("did_request_named_cookie"sv, "not running a WebDriver cookie command"sv);return Optional<HTTP::Cookie::Cookie> {};}@@ -742,8 +765,9 @@ Messages::WebContentClient::DidRequestNamedCookieResponse WebContentClient::did_Messages::WebContentClient::DidRequestCookieResponse WebContentClient::did_request_cookie(Web::PageId page_id, Optional<Web::HTML::EnvironmentId> environment_id, URL::URL url, HTTP::Cookie::Source source){- if (source == HTTP::Cookie::Source::Http && !renderers_may_access_cookies_like_http()) {- did_misbehave("did_request_cookie"sv, "HTTP cookie source"sv);+ if (auto access = source == HTTP::Cookie::Source::Http ? http_cookie_access_for(url) : HTTPCookieAccess::Allowed; access != HTTPCookieAccess::Allowed) {+ if (access == HTTPCookieAccess::Refused)+ did_misbehave("did_request_cookie"sv, "HTTP cookie source"sv);return HTTP::Cookie::VersionedCookie {};}@@ -888,12 +912,28 @@ void WebContentClient::did_close_browsing_context(Web::PageId page_id)void WebContentClient::did_update_cookie(HTTP::Cookie::Cookie cookie){- if (!renderers_may_access_cookies_like_http()) {- did_misbehave("did_update_cookie"sv, "not driven by WebDriver"sv);+ if (Application::web_content_options().is_test_mode == IsTestMode::Yes) {+ m_session->cookie_jar->update_cookie(move(cookie));+ return;+ }++ // NB: WebDriver's Delete Cookie expires the cookies of the document its cookie command is for, which it got from+ // the cookie jar. So the browser expires its own copy of the cookie, and the renderer changes nothing else.+ auto command_url = url_of_webdriver_cookie_command_running_in(*this);+ if (!command_url.has_value()) {+ did_misbehave("did_update_cookie"sv, "not running a WebDriver cookie command"sv);return;}- m_session->cookie_jar->update_cookie(cookie);+ // NB: A cookie of the document can expire, and leave the cookie jar, before the renderer asks to expire it.+ for (auto existing : m_session->cookie_jar->get_all_cookies_webdriver(*command_url)) {+ if (existing.name != cookie.name || existing.domain != cookie.domain || existing.path != cookie.path+ || existing.host_only != cookie.host_only || existing.partition_key != cookie.partition_key)+ continue;+ existing.expiry_time = UnixDateTime::earliest();+ m_session->cookie_jar->update_cookie(move(existing));+ return;+ }}Messages::WebContentClient::DidIsKnownHstsHostResponse WebContentClient::did_is_known_hsts_host(String domain)diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 5e37f843a0f..507ab8858ff 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -122,8 +122,14 @@ public:Optional<i32> compositor_connection_id(Badge<Application>) const { return m_compositor_connection_id; }virtual void did_misbehave(StringView message_name, StringView reason) override;- static bool renderers_may_access_cookies_like_http();- static bool renderers_may_synthesize_input();+ enum class HTTPCookieAccess : u8 {+ Allowed,+ // A WebDriver cookie command runs, but for another document, which the renderer may not have heard of yet.+ RefusedForURL,+ Refused,+ };+ HTTPCookieAccess http_cookie_access_for(URL::URL const&) const;+ static bool renderers_may_synthesize_input_for_testing();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);diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex f663953981c..bade1e01e02 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -1104,7 +1104,7 @@ void WebContentPage::did_click_link(Web::HTML::PreparedNavigationDescriptor navi// NB: The renderer sends a link to open in a new tab only for the user's own click, which the view delivered.// That click opens the link whatever activation the page used up for other things, such as a popup its// click handler opened.- if (!view().take_input_to_open_link_in_new_tab({}))+ if (!view().take_input_to_open_link_in_new_tab({}, *this))return;view().open_navigation_in_new_tab(verified_navigation.release_value(), open_in_background ? Web::HTML::ActivateTab::No : Web::HTML::ActivateTab::Yes);} else {@@ -1125,7 +1125,7 @@ void WebContentPage::did_middle_click_link(Web::HTML::PreparedNavigationDescript}// NB: The renderer sends a link to open in a new tab only for the user's own click, which the view delivered.// That click opens the link whatever activation the page used up for other things.- if (!view().take_input_to_open_link_in_new_tab({}))+ if (!view().take_input_to_open_link_in_new_tab({}, *this))return;view().open_navigation_in_new_tab(verified_navigation.release_value(), Web::HTML::ActivateTab::No);}@@ -1445,10 +1445,20 @@ void WebContentPage::notify_about_user_activation(Web::HTML::CrossProcessId docuasync_notify_about_user_activation(document_id);}+// NB: The internals object of a test, and a WebDriver input command in the page it runs in, dispatch input as though+// the user produced it.+static bool may_synthesize_input(WebContentPage const& page)+{+ if (WebContentClient::renderers_may_synthesize_input_for_testing())+ return true;+ auto view = page.traversable().view();+ return view.has_value() && view->is_running_webdriver_input_command_in(page);+}+bool WebContentPage::has_transient_user_activation() const{// NB: Automation lets a renderer synthesize the input that gives it activation.- if (WebContentClient::renderers_may_synthesize_input())+ if (may_synthesize_input(*this))return true;if (m_last_user_activation.has_value() && MonotonicTime::now() - *m_last_user_activation < transient_activation_duration)return true;@@ -1499,7 +1509,7 @@ void WebContentPage::did_notify_about_user_activation(Web::HTML::CrossProcessId// NB: The renderer runs the steps for input the view is delivering to it, and it sends this before it reports that// it finished handling that input. So any other claim is a renderer handing out activation for input it never// got, unless automation lets it synthesize input.- if (!WebContentClient::renderers_may_synthesize_input()) {+ if (!may_synthesize_input(*this)) {auto view = traversable().view();if (!view.has_value() || !view->is_delivering_user_activation_to(*this))return;@@ -1557,7 +1567,9 @@ void WebContentPage::did_update_resource_count(i32 count_waiting)// Only WebDriver's window commands and the internals object of a test ask for a change to the window.static bool may_change_window(WebContentPage& page, StringView message){- if (WebContentClient::renderers_may_synthesize_input())+ if (WebContentClient::renderers_may_synthesize_input_for_testing())+ return true;+ if (auto view = page.traversable().view(); view.has_value() && view->is_running_webdriver_window_command_in(page))return true;page.client().did_misbehave(message, "not driven by WebDriver or a test"sv);return false;@@ -1610,7 +1622,10 @@ void WebContentPage::did_request_fullscreen_window(){// Element fullscreen needs and consumes the activation of the user's input, which the renderer checks. A// compromised renderer skips that check. The process of an isolated iframe asks for the window of its tab itself.- if (!consume_transient_user_activation()) {+ // NB: WebDriver's Fullscreen Window command makes the document element fullscreen with no input from the user.+ auto tab_view = traversable().view();+ auto is_webdriver_window_command = tab_view.has_value() && tab_view->is_running_webdriver_window_command_in(*this);+ if (!is_webdriver_window_command && !consume_transient_user_activation()) {async_deny_fullscreen_window();return;}@@ -1662,9 +1677,14 @@ bool WebContentPage::populates_a_navigation_to_local_file(ByteString const& pathvoid 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 reading the file a navigation it populates- // names: any other could read every file the user can.- if (!client().may_read_local_files() && !populates_a_navigation_to_local_file(path)) {+ // 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.+ 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()) {async_handle_file_return(EACCES, {}, request_id);return;}@@ -2250,8 +2270,8 @@ void WebContentPage::did_request_key_event_for_testing(Web::KeyEvent event){// NB: The event enters the tab's input path as the user's own, reaching the focused navigable in whatever process// hosts it and granting user activation, so only automation may ask for one.- if (!WebContentClient::renderers_may_synthesize_input()) {- client().did_misbehave("did_request_key_event_for_testing"sv, "not driven by WebDriver or a test"sv);+ if (!WebContentClient::renderers_may_synthesize_input_for_testing()) {+ client().did_misbehave("did_request_key_event_for_testing"sv, "not a test"sv);return;}// Only the compositor sets these, on its way to WebContent.@@ -2512,7 +2532,7 @@ void WebContentPage::did_update_indexed_database(String update)void WebContentPage::did_request_clipboard_entries_for_paste(u64 request_id){Vector<Web::Clipboard::SystemClipboardItem> items;- if (!WebContentClient::renderers_may_synthesize_input() && !view().take_paste_shortcut_handled_by({}, *this)) {+ if (!may_synthesize_input(*this) && !view().take_paste_shortcut_handled_by({}, *this)) {async_retrieved_clipboard_entries(request_id, items);return;}@@ -2548,8 +2568,8 @@ void WebContentPage::did_request_clipboard_entries(u64 request_id, Web::HTML::Crvoid WebContentPage::did_request_paste_from_clipboard_for_testing(){// NB: This stands in for the browser's Paste command, which hands the page the system clipboard data.- if (!WebContentClient::renderers_may_synthesize_input()) {- client().did_misbehave("did_request_paste_from_clipboard_for_testing"sv, "not driven by WebDriver or a test"sv);+ if (!WebContentClient::renderers_may_synthesize_input_for_testing()) {+ client().did_misbehave("did_request_paste_from_clipboard_for_testing"sv, "not a test"sv);return;}view().paste_from_clipboard(Web::Clipboard::PasteMode::AllMimeTypes);@@ -3107,8 +3127,8 @@ void WebContentPage::did_request_context_menu(Web::HTML::CrossProcessId local_rovoid WebContentPage::did_request_spelling_menu_action_for_testing(Web::SpellingMenuActionForTesting action, u32 guess_index){// NB: This activates the tab's own menu actions, so only automation may ask for it.- if (!WebContentClient::renderers_may_synthesize_input()) {- client().did_misbehave("did_request_spelling_menu_action_for_testing"sv, "not driven by WebDriver or a test"sv);+ if (!WebContentClient::renderers_may_synthesize_input_for_testing()) {+ client().did_misbehave("did_request_spelling_menu_action_for_testing"sv, "not a test"sv);return;}view().activate_spelling_menu_action_for_testing({}, *this, action, guess_index);@@ -3117,8 +3137,8 @@ void WebContentPage::did_request_spelling_menu_action_for_testing(Web::SpellingMvoid WebContentPage::did_request_page_translation_for_testing(String target_language){// NB: This translates the tab as its menu would, so only automation may ask for it.- if (!WebContentClient::renderers_may_synthesize_input()) {- client().did_misbehave("did_request_page_translation_for_testing"sv, "not driven by WebDriver or a test"sv);+ if (!WebContentClient::renderers_may_synthesize_input_for_testing()) {+ client().did_misbehave("did_request_page_translation_for_testing"sv, "not a test"sv);return;}view().page_translation().translate_for_testing({}, move(target_language));@@ -3306,8 +3326,11 @@ void WebContentPage::did_change_favicon(Gfx::ShareableBitmap favicon)void WebContentPage::did_request_delete_all_cookies(u64 request_id, URL::URL url){- if (!WebContentClient::renderers_may_access_cookies_like_http()) {- client().did_misbehave("did_request_delete_all_cookies"sv, "not driven by WebDriver"sv);+ if (auto access = client().http_cookie_access_for(url); access != WebContentClient::HTTPCookieAccess::Allowed) {+ if (access == WebContentClient::HTTPCookieAccess::Refused)+ client().did_misbehave("did_request_delete_all_cookies"sv, "not running a WebDriver cookie command"sv);+ else+ async_did_delete_all_cookies(request_id);return;}@@ -3434,8 +3457,8 @@ void WebContentPage::did_update_session_history_entry_scroll_restoration_mode(Wevoid WebContentPage::did_request_pinch_event_for_testing(Web::HTML::CrossProcessId local_root_id, Web::PinchEvent event){// NB: As for a key event for testing, the event is dispatched as the user's own.- if (!WebContentClient::renderers_may_synthesize_input()) {- client().did_misbehave("did_request_pinch_event_for_testing"sv, "not driven by WebDriver or a test"sv);+ if (!WebContentClient::renderers_may_synthesize_input_for_testing()) {+ client().did_misbehave("did_request_pinch_event_for_testing"sv, "not a test"sv);return;}@@ -3450,24 +3473,49 @@ void WebContentPage::did_request_pinch_event_for_testing(Web::HTML::CrossProcessvoid WebContentPage::did_request_webdriver_mouse_event(u64 request_id, Web::HTML::CrossProcessId local_root_id, Web::MouseEvent event){// NB: As for a key event for testing, the event is dispatched as the user's own.- if (!WebContentClient::renderers_may_synthesize_input()) {+ if (!may_synthesize_input(*this)) {client().did_misbehave("did_request_webdriver_mouse_event"sv, "not driven by WebDriver or a test"sv);return;}- auto on_handled = [page = NonnullRefPtr<WebContentPage>(*this), request_id]() {- page->async_did_handle_webdriver_mouse_event(request_id);- };- // The event is relative to the viewport of the local root its page dispatches input to.- if (auto root = view().traversable().find(local_root_id); root.has_value()) {- auto offset = view().traversable().local_root_offset(*root);- event.position.translate_by(offset);- event.screen_position.translate_by(offset);+ // NB: The renderer dispatches the event to a local root it hosts, so naming another would aim it at a document of+ // another page. The renderer reports the viewports of the child navigables it hosts with their parents, so+ // only a local root's viewport bounds the event below.+ auto root = hosted_navigable(local_root_id);+ if (!root.has_value() || (!root->is_top_level_traversable() && !root->has_remote_host())) {+ client().did_misbehave("did_request_webdriver_mouse_event"sv, "not a local root hosted by the page"sv);+ return;+ }++ // NB: The event enters the tab's input path at its position in the tab, so a position outside the viewport of the+ // local root would reach whatever the tab shows there. A legitimate one is inside, as WebDriver's actions move+ // the pointer only within the viewport. The viewport of an isolated iframe may not be known yet.+ auto viewport_size = root->is_top_level_traversable() ? view().viewport_size() : root->viewport_rect().map([](auto const& rect) { return rect.size(); }).value_or({});+ Web::DevicePixelRect viewport { {}, viewport_size };+ if (!viewport.contains(event.position)) {+ // NB: The viewport can shrink while a button is pressed, and the page must still get the button's release, so+ // it goes to the nearest position in the viewport.+ if (event.type != Web::MouseEvent::Type::MouseUp || viewport.is_empty()) {+ async_did_handle_webdriver_mouse_event(request_id);+ return;+ }+ auto clamped_x = clamp(event.position.x(), viewport.left(), viewport.right() - 1);+ auto clamped_y = clamp(event.position.y(), viewport.top(), viewport.bottom() - 1);+ event.screen_position.translate_by(Web::DevicePixelPoint { clamped_x, clamped_y } - event.position);+ event.position = { clamped_x, clamped_y };}++ // The event is relative to the viewport of the local root its page dispatches input to.+ auto offset = view().traversable().local_root_offset(*root);+ event.position.translate_by(offset);+ event.screen_position.translate_by(offset);// Only the compositor sets these, on its way to WebContent.event.async_scroll_performed_default_action = false;event.scrollbar_dragged_by_compositor = {};event.wheel_gesture_mark = {};+ auto on_handled = [page = NonnullRefPtr<WebContentPage>(*this), request_id]() {+ page->async_did_handle_webdriver_mouse_event(request_id);+ };view().enqueue_webdriver_mouse_event({}, move(event), move(on_handled));}@@ -3779,8 +3827,9 @@ void WebContentPage::did_set_cookie(Optional<Web::HTML::EnvironmentId> environme{// NB: Only WebDriver sets cookies like HTTP does, for the top-level documents it drives.if (source == HTTP::Cookie::Source::Http) {- if (!WebContentClient::renderers_may_access_cookies_like_http()) {- client().did_misbehave("did_set_cookie"sv, "HTTP cookie source"sv);+ if (auto access = client().http_cookie_access_for(url); access != WebContentClient::HTTPCookieAccess::Allowed) {+ if (access == WebContentClient::HTTPCookieAccess::Refused)+ client().did_misbehave("did_set_cookie"sv, "HTTP cookie source"sv);return;}client().session().cookie_jar->set_cookie(url, cookie, source, {}, HTTP::Cookie::SameSiteContext::same_site());diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex cde19f7fe59..8bb800a3308 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -24,6 +24,7 @@ if (BUILD_TESTING AND NOT WIN32)endif()ladybird_python_test(test-webdriver-bidi.py ARGS $<TARGET_FILE:WebDriver>)+ ladybird_python_test(test-webdriver-command-privileges.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-content-blockers.py ARGS $<TARGET_FILE:WebDriver> TIMEOUT 180)ladybird_python_test(test-webdriver-delete-session.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-element-screenshot.py ARGS $<TARGET_FILE:WebDriver>)diff --git a/Tests/LibWebView/test-webdriver-command-privileges.py b/Tests/LibWebView/test-webdriver-command-privileges.pynew file mode 100644index 00000000000..c831c551dbe--- /dev/null+++ b/Tests/LibWebView/test-webdriver-command-privileges.py@@ -0,0 +1,151 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++# The browser lets a renderer read a local file, reach cookies the way HTTP does, change the window, or synthesize input+# only while it runs a WebDriver command that needs it. This checks that those commands still work.++import http.server+import runpy+import subprocess+import sys+import tempfile+import threading+import time++from pathlib import Path++helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))++PAGE = b"""<!doctype html>+<input id="file" type="file">+<button id="button" onclick="this.textContent = 'clicked'">click</button>+<script>+window.buttonEvents = [];+addEventListener("mousedown", () => buttonEvents.push("mousedown"));+addEventListener("mouseup", () => buttonEvents.push("mouseup"));+</script>+"""++READ_FILE_SCRIPT = """+const done = arguments[arguments.length - 1];+const file = document.getElementById("file").files[0];+if (!file)+ done(null);+else+ file.text().then(text => done({ name: file.name, text }));+"""+++class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == "/favicon.ico":+ self.send_error(404)+ return+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(PAGE)++ def log_message(self, format, *args):+ pass+++def main():+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ with tempfile.TemporaryDirectory() as directory:+ upload = Path(directory) / "upload.txt"+ upload.write_text("uploaded contents")++ 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):+ status, payload, raw = helpers["request"](port, method, f"/session/{session}/{path}", body)+ assert status == 200, raw+ return payload["value"]++ def find(selector):+ element = command("POST", "element", {"using": "css selector", "value": selector})+ return next(iter(element.values()))++ command("POST", "url", {"url": f"http://127.0.0.1:{server.server_port}/"})+ deadline = time.monotonic() + 30+ while command("POST", "execute/sync", {"script": "return document.readyState", "args": []}) != "complete":+ assert time.monotonic() < deadline, "The page did not finish loading"+ time.sleep(0.01)++ command("POST", f"element/{find('#file')}/value", {"text": str(upload)})+ selected = command("POST", "execute/async", {"script": READ_FILE_SCRIPT, "args": []})+ assert selected == {"name": "upload.txt", "text": "uploaded contents"}, selected+ print("PASS: Element Send Keys selects the file it names")++ command("POST", "cookie", {"cookie": {"name": "session", "value": "secret", "httpOnly": True}})+ command("POST", "cookie", {"cookie": {"name": "other", "value": "value"}})+ names = sorted(cookie["name"] for cookie in command("GET", "cookie"))+ assert names == ["other", "session"], names+ assert command("GET", "cookie/session")["value"] == "secret"+ assert "session" not in command("POST", "execute/sync", {"script": "return document.cookie", "args": []})+ command("DELETE", "cookie/session")+ assert [cookie["name"] for cookie in command("GET", "cookie")] == ["other"]+ command("DELETE", "cookie")+ assert command("GET", "cookie") == []+ print("PASS: the cookie commands reach the cookies of the current document, HttpOnly ones too")++ rect = command("POST", "window/rect", {"width": 700, "height": 500})+ assert (rect["width"], rect["height"]) == (700, 500), rect+ print("PASS: Set Window Rect changes the window")++ # A button pressed where the viewport ends after it shrinks is still released.+ command("POST", "window/rect", {"width": 800, "height": 600})+ pointer_down = {+ "actions": [+ {+ "type": "pointer",+ "id": "mouse",+ "parameters": {"pointerType": "mouse"},+ "actions": [+ {"type": "pointerMove", "x": 700, "y": 500, "origin": "viewport"},+ {"type": "pointerDown", "button": 0},+ ],+ }+ ]+ }+ command("POST", "actions", pointer_down)+ command("POST", "window/rect", {"width": 400, "height": 300})+ command("DELETE", "actions")+ events = command("POST", "execute/sync", {"script": "return buttonEvents", "args": []})+ assert events == ["mousedown", "mouseup"], events+ print("PASS: Release Actions releases a button pressed outside the shrunken viewport")++ command("POST", "window/fullscreen")+ fullscreen = "return document.fullscreenElement === document.documentElement"+ assert command("POST", "execute/sync", {"script": fullscreen, "args": []}), "The document is not fullscreen"+ print("PASS: Fullscreen Window makes the document fullscreen")++ button = find("#button")+ command("POST", f"element/{button}/click")+ assert command("GET", f"element/{button}/text") == "clicked"+ print("PASS: Element Click clicks the element")+ 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()+ server.shutdown()+ server.server_close()+++main()