Truly independent web browser
LibWebView: Let sites ask for location by default
sideshowbarker322741dbc525
diff --git a/Base/res/ladybird/about-pages/settings/geolocation.js b/Base/res/ladybird/about-pages/settings/geolocation.jsindex a7998f6a853..09118edb1e2 100644--- a/Base/res/ladybird/about-pages/settings/geolocation.js+++ b/Base/res/ladybird/about-pages/settings/geolocation.js@@ -1,7 +1,7 @@const enableGeolocation = document.querySelector("#enable-geolocation");enableGeolocation.addEventListener("change", () => {- ladybird.sendMessage("setGeolocationEnabled", enableGeolocation.checked);+ ladybird.sendMessage("setLocationPolicy", enableGeolocation.checked ? "ask" : "block");});document.addEventListener("WebUIMessage", event => {@@ -13,9 +13,9 @@ document.addEventListener("WebUIMessage", event => {if (event.detail.name !== "loadSettings") {return;}- if (!Object.hasOwn(event.detail.data, "geolocationEnabled")) {+ if (!Object.hasOwn(event.detail.data, "locationPolicy")) {return;}- enableGeolocation.checked = event.detail.data.geolocationEnabled === true;+ enableGeolocation.checked = event.detail.data.locationPolicy === "ask";});diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp b/Libraries/LibWeb/PermissionsAPI/Permissions.cppindex 7d4bc79c65b..5e0e6d617de 100644--- a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp@@ -62,7 +62,7 @@ PermissionState request_permission(PermissionDescriptor const& descriptor)// 4. If the user gives express permission to use the powerful feature, set current state to "granted"; otherwise to "denied".// The user's interaction may provide new information about the user's intent for the origin.- if (descriptor.name == "geolocation"_utf16 || HTML::Window::in_test_mode()) {+ if (HTML::Window::in_test_mode()) {current_state = PermissionState::Granted;} else {current_state = PermissionState::Denied;diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex b0835e16c4a..66d8444b6d5 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -61,6 +61,7 @@#include <LibWebView/HelperProcess.h>#include <LibWebView/HistoryStore.h>#include <LibWebView/Menu.h>+#include <LibWebView/PermissionManager.h>#include <LibWebView/PictureInPictureWindow.h>#include <LibWebView/ProcessType.h>#include <LibWebView/RequestServerManager.h>@@ -158,6 +159,11 @@ struct ApplicationSettingsObserver final : public SettingsObserver {{Application::the().content_blocker_settings_changed({});}++ virtual void geolocation_settings_changed() override+ {+ Application::the().location_policy_changed({});+ }};struct ApplicationBookmarkStoreObserver final : public BookmarkStoreObserver {@@ -1225,6 +1231,7 @@ NonnullRefPtr<BrowsingSession> Application::session_for_new_view(IsPrivate is_prreturn *session;auto session = BrowsingSession::create(IsPrivate::Yes);+ session->permission_manager = PermissionManager::create_for_private_session(*the().m_default_session->permission_manager);the().m_private_session = session;return session;}@@ -1703,6 +1710,9 @@ ErrorOr<void> Application::launch_services()notify_devtools_of_storage_change(jar, change);};+ m_default_session->permission_manager = PermissionManager::create_for_ordinary_session(LexicalPath::join(profile().paths().config, "Permissions.json"sv).string());+ update_permission_defaults();+m_settings_observer = make<ApplicationSettingsObserver>();m_bookmark_store_observer = make<ApplicationBookmarkStoreObserver>();@@ -2933,6 +2943,23 @@ void Application::apply_view_options(Badge<ViewImplementation>, ViewImplementatipage.async_debug_request("navigator-compatibility-mode"sv, m_navigator_compatibility_mode);}+bool Application::sites_can_ask_for_location() const+{+ return settings().location_policy() == LocationPolicy::Ask && Core::GeolocationProvider::is_available();+}++void Application::location_policy_changed(Badge<ApplicationSettingsObserver>)+{+ update_permission_defaults();+}++void Application::update_permission_defaults()+{+ // NB: A private session reads its defaults from the ordinary one.+ auto state = sites_can_ask_for_location() ? Web::Permissions::EffectiveState::Prompt : Web::Permissions::EffectiveState::Denied;+ m_default_session->permission_manager->set_global_default(Web::Permissions::PermissionName::Geolocation, state);+}+void Application::languages_changed(Badge<ApplicationSettingsObserver>){WorkerProcessManager::the().update_preferred_languages(m_settings->languages());diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex f17a3ef669f..608eb277743 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -169,6 +169,10 @@ public:void background_networking_settings_changed(Badge<ApplicationSettingsObserver>);+ // True unless the user has turned location off, or there's no way to find it.+ bool sites_can_ask_for_location() const;+ void location_policy_changed(Badge<ApplicationSettingsObserver>);+bool content_blocking_enabled() const;bool has_content_blocking_rules() const;void apply_content_blocking_policy(WebContentPage&);@@ -485,6 +489,7 @@ private:void stop_current_content_blocker_list_update_and_continue();void finish_current_content_blocker_list_update();ErrorOr<NonnullRawPtr<Core::GeolocationProvider>> ensure_geolocation_provider();+ void update_permission_defaults();void initialize_actions();void update_vertical_tabs_action();diff --git a/Libraries/LibWebView/BrowsingSession.cpp b/Libraries/LibWebView/BrowsingSession.cppindex 42ef0d58f0c..2538a13383c 100644--- a/Libraries/LibWebView/BrowsingSession.cpp+++ b/Libraries/LibWebView/BrowsingSession.cpp@@ -10,6 +10,7 @@#include <LibWebView/FaviconStore.h>#include <LibWebView/HSTSStore.h>#include <LibWebView/HistoryStore.h>+#include <LibWebView/PermissionManager.h>#include <LibWebView/SessionStore.h>#include <LibWebView/StorageJar.h>diff --git a/Libraries/LibWebView/BrowsingSession.h b/Libraries/LibWebView/BrowsingSession.hindex 785f3b73fae..0e3a3b14946 100644--- a/Libraries/LibWebView/BrowsingSession.h+++ b/Libraries/LibWebView/BrowsingSession.h@@ -40,6 +40,7 @@ public:OwnPtr<FaviconStore> favicon_store;OwnPtr<HistoryStore> history_store;OwnPtr<SessionStore> session_store;+ OwnPtr<PermissionManager> permission_manager;private:explicit BrowsingSession(IsPrivate);diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.hindex 3322ab830ed..1657170f193 100644--- a/Libraries/LibWebView/Forward.h+++ b/Libraries/LibWebView/Forward.h@@ -53,6 +53,7 @@ class ProcessManager;class RequestServerInstance;class RequestServerManager;class RequestServerSiteBindings;+class PermissionManager;class SessionStore;class Settings;class SettingsUI;diff --git a/Libraries/LibWebView/Settings.cpp b/Libraries/LibWebView/Settings.cppindex 2b5d8bd8b94..53d2a6711a0 100644--- a/Libraries/LibWebView/Settings.cpp+++ b/Libraries/LibWebView/Settings.cpp@@ -74,7 +74,7 @@ static constexpr auto SITE_SETTING_POLICY_KEY = "policy"sv;static constexpr auto SITE_SETTING_SITE_FILTERS_KEY = "siteFilters"sv;static constexpr auto AUTOPLAY_KEY = "autoplay"sv;-static constexpr auto GEOLOCATION_ENABLED_KEY = "geolocationEnabled"sv;+static constexpr auto LOCATION_POLICY_KEY = "locationPolicy"sv;static constexpr auto BROWSING_DATA_KEY = "browsingData"sv;static constexpr auto DISK_CACHE_KEY = "diskCache"sv;@@ -423,8 +423,10 @@ Settings Settings::create(ByteString settings_path, Vector<String> platform_langload_site_setting(settings.m_autoplay, AUTOPLAY_KEY);- if (auto geolocation_enabled = settings_json.value().get_bool(GEOLOCATION_ENABLED_KEY); geolocation_enabled.has_value())- settings.m_geolocation_enabled = *geolocation_enabled && Core::GeolocationProvider::is_available();+ // NB: The geolocationEnabled key this replaced was written on every save, so its false was rarely the user's+ // choice; it's ignored, and every profile starts out letting sites ask.+ if (auto location_policy = settings_json.value().get_string(LOCATION_POLICY_KEY); location_policy.has_value() && *location_policy == "block"sv)+ settings.m_location_policy = LocationPolicy::Block;if (auto browsing_data_settings = settings_json.value().get(BROWSING_DATA_KEY); browsing_data_settings.has_value())settings.m_browsing_data_settings = parse_browsing_data_settings(*browsing_data_settings);@@ -643,7 +645,7 @@ JsonValue Settings::serialize_json() constsave_site_setting(m_autoplay, AUTOPLAY_KEY);- settings.set(GEOLOCATION_ENABLED_KEY, m_geolocation_enabled);+ settings.set(LOCATION_POLICY_KEY, m_location_policy == LocationPolicy::Block ? "block"_string : "ask"_string);JsonObject disk_cache_settings;disk_cache_settings.set(DISK_CACHE_MAXIMUM_SIZE_KEY, m_browsing_data_settings.disk_cache_settings.maximum_size);@@ -1111,9 +1113,9 @@ void Settings::remove_all_autoplay_site_filters()observer.autoplay_settings_changed();}-void Settings::set_geolocation_enabled(bool enabled)+void Settings::set_location_policy(LocationPolicy policy){- m_geolocation_enabled = enabled && Core::GeolocationProvider::is_available();+ m_location_policy = policy;persist_settings();for (auto& observer : m_observers)diff --git a/Libraries/LibWebView/Settings.h b/Libraries/LibWebView/Settings.hindex 0ac45597ffd..8fe950e6cb8 100644--- a/Libraries/LibWebView/Settings.h+++ b/Libraries/LibWebView/Settings.h@@ -87,6 +87,12 @@ struct AutoplaySiteSetting : public SiteSetting {Web::HTML::AutoplayPolicy policy { Web::HTML::AutoplayPolicy::BlockAudio };};+// Whether sites may ask for the user's location at all.+enum class LocationPolicy : u8 {+ Ask,+ Block,+};+struct BrowsingDataSettings {HTTP::DiskCacheSettings disk_cache_settings;};@@ -219,8 +225,8 @@ public:void remove_autoplay_site_filter(String const&);void remove_all_autoplay_site_filters();- bool geolocation_enabled() const { return m_geolocation_enabled; }- void set_geolocation_enabled(bool);+ LocationPolicy location_policy() const { return m_location_policy; }+ void set_location_policy(LocationPolicy);static BrowsingDataSettings parse_browsing_data_settings(JsonValue const&);BrowsingDataSettings const& browsing_data_settings() const { return m_browsing_data_settings; }@@ -295,7 +301,7 @@ private:Vector<SearchEngine> m_custom_search_engines;AutoplaySiteSetting m_autoplay;- bool m_geolocation_enabled { false };+ LocationPolicy m_location_policy { LocationPolicy::Ask };BrowsingDataSettings m_browsing_data_settings;GlobalPrivacyControl m_global_privacy_control { GlobalPrivacyControl::No };diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 7c36aa70823..9a1ecab0c5e 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -2960,7 +2960,7 @@ void ViewImplementation::initialize_tab(Web::HTML::VisibilityState system_visibireturn;}- if (!Application::settings().geolocation_enabled()) {+ if (!Application::the().sites_can_ask_for_location()) {if (auto provider_watch_id = view->m_geolocation_watch_ids.take(key); provider_watch_id.has_value())Application::the().stop_watching_geolocation_position(*provider_watch_id);request_page->async_geolocation_position_response(request_id, {}, to_underlying(GeolocationErrorCode::PermissionDenied));@@ -3000,7 +3000,7 @@ void ViewImplementation::initialize_tab(Web::HTML::VisibilityState system_visibi};on_request_geolocation_position = [this, geolocation_error_code, make_geolocation_success_handler, make_geolocation_error_handler](WebContentPage& requesting_page, u64 request_id) {- if (!Application::settings().geolocation_enabled()) {+ if (!Application::the().sites_can_ask_for_location()) {requesting_page.async_geolocation_position_response(request_id, {}, to_underlying(GeolocationErrorCode::PermissionDenied));return;}@@ -3026,7 +3026,7 @@ void ViewImplementation::initialize_tab(Web::HTML::VisibilityState system_visibi};on_start_geolocation_position_watch = [this, geolocation_error_code, make_geolocation_success_handler, make_geolocation_error_handler](WebContentPage& requesting_page, u64 request_id) {- if (!Application::settings().geolocation_enabled()) {+ if (!Application::the().sites_can_ask_for_location()) {requesting_page.async_geolocation_position_response(request_id, {}, to_underlying(GeolocationErrorCode::PermissionDenied));return;}@@ -4213,7 +4213,7 @@ void ViewImplementation::geolocation_settings_changed(){using ErrorCode = Web::Geolocation::GeolocationPositionErrorCode;- if (Application::web_content_options().is_test_mode != IsTestMode::Yes && !Application::settings().geolocation_enabled()) {+ if (Application::web_content_options().is_test_mode != IsTestMode::Yes && !Application::the().sites_can_ask_for_location()) {auto geolocation_position_request_ids = move(m_geolocation_position_request_ids);for (auto const& request : geolocation_position_request_ids) {Application::the().cancel_geolocation_position_request(request.value);@@ -4240,7 +4240,7 @@ void ViewImplementation::send_geolocation_emulated_position(WebContentPage& pageif (Application::web_content_options().is_test_mode == IsTestMode::Yes)page.async_set_geolocation_emulated_position({ 37.7647658, -122.4345892, 100.0, 0.0, 0.0, 0.0, 0.0 }, {});- else if (Application::settings().geolocation_enabled())+ else if (Application::the().sites_can_ask_for_location())page.async_set_geolocation_emulated_position({}, {});elsepage.async_set_geolocation_emulated_position({}, to_underlying(ErrorCode::PermissionDenied));diff --git a/Libraries/LibWebView/WebUI/SettingsUI.cpp b/Libraries/LibWebView/WebUI/SettingsUI.cppindex 2b20d1cd5fd..7351872f0e3 100644--- a/Libraries/LibWebView/WebUI/SettingsUI.cpp+++ b/Libraries/LibWebView/WebUI/SettingsUI.cpp@@ -143,8 +143,8 @@ void SettingsUI::register_interfaces()register_interface("removeAllSiteSettingFilters"sv, [this](auto const& data) {remove_all_site_setting_filters(data);});- register_interface("setGeolocationEnabled"sv, [this](auto const& data) {- set_geolocation_enabled(data);+ register_interface("setLocationPolicy"sv, [this](auto const& data) {+ set_location_policy(data);});register_interface("estimateBrowsingDataSizes"sv, [this](auto const& data) {@@ -517,12 +517,15 @@ void SettingsUI::remove_all_site_setting_filters(JsonValue const& site_setting)}}-void SettingsUI::set_geolocation_enabled(JsonValue const& enabled)+void SettingsUI::set_location_policy(JsonValue const& policy){- if (!enabled.is_bool())+ if (!policy.is_string())return;- Application::settings().set_geolocation_enabled(enabled.as_bool());+ if (policy.as_string() == "ask"sv)+ Application::settings().set_location_policy(LocationPolicy::Ask);+ else if (policy.as_string() == "block"sv)+ Application::settings().set_location_policy(LocationPolicy::Block);}void SettingsUI::estimate_browsing_data_sizes(JsonValue const& options)diff --git a/Libraries/LibWebView/WebUI/SettingsUI.h b/Libraries/LibWebView/WebUI/SettingsUI.hindex f8a84fbfb1b..124a9b73407 100644--- a/Libraries/LibWebView/WebUI/SettingsUI.h+++ b/Libraries/LibWebView/WebUI/SettingsUI.h@@ -65,7 +65,7 @@ private:void add_site_setting_filter(JsonValue const&);void remove_site_setting_filter(JsonValue const&);void remove_all_site_setting_filters(JsonValue const&);- void set_geolocation_enabled(JsonValue const&);+ void set_location_policy(JsonValue const&);void estimate_browsing_data_sizes(JsonValue const&);void set_browsing_data_settings(JsonValue const&);diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 64a27abb0c5..155841f7c00 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -84,6 +84,12 @@ if (BUILD_TESTING AND NOT WIN32))set_tests_properties(TestWebDriverContentBlockers PROPERTIES TIMEOUT 180)+ add_test(+ NAME TestWebDriverLocationPolicy+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-location-policy.py $<TARGET_FILE:WebDriver>+ )+ set_tests_properties(TestWebDriverLocationPolicy PROPERTIES TIMEOUT 120)+add_test(NAME TestWebDriverSearchEngineSettingsCOMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-search-engine-settings.py $<TARGET_FILE:WebDriver>diff --git a/Tests/LibWebView/test-webdriver-location-policy.py b/Tests/LibWebView/test-webdriver-location-policy.pynew file mode 100755index 00000000000..67efe6315fe--- /dev/null+++ b/Tests/LibWebView/test-webdriver-location-policy.py@@ -0,0 +1,118 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import argparse+import json+import runpy+import subprocess+import tempfile++from pathlib import Path++helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))+++def run_browser(webdriver_binary, settings, check):+ with tempfile.TemporaryDirectory() as directory:+ config = Path(directory) / "config"+ config.mkdir()+ settings_file = config / "Settings.json"+ settings_file.write_text(json.dumps(settings))+ port = helpers["unused_port"]()+ process = subprocess.Popen(+ [webdriver_binary, "--headless", "-l", "127.0.0.1", "-p", str(port), "--profile-path", directory]+ )+ session = None+ try:+ helpers["wait_for_port"](port)+ session = helpers["create_session"](port)++ def command(path, body=None, method="POST"):+ status, payload, raw = helpers["request"](port, method, f"/session/{session}/{path}", body)+ assert status == 200, raw+ return payload["value"]++ def switch_state():+ command("url", {"url": "about:settings"})+ return command(+ "execute/async",+ {+ "script": """+ const done = arguments[0];+ const toggle = document.querySelector('#enable-geolocation');+ document.addEventListener('WebUIMessage', function listener(event) {+ if (event.detail.name !== 'loadSettings') return;+ document.removeEventListener('WebUIMessage', listener);+ setTimeout(() => done([toggle.checked, toggle.disabled]));+ });+ // The page may have loaded its settings already, so ask for them again.+ if (window.ladybird) ladybird.sendMessage('loadCurrentSettings');+ """,+ "args": [],+ },+ )++ def toggle_switch():+ command(+ "execute/async",+ {+ "script": """+ const done = arguments[0];+ document.addEventListener('WebUIMessage', function listener(event) {+ if (event.detail.name !== 'loadSettings') return;+ document.removeEventListener('WebUIMessage', listener);+ done();+ });+ document.querySelector('#enable-geolocation').click();+ """,+ "args": [],+ },+ )++ check(switch_state, toggle_switch, settings_file)+ finally:+ if session is not None:+ helpers["request"](port, "DELETE", f"/session/{session}")+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+++def run_test(webdriver_binary):+ # A profile saved before the location policy existed carries a geolocationEnabled of false that the user never+ # chose, since every save wrote it. Such a profile lets sites ask.+ def check_migrated_profile(switch_state, toggle_switch, settings_file):+ checked, disabled = switch_state()+ assert checked, "a profile with only the old geolocationEnabled key should let sites ask"+ if disabled:+ print("NOTE: no geolocation provider here, so the switch can't be toggled")+ return+ toggle_switch()+ saved = json.loads(settings_file.read_text())+ assert saved.get("locationPolicy") == "block", saved+ assert "geolocationEnabled" not in saved, saved+ toggle_switch()+ saved = json.loads(settings_file.read_text())+ assert saved.get("locationPolicy") == "ask", saved++ run_browser(webdriver_binary, {"geolocationEnabled": False}, check_migrated_profile)++ def check_blocking_profile(switch_state, toggle_switch, settings_file):+ checked, _ = switch_state()+ assert not checked, "a profile whose location policy is block should keep sites from asking"++ run_browser(webdriver_binary, {"locationPolicy": "block"}, check_blocking_profile)+ print("PASS: the location policy defaults to letting sites ask, and a saved block stays")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("webdriver_binary")+ args = parser.parse_args()+ run_test(args.webdriver_binary)