Skip to content

Truly independent web browser

LibWeb+LibWebView: Ask the UI process for permission, and let it decide

sideshowbarkerf905b0e5c191
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index f8fe1252fb6..8f3e1a1afb5 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -108,6 +108,8 @@
#include <LibWeb/Painting/HitTestResult.h>
#include <LibWeb/Painting/PaintingRustBridge.h>
#include <LibWeb/Painting/Scrolling.h>
+#include <LibWeb/PermissionsAPI/PermissionStore.h>
+#include <LibWeb/PermissionsAPI/Permissions.h>
#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/ResizeObserver/ResizeObserver.h>
#include <LibWeb/Streams/ReadableStream.h>
@@ -2103,6 +2105,55 @@ void Internals::set_geolocation_emulated_position(double latitude, double longit
});
}
+GC::Ref<WebIDL::Promise> Internals::request_permission(Utf16String const& name)
+{
+ auto& realm = window().principal_realm();
+ auto promise = WebIDL::create_promise_for(window());
+ auto& settings = window().associated_document().relevant_settings_object();
+ PermissionsAPI::request_permission_with_user_prompt({ name }, settings, GC::create_function(realm.heap(), [&realm, promise](PermissionsAPI::PermissionState state) {
+ HTML::TemporaryExecutionContext execution_context { realm };
+ WebIDL::resolve_promise(realm, promise, JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(state)));
+ }));
+ return promise;
+}
+
+// The UI process answers with the snapshot that holds the change; resolving in a task on the permissions task source lets
+// whatever the change queued run first.
+static GC::Ref<WebIDL::Promise> apply_snapshot_then_resolve(HTML::Window& window, Optional<Web::Permissions::PermissionSnapshot> snapshot)
+{
+ auto promise = WebIDL::create_promise_for(window);
+ if (snapshot.has_value())
+ PermissionsAPI::PermissionStore::the().apply_snapshot(snapshot.release_value());
+ HTML::queue_global_task(HTML::Task::Source::Permissions, window.associated_document().relevant_settings_object().global_object(), GC::create_function(window.heap(), [&window, promise] {
+ auto& realm = window.principal_realm();
+ HTML::TemporaryExecutionContext execution_context { realm };
+ WebIDL::resolve_promise(realm, promise);
+ }));
+ return promise;
+}
+
+GC::Ref<WebIDL::Promise> Internals::set_permission(Utf16String const& name, Utf16String const& state)
+{
+ auto snapshot = page().client().page_did_set_permission_for_testing(window().associated_document().id(), name.to_utf8(), state.to_utf8());
+ return apply_snapshot_then_resolve(window(), move(snapshot));
+}
+
+void Internals::set_next_permission_prompt_outcome(Utf16String const& name, Utf16String const& outcome, bool held)
+{
+ page().client().page_did_set_next_permission_prompt_outcome_for_testing(name.to_utf8(), outcome.to_utf8(), held);
+}
+
+void Internals::release_held_permission_prompt(WebIDL::UnsignedLong waiters)
+{
+ page().client().page_did_release_held_permission_prompt_for_testing(waiters);
+}
+
+GC::Ref<WebIDL::Promise> Internals::advance_permission_clock(WebIDL::UnsignedLongLong milliseconds)
+{
+ auto snapshot = page().client().page_did_advance_permission_clock_for_testing(milliseconds);
+ return apply_snapshot_then_resolve(window(), move(snapshot));
+}
+
bool Internals::html_parser_body_is_exhausted(DOM::Document& document)
{
auto parser = document.parser();
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 6a20da232ec..f72a9b283fc 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -256,6 +256,12 @@ public:
void set_environments_top_level_url(Utf16String const& url);
void set_geolocation_emulated_position(double latitude, double longitude, double accuracy);
+ GC::Ref<WebIDL::Promise> request_permission(Utf16String const& name);
+ GC::Ref<WebIDL::Promise> set_permission(Utf16String const& name, Utf16String const& state);
+ void set_next_permission_prompt_outcome(Utf16String const& name, Utf16String const& outcome, bool held);
+ void release_held_permission_prompt(WebIDL::UnsignedLong waiters);
+ GC::Ref<WebIDL::Promise> advance_permission_clock(WebIDL::UnsignedLongLong milliseconds);
+
u64 parser_non_append_insertions();
DOM::Document::StyleInvalidationCounters const& style_invalidation_counters() const;
GC::Ref<JS::Object> style_invalidation_counters_object() const;
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index a6fe6846c08..1f1b1b1fb0d 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -258,6 +258,12 @@ interface Internals {
undefined setEnvironmentsTopLevelURL(USVString url);
undefined setGeolocationEmulatedPosition(double latitude, double longitude, optional double accuracy = 100);
+ Promise<DOMString> requestPermission(DOMString name);
+ Promise<undefined> setPermission(DOMString name, DOMString state);
+ undefined setNextPermissionPromptOutcome(DOMString name, DOMString outcome, optional boolean held = false);
+ undefined releaseHeldPermissionPrompt(optional unsigned long waiters = 1);
+ Promise<undefined> advancePermissionClock(unsigned long long milliseconds);
+
InternalGamepad connectVirtualGamepad();
undefined setHighlightedNode(Node? node);
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index 2b2779df35a..5d8a6457804 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -1511,17 +1511,17 @@ void Page::unregister_emulated_position_data_observer(u64 observer_id)
m_emulated_position_data_observers.remove(observer_id);
}
-void Page::request_permission(Utf16String const& name, PermissionPromptCallback callback)
+void Page::request_permission(HTML::CrossProcessId requesting_document_id, Utf16String const& name, PermissionPromptCallback callback)
{
auto request_id = m_next_permission_request_id++;
m_pending_permission_requests.set(request_id, callback);
- client().page_did_request_permission(request_id, name);
+ client().page_did_request_permission(request_id, requesting_document_id, name);
}
-void Page::permission_request_completed(u64 request_id, bool granted)
+void Page::permission_request_completed(u64 request_id, Web::Permissions::EffectiveState state)
{
if (auto callback = m_pending_permission_requests.take(request_id); callback.has_value())
- callback.value()->function()(granted);
+ callback.value()->function()(state);
}
u64 Page::request_geolocation_position(GeolocationPositionCallback callback, GeolocationRequestType type)
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index a34dbe056d2..6b08e1cc353 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -97,6 +97,7 @@
#include <LibWebCommon/Page/TextEditingCommand.h>
#include <LibWebCommon/Page/ViewportIsFullscreen.h>
#include <LibWebCommon/Page/WritingSuggestion.h>
+#include <LibWebCommon/Permissions/Permissions.h>
#include <LibWebCommon/PixelUnits.h>
#include <LibWebCommon/StorageAPI/StorageEndpoint.h>
#include <LibWebCommon/UIEvents/KeyCode.h>
@@ -348,9 +349,9 @@ public:
void receive_geolocation_position(u64 request_id, GeolocationPositionResult);
// The browser-process bridge for the Permissions spec's "ask the user for express permission" step.
- using PermissionPromptCallback = GC::Ref<GC::Function<void(bool granted)>>;
- void request_permission(Utf16String const& name, PermissionPromptCallback);
- void permission_request_completed(u64 request_id, bool granted);
+ using PermissionPromptCallback = GC::Ref<GC::Function<void(Web::Permissions::EffectiveState)>>;
+ void request_permission(HTML::CrossProcessId requesting_document_id, Utf16String const& name, PermissionPromptCallback);
+ void permission_request_completed(u64 request_id, Web::Permissions::EffectiveState);
// https://w3c.github.io/geolocation/#dfn-emulated-position-data
// NB: The top-level traversable's, which the UI process tells every page representing it.
@@ -877,7 +878,11 @@ public:
virtual void page_did_cancel_geolocation_position_request([[maybe_unused]] u64 request_id) { }
virtual void page_did_start_geolocation_position_watch([[maybe_unused]] u64 request_id) { }
virtual void page_did_stop_geolocation_position_watch([[maybe_unused]] u64 request_id) { }
- virtual void page_did_request_permission([[maybe_unused]] u64 request_id, [[maybe_unused]] Utf16String const& name) { }
+ virtual void page_did_request_permission([[maybe_unused]] u64 request_id, [[maybe_unused]] HTML::CrossProcessId requesting_document_id, [[maybe_unused]] Utf16String const& name) { }
+ virtual Optional<Web::Permissions::PermissionSnapshot> page_did_set_permission_for_testing([[maybe_unused]] HTML::CrossProcessId document_id, [[maybe_unused]] String const& name, [[maybe_unused]] String const& state) { return {}; }
+ virtual void page_did_set_next_permission_prompt_outcome_for_testing([[maybe_unused]] String const& name, [[maybe_unused]] String const& outcome, [[maybe_unused]] bool held) { }
+ virtual void page_did_release_held_permission_prompt_for_testing([[maybe_unused]] u32 waiters) { }
+ virtual Optional<Web::Permissions::PermissionSnapshot> page_did_advance_permission_clock_for_testing([[maybe_unused]] u64 milliseconds) { return {}; }
virtual void page_did_finish_test([[maybe_unused]] Utf16String const& text) { }
virtual void page_did_set_test_timeout([[maybe_unused]] double milliseconds) { }
diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp
index 4e35850457e..1dbf7514a14 100644
--- a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp
+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp
@@ -120,35 +120,36 @@ void request_permission_with_user_prompt(PermissionDescriptor const& descriptor,
return;
}
- auto settle = GC::create_function(GC::Heap::the(), [descriptor, settings = GC::Ref(settings), on_decided](bool granted) {
+ // 3. Ask the user for express permission for the calling algorithm to use the powerful feature described by descriptor.
+ // NB: Only windows have a page to ask through; a worker's request is denied.
+ auto* window = HTML::window_from_global_object(settings.global_object());
+ if (!window) {
+ on_decided->function()(PermissionState::Denied);
+ return;
+ }
+
+ auto settle = GC::create_function(GC::Heap::the(), [descriptor, settings = GC::Ref(settings), on_decided](Web::Permissions::EffectiveState answer) {
// 4. If the user gives express permission to use the powerful feature, set current state to "granted"; otherwise to "denied".
- auto current_state = granted ? PermissionState::Granted : PermissionState::Denied;
+ // The user's interaction may provide new information about the user's intent for the origin.
+ // AD-HOC: A prompt the user dismisses or ignores leaves the permission at "prompt", rather than storing "denied";
+ // only the calling algorithm sees "denied" then, so the site may ask again.
+ auto current_state = answer == Web::Permissions::EffectiveState::Granted ? PermissionState::Granted : PermissionState::Denied;
// 5. Let settings be the current settings object.
// NB: The user's answer arrives outside any script, so the requester's settings object was captured instead.
// 6. Let key be the result of generating a permission key for descriptor with settings's top-level origin and settings's origin.
// 7. Queue a task on the current settings object's responsible event loop to set a permission store entry with descriptor, key, and current state.
- // NB: store_permission_decision() carries out steps 6 and 7 for both request algorithms.
- store_permission_decision(descriptor, settings, current_state);
+ // NB: The UI process stores the user's answer, and sends the snapshot that reflects it ahead of the answer itself.
+ // It can't key an answer for an opaque top-level origin (a file: page's), so that answer is kept here, for
+ // as long as the origin lives.
+ if (settings->top_level_origin->is_opaque() && answer != Web::Permissions::EffectiveState::Prompt)
+ store_permission_decision(descriptor, settings, current_state);
// 8. Return current state.
on_decided->function()(current_state);
});
- // Tests have no user to ask, so they are granted as the synchronous path grants them.
- if (HTML::Window::in_test_mode()) {
- settle->function()(true);
- return;
- }
-
- // 3. Ask the user for express permission for the calling algorithm to use the powerful feature described by descriptor.
- // Only windows have a page to ask through; a worker's request is denied.
- auto* window = HTML::window_from_global_object(settings.global_object());
- if (!window) {
- settle->function()(false);
- return;
- }
- window->page().request_permission(descriptor.name, settle);
+ window->page().request_permission(window->associated_document().id(), descriptor.name, settle);
}
// https://w3c.github.io/permissions/#dfn-permission-state
diff --git a/Libraries/LibWebView/PermissionManager.cpp b/Libraries/LibWebView/PermissionManager.cpp
index 7b8a64c663a..220afe70e53 100644
--- a/Libraries/LibWebView/PermissionManager.cpp
+++ b/Libraries/LibWebView/PermissionManager.cpp
@@ -453,10 +453,18 @@ void PermissionManager::unregister_observer(PermissionManagerObserver& observer)
m_observers.remove_first_matching([&](auto* candidate) { return candidate == &observer; });
}
-void PermissionManager::clear_for_testing()
+void PermissionManager::age_origin_for_testing(URL::Origin const& origin, AK::Duration duration)
{
- m_entries.clear();
- did_change();
+ for (auto& entry : m_entries) {
+ if (!entry.origin.is_same_origin(origin))
+ continue;
+ entry.decided_at -= duration;
+ if (entry.hidden_since.has_value())
+ *entry.hidden_since -= duration;
+ if (entry.embargo_until.has_value())
+ *entry.embargo_until -= duration;
+ }
+ run_expiry();
}
void PermissionManager::set_clock_for_testing(Function<UnixDateTime()> clock)
diff --git a/Libraries/LibWebView/PermissionManager.h b/Libraries/LibWebView/PermissionManager.h
index b2e889653ce..7074cdaac6a 100644
--- a/Libraries/LibWebView/PermissionManager.h
+++ b/Libraries/LibWebView/PermissionManager.h
@@ -97,7 +97,8 @@ public:
void register_observer(PermissionManagerObserver&);
void unregister_observer(PermissionManagerObserver&);
- void clear_for_testing();
+ // Makes the given time pass for one origin's entries only, so concurrently running tests don't disturb each other.
+ void age_origin_for_testing(URL::Origin const&, AK::Duration);
void set_clock_for_testing(Function<UnixDateTime()>);
void set_timeouts_for_testing(PermissionTimeouts);
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 9a1ecab0c5e..67ac0875b5b 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -200,6 +200,108 @@ void ViewImplementation::did_update_url()
update_displayed_url();
}
+void ViewImplementation::request_permission_prompt(PermissionPromptRequest request, PermissionPromptCallback on_outcome)
+{
+ for (auto& pending : m_pending_permission_prompts) {
+ if (pending.request.is_same_request_as(request)) {
+ pending.waiters.append(move(on_outcome));
+ release_held_permission_prompt_if_ready_for_testing();
+ return;
+ }
+ }
+
+ Vector<PermissionPromptCallback> waiters;
+ waiters.append(move(on_outcome));
+ m_pending_permission_prompts.append({ request, move(waiters) });
+
+ // Tests have no user to ask: They get the answer a test set up, and "Allow while visiting the site" otherwise.
+ if (Application::web_content_options().is_test_mode == IsTestMode::Yes) {
+ auto outcome = Web::Permissions::PromptOutcome::AllowAlways;
+ if (auto next = m_next_permission_prompt_outcomes_for_testing.take(request.name); next.has_value()) {
+ if (next->held) {
+ m_held_permission_prompt_for_testing = request;
+ m_held_permission_prompt_outcome_for_testing = next->outcome;
+ release_held_permission_prompt_if_ready_for_testing();
+ return;
+ }
+ outcome = next->outcome;
+ }
+ settle_permission_prompt(request, outcome);
+ return;
+ }
+
+ if (!on_request_permission) {
+ settle_permission_prompt(request, Web::Permissions::PromptOutcome::Cancelled);
+ return;
+ }
+
+ on_request_permission(request, [weak_this = make_weak_ptr(), request](Web::Permissions::PromptOutcome outcome) {
+ if (auto* view = weak_this.ptr())
+ view->settle_permission_prompt(request, outcome);
+ });
+}
+
+void ViewImplementation::settle_permission_prompt(PermissionPromptRequest const& request, Web::Permissions::PromptOutcome outcome)
+{
+ auto index = m_pending_permission_prompts.find_first_index_if([&](auto const& pending) { return pending.request.is_same_request_as(request); });
+ if (!index.has_value())
+ return;
+
+ auto pending = m_pending_permission_prompts.take(*index);
+ for (auto& waiter : pending.waiters)
+ waiter(outcome);
+}
+
+void ViewImplementation::ignore_pending_permission_prompts()
+{
+ auto pending_prompts = move(m_pending_permission_prompts);
+ m_held_permission_prompt_for_testing.clear();
+ for (auto& pending : pending_prompts) {
+ if (on_cancel_permission_prompt)
+ on_cancel_permission_prompt(pending.request);
+ for (auto& waiter : pending.waiters)
+ waiter(Web::Permissions::PromptOutcome::Ignored);
+ }
+}
+
+void ViewImplementation::set_next_permission_prompt_outcome_for_testing(Web::Permissions::PermissionName name, Web::Permissions::PromptOutcome outcome, bool held)
+{
+ m_next_permission_prompt_outcomes_for_testing.set(name, { outcome, held });
+}
+
+void ViewImplementation::reset_permission_prompts_for_testing()
+{
+ m_next_permission_prompt_outcomes_for_testing.clear();
+ m_held_permission_prompt_for_testing.clear();
+ m_held_permission_prompt_release_waiters_for_testing.clear();
+ auto pending_prompts = move(m_pending_permission_prompts);
+ for (auto& pending : pending_prompts) {
+ for (auto& waiter : pending.waiters)
+ waiter(Web::Permissions::PromptOutcome::Cancelled);
+ }
+}
+
+void ViewImplementation::release_held_permission_prompt_for_testing(u32 waiters)
+{
+ m_held_permission_prompt_release_waiters_for_testing = waiters;
+ release_held_permission_prompt_if_ready_for_testing();
+}
+
+void ViewImplementation::release_held_permission_prompt_if_ready_for_testing()
+{
+ if (!m_held_permission_prompt_for_testing.has_value() || !m_held_permission_prompt_release_waiters_for_testing.has_value())
+ return;
+
+ auto const& request = *m_held_permission_prompt_for_testing;
+ auto pending = m_pending_permission_prompts.find_if([&](auto const& candidate) { return candidate.request.is_same_request_as(request); });
+ if (pending == m_pending_permission_prompts.end() || pending->waiters.size() < *m_held_permission_prompt_release_waiters_for_testing)
+ return;
+
+ m_held_permission_prompt_release_waiters_for_testing.clear();
+ auto held_request = m_held_permission_prompt_for_testing.release_value();
+ settle_permission_prompt(held_request, m_held_permission_prompt_outcome_for_testing);
+}
+
Optional<URL::URL const&> ViewImplementation::browser_ui_load_url() const
{
if (!m_browser_ui_load.has_value() || !m_top_level_traversable)
@@ -217,6 +319,8 @@ void ViewImplementation::did_change_ongoing_navigation(Badge<CanonicalNavigable>
void ViewImplementation::did_change_active_document(Badge<CanonicalTraversable>)
{
+ // A prompt the document that asked has left behind goes unanswered: the user ignored it.
+ ignore_pending_permission_prompts();
set_title(Utf16String::from_utf8(url().serialize()));
set_favicon({});
did_update_url();
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index cd96a5b83db..f00048fce6e 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -59,6 +59,7 @@
#include <LibWebCommon/Page/QueuedInputEvent.h>
#include <LibWebCommon/Page/ScreenWakeLockState.h>
#include <LibWebCommon/Page/ViewportIsFullscreen.h>
+#include <LibWebCommon/Permissions/Permissions.h>
#include <LibWebCommon/WebDriver/Response.h>
#include <LibWebCommon/WebDriver/SessionBrowsingContext.h>
#include <LibWebCommon/WebView/DOMNodeProperties.h>
@@ -93,6 +94,22 @@ struct GeolocationRequestKey {
bool operator==(GeolocationRequestKey const&) const = default;
};
+// What the UI shows the user when a site asks for a permission. The origin is the top-level one the decision is kept
+// for; a file: page has none worth showing, so the prompt names it as a file instead.
+struct PermissionPromptRequest {
+ Web::Permissions::PermissionName name;
+ URL::Origin top_level_origin;
+ bool is_file { false };
+ bool show_os_hint { false };
+
+ bool is_same_request_as(PermissionPromptRequest const& other) const
+ {
+ return name == other.name && is_file == other.is_file && top_level_origin.is_same_origin(other.top_level_origin);
+ }
+};
+
+using PermissionPromptCallback = Function<void(Web::Permissions::PromptOutcome)>;
+
class WEBVIEW_API ViewImplementation
: public SettingsObserver
, public BookmarkStoreObserver
@@ -110,6 +127,13 @@ public:
IsPrivate is_private() const { return m_is_private; }
BrowsingSession& session() const { return *m_session; }
+ // Asks the user, unless an identical prompt is already up, in which case its answer goes to every request for it.
+ void request_permission_prompt(PermissionPromptRequest, PermissionPromptCallback);
+ void set_next_permission_prompt_outcome_for_testing(Web::Permissions::PermissionName, Web::Permissions::PromptOutcome, bool held);
+ // Answers the held prompt once this many requests wait on it, since the requests arrive over another connection.
+ void release_held_permission_prompt_for_testing(u32 waiters);
+ void reset_permission_prompts_for_testing();
+
u64 view_id() const { return m_view_id; }
pid_t web_content_pid() const;
@@ -574,7 +598,8 @@ public:
Function<void(WebContentPage& requesting_page, u64 request_id)> on_cancel_geolocation_position_request;
Function<void(WebContentPage& requesting_page, u64 request_id)> on_start_geolocation_position_watch;
Function<void(WebContentPage& requesting_page, u64 request_id)> on_stop_geolocation_position_watch;
- Function<void(Utf16String const& name, URL::Origin const&, Function<void(bool granted)> on_decided)> on_request_permission;
+ Function<void(PermissionPromptRequest const&, PermissionPromptCallback)> on_request_permission;
+ Function<void(PermissionPromptRequest const&)> on_cancel_permission_prompt;
Function<void(Web::HTML::FileFilter const& accepted_file_types, Web::HTML::AllowMultipleFiles)> on_request_file_picker;
Function<void(Gfx::IntPoint content_position, i32 minimum_width, Vector<Web::HTML::SelectItem> items)> on_request_select_dropdown;
Function<void(Web::KeyEvent const&)> on_finish_handling_key_event;
@@ -661,6 +686,8 @@ protected:
void set_owner_view(ViewImplementation const& owner_view) { m_owner_view_id = owner_view.view_id(); }
void did_update_url();
+ void settle_permission_prompt(PermissionPromptRequest const&, Web::Permissions::PromptOutcome);
+ void ignore_pending_permission_prompts();
void set_title(Utf16String);
void set_favicon(Optional<Gfx::Bitmap const&>);
Optional<URL::URL const&> browser_ui_load_url() const;
@@ -1099,6 +1126,22 @@ protected:
HashMap<GeolocationRequestKey, Core::GeolocationProvider::RequestId> m_geolocation_position_request_ids;
HashMap<GeolocationRequestKey, Core::GeolocationProvider::WatchId> m_geolocation_watch_ids;
+ struct PendingPermissionPrompt {
+ PermissionPromptRequest request;
+ Vector<PermissionPromptCallback> waiters;
+ };
+ Vector<PendingPermissionPrompt> m_pending_permission_prompts;
+
+ struct PermissionPromptOutcomeForTesting {
+ Web::Permissions::PromptOutcome outcome;
+ bool held { false };
+ };
+ HashMap<Web::Permissions::PermissionName, PermissionPromptOutcomeForTesting> m_next_permission_prompt_outcomes_for_testing;
+ Optional<PermissionPromptRequest> m_held_permission_prompt_for_testing;
+ Web::Permissions::PromptOutcome m_held_permission_prompt_outcome_for_testing { Web::Permissions::PromptOutcome::Cancelled };
+ Optional<u32> m_held_permission_prompt_release_waiters_for_testing;
+ void release_held_permission_prompt_if_ready_for_testing();
+
Core::AnonymousBuffer m_document_cookie_version_buffer;
HashMap<String, Core::SharedVersionIndex> m_document_cookie_version_indices;
DevTools::DevToolsDelegate::OnHostCookieChange m_on_host_cookie_change;
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 067a50b35f9..93fa47e1ff0 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -38,6 +38,7 @@
#include <LibWebView/HelperProcess.h>
#include <LibWebView/HistoryStore.h>
#include <LibWebView/NavigationLoader.h>
+#include <LibWebView/PermissionManager.h>
#include <LibWebView/PictureInPictureManager.h>
#include <LibWebView/RequestServerManager.h>
#include <LibWebView/ViewImplementation.h>
@@ -941,7 +942,7 @@ String WebContentClient::audio_capture_permission_key(URL::URL const& url)
return url.serialize(URL::ExcludeFragment::Yes);
}
-ErrorOr<void> WebContentClient::grant_audio_capture(URL::URL const& url)
+ErrorOr<void> WebContentClient::grant_audio_capture_to_file(URL::URL const& url)
{
m_audio_capture_grants.set(audio_capture_permission_key(url));
m_audio_capture_permitted = audio_capture_permitted();
@@ -963,13 +964,22 @@ void WebContentClient::update_audio_capture_permission()
warnln("Unable to update the AudioServer's capture permission: {}", result.error());
}
+bool WebContentClient::page_may_capture_audio(WebContentPage const& page) const
+{
+ auto const& url = page.view().url();
+ auto origin = url.origin();
+ if (origin.is_opaque())
+ return m_audio_capture_grants.contains(audio_capture_permission_key(url));
+ return session().permission_manager->effective_state(Web::Permissions::PermissionName::Microphone, origin) == Web::Permissions::EffectiveState::Granted;
+}
+
bool WebContentClient::audio_capture_permitted() const
{
// A tab's grant reaches only the documents whose permissions policy allows them the microphone. The process may
// capture if it hosts one, as it can act for any document it hosts.
for (auto const& it : m_pages) {
auto const& page = it.value;
- if (!page->is_open() || !m_audio_capture_grants.contains(audio_capture_permission_key(page->view().url())))
+ if (!page->is_open() || !page_may_capture_audio(*page))
continue;
if (page->hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature::Microphone))
return true;
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index 701b1e2bafe..1ea81c032fd 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -160,7 +160,8 @@ public:
ErrorOr<void> recreate_compositor_contexts(Badge<Application>);
// The user let the page at the URL capture audio. The process's AudioServer hears of the permission before this
// returns, so a page told afterwards finds it in place.
- ErrorOr<void> grant_audio_capture(URL::URL const&);
+ // A file: page's microphone grant, which has no origin to be kept for; every other site's is the PermissionManager's.
+ ErrorOr<void> grant_audio_capture_to_file(URL::URL const&);
// The permission follows the origins the process's open pages show, so it goes with a navigation away.
void update_audio_capture_permission();
// The process's AudioServer plays the page's sound while the page is authorized. It hears of an authorization
@@ -261,6 +262,7 @@ private:
void did_change_audio_playback_audibility(Audio::PlaybackGroupId, Audio::Audibility);
static String audio_capture_permission_key(URL::URL const&);
bool audio_capture_permitted() const;
+ bool page_may_capture_audio(WebContentPage const&) const;
void decide_audio_capture_request(u64 request_id);
// The controller connections to the MediaServer and AudioServer spawned for this process, from its first media use
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index ce99a556019..3162d75abf8 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -14,6 +14,7 @@
#include <LibWebCommon/Geolocation/GeolocationPositionErrorCode.h>
#include <LibWebCommon/HTML/BrowsingContext.h>
#include <LibWebCommon/Page/InputEvent.h>
+#include <LibWebCommon/SecureContexts/AbstractOperations.h>
#include <LibWebCommon/WebDriver/Error.h>
#include <LibWebCommon/WebView/SiteIsolation.h>
#include <LibWebView/Application.h>
@@ -28,6 +29,7 @@
#include <LibWebView/CookieJar.h>
#include <LibWebView/HistoryStore.h>
#include <LibWebView/NavigationLoader.h>
+#include <LibWebView/PermissionManager.h>
#include <LibWebView/PictureInPictureManager.h>
#include <LibWebView/RequestServerManager.h>
#include <LibWebView/StorageAreaRegistry.h>
@@ -1621,33 +1623,177 @@ void WebContentPage::did_request_geolocation_position(u64 request_id)
view().on_request_geolocation_position(*this, request_id);
}
-void WebContentPage::did_request_permission(u64 request_id, Utf16String name)
+static Optional<Web::Permissions::PermissionName> permission_name_from(Utf16String const& name)
{
- if (name != "microphone"_utf16) {
+ if (name == "geolocation"_utf16)
+ return Web::Permissions::PermissionName::Geolocation;
+ if (name == "microphone"_utf16)
+ return Web::Permissions::PermissionName::Microphone;
+ return {};
+}
+
+static Web::PermissionsPolicy::PolicyControlledFeature policy_controlled_feature_for(Web::Permissions::PermissionName name)
+{
+ switch (name) {
+ case Web::Permissions::PermissionName::Geolocation:
+ return Web::PermissionsPolicy::PolicyControlledFeature::Geolocation;
+ case Web::Permissions::PermissionName::Microphone:
+ return Web::PermissionsPolicy::PolicyControlledFeature::Microphone;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+RefPtr<CanonicalDocument> WebContentPage::hosted_document_with_id(Web::HTML::CrossProcessId document_id) const
+{
+ RefPtr<CanonicalDocument> found;
+ traversable().for_each_in_inclusive_subtree([&](CanonicalNavigable const& navigable) {
+ auto document = navigable.document_with_id(document_id);
+ if (!document || document->host() != this)
+ return IterationDecision::Continue;
+ found = move(document);
+ return IterationDecision::Break;
+ });
+ return found;
+}
+
+void WebContentPage::did_request_permission(u64 request_id, Web::HTML::CrossProcessId document_id, Utf16String name)
+{
+ auto permission_name = permission_name_from(name);
+ if (!permission_name.has_value()) {
client().did_misbehave("did_request_permission"sv, "unknown permission name"sv);
return;
}
- if (!view().on_request_permission) {
- async_permission_request_completed(request_id, false);
+ auto deny = [&] { async_permission_request_completed(request_id, Web::Permissions::EffectiveState::Denied); };
+
+ // The UI process decides from what it knows of the requesting document, never from what the renderer says of it.
+ auto document = hosted_document_with_id(document_id);
+ if (!document) {
+ deny();
return;
}
+ auto top_level_origin = document->top_level_origin();
+ if (!top_level_origin.has_value()) {
+ deny();
+ return;
+ }
+
+ auto policy = Web::PermissionsPolicy::check_permissions_policy(document->permissions_policy(), policy_controlled_feature_for(*permission_name), document->origin(), document->origin());
+ if (policy != Web::PermissionsPolicy::FeatureValue::Enabled) {
+ deny();
+ return;
+ }
+
+ // A file: page has an opaque origin, and it's the only one that gets to ask. Its answer lasts as long as the page.
+ auto is_file = top_level_origin->is_opaque() && view().url().scheme() == "file"sv;
+ if (!is_file) {
+ auto is_trustworthy = [](URL::Origin const& origin) {
+ return Web::SecureContexts::is_origin_potentially_trustworthy(origin) == Web::SecureContexts::Trustworthiness::PotentiallyTrustworthy;
+ };
+ if (!is_trustworthy(*top_level_origin) || !is_trustworthy(document->origin())) {
+ deny();
+ return;
+ }
+ }
+
+ auto& manager = *view().session().permission_manager;
+ if (!is_file) {
+ if (auto state = manager.effective_state(*permission_name, *top_level_origin); state != Web::Permissions::EffectiveState::Prompt) {
+ async_permission_request_completed(request_id, state);
+ return;
+ }
+ }
+
+ auto generation_when_asked = manager.decision_generation(*permission_name, *top_level_origin);
+ PermissionPromptRequest request { *permission_name, *top_level_origin, is_file };
- auto url = view().url();
- view().on_request_permission(name, url.origin(), [page = NonnullRefPtr(*this), request_id, name, url](bool granted) {
+ view().request_permission_prompt(move(request), [page = NonnullRefPtr(*this), request_id, document_id, permission_name = *permission_name, top_level_origin = *top_level_origin, is_file, generation_when_asked](Web::Permissions::PromptOutcome outcome) {
if (!page->is_open())
return;
- // The AudioServer hears of the permission before the page does, so the page's first request finds it in place.
- if (granted && name == "microphone"_utf16) {
- if (auto result = page->client().grant_audio_capture(url); result.is_error()) {
- warnln("Unable to grant audio capture: {}", result.error());
- granted = false;
+
+ auto state = Web::Permissions::EffectiveState::Prompt;
+ if (is_file) {
+ if (outcome == Web::Permissions::PromptOutcome::AllowAlways || outcome == Web::Permissions::PromptOutcome::AllowOnce)
+ state = Web::Permissions::EffectiveState::Granted;
+ else if (outcome == Web::Permissions::PromptOutcome::Block)
+ state = Web::Permissions::EffectiveState::Denied;
+ if (state == Web::Permissions::EffectiveState::Granted && permission_name == Web::Permissions::PermissionName::Microphone) {
+ if (auto result = page->client().grant_audio_capture_to_file(page->view().url()); result.is_error())
+ warnln("Unable to grant audio capture: {}", result.error());
}
+ } else {
+ auto& manager = *page->view().session().permission_manager;
+
+ // The answer counts only if nothing was decided for the site while the prompt was up: A decision made
+ // elsewhere (in the site-info panel, e.g.) wins, and a document that's gone takes its prompt with it. And
+ // requests that shared one prompt record its answer once, as the first of them records it.
+ auto still_relevant = page->hosted_document_with_id(document_id) && manager.decision_generation(permission_name, top_level_origin) == generation_when_asked;
+ if (still_relevant)
+ manager.record_prompt_outcome(permission_name, top_level_origin, outcome);
+ state = manager.effective_state(permission_name, top_level_origin);
}
- page->async_permission_request_completed(request_id, granted);
+
+ // The AudioServer hears of the permission before the page does, so the page's first request finds it in place.
+ if (permission_name == Web::Permissions::PermissionName::Microphone)
+ page->client().update_audio_capture_permission();
+
+ page->async_permission_request_completed(request_id, state);
});
}
+Web::Permissions::PermissionSnapshot WebContentPage::set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state)
+{
+ auto& manager = *view().session().permission_manager;
+ auto permission_name = Web::Permissions::permission_name_from_string(name);
+ auto document = hosted_document_with_id(document_id);
+ auto top_level_origin = document ? document->top_level_origin() : Optional<URL::Origin> {};
+
+ if (permission_name.has_value() && top_level_origin.has_value()) {
+ if (state == "granted"sv)
+ manager.set_decision(*permission_name, *top_level_origin, PermissionDecision::Allow);
+ else if (state == "denied"sv)
+ manager.set_decision(*permission_name, *top_level_origin, PermissionDecision::Block);
+ else if (state == "prompt"sv)
+ manager.set_decision(*permission_name, *top_level_origin, {});
+ if (*permission_name == Web::Permissions::PermissionName::Microphone)
+ client().update_audio_capture_permission();
+ }
+ return manager.snapshot();
+}
+
+void WebContentPage::set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held)
+{
+ auto permission_name = Web::Permissions::permission_name_from_string(name);
+ if (!permission_name.has_value())
+ return;
+
+ Optional<Web::Permissions::PromptOutcome> prompt_outcome;
+ if (outcome == "allow"sv)
+ prompt_outcome = Web::Permissions::PromptOutcome::AllowAlways;
+ else if (outcome == "allow-once"sv)
+ prompt_outcome = Web::Permissions::PromptOutcome::AllowOnce;
+ else if (outcome == "block"sv)
+ prompt_outcome = Web::Permissions::PromptOutcome::Block;
+ else if (outcome == "dismiss"sv)
+ prompt_outcome = Web::Permissions::PromptOutcome::Dismissed;
+ else if (outcome == "ignore"sv)
+ prompt_outcome = Web::Permissions::PromptOutcome::Ignored;
+ if (prompt_outcome.has_value())
+ view().set_next_permission_prompt_outcome_for_testing(*permission_name, *prompt_outcome, held);
+}
+
+void WebContentPage::release_held_permission_prompt_for_testing(u32 waiters)
+{
+ view().release_held_permission_prompt_for_testing(waiters);
+}
+
+Web::Permissions::PermissionSnapshot WebContentPage::advance_permission_clock_for_testing(u64 milliseconds)
+{
+ auto& manager = *view().session().permission_manager;
+ manager.age_origin_for_testing(view().url().origin(), AK::Duration::from_milliseconds(static_cast<i64>(milliseconds)));
+ return manager.snapshot();
+}
+
void WebContentPage::did_cancel_geolocation_position_request(u64 request_id)
{
if (view().on_cancel_geolocation_position_request)
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index cc930b8b12d..b785f694e1f 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -118,6 +118,12 @@ public:
// Whether a document this page hosts may use the feature. The process hosting the page can act for any of them.
bool hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature) const;
+ RefPtr<CanonicalDocument> hosted_document_with_id(Web::HTML::CrossProcessId) const;
+
+ Web::Permissions::PermissionSnapshot set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state);
+ void set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held);
+ void release_held_permission_prompt_for_testing(u32 waiters);
+ Web::Permissions::PermissionSnapshot advance_permission_clock_for_testing(u64 milliseconds);
void close();
void owe_reply(OwedReply);
@@ -269,7 +275,7 @@ private:
virtual void did_cancel_geolocation_position_request(u64 request_id) override;
virtual void did_start_geolocation_position_watch(u64 request_id) override;
virtual void did_stop_geolocation_position_watch(u64 request_id) override;
- virtual void did_request_permission(u64 request_id, Utf16String name) override;
+ virtual void did_request_permission(u64 request_id, Web::HTML::CrossProcessId document_id, Utf16String name) override;
virtual void did_request_file_picker(Web::HTML::FileFilter accepted_file_types, Web::HTML::AllowMultipleFiles allow_multiple_files) override;
virtual void did_finish_handling_input_event(u64 event_id, Web::EventResult event_result) override;
virtual void did_update_input_method_state(Optional<Web::DevicePixelRect> caret_rect, bool is_enabled, i32 cursor_position, i32 anchor_position, Utf16String text_before_cursor, Utf16String text_after_cursor) override;
diff --git a/Libraries/LibWebView/WebContentTestClient.cpp b/Libraries/LibWebView/WebContentTestClient.cpp
index 9f3a88157c0..bd972c6120c 100644
--- a/Libraries/LibWebView/WebContentTestClient.cpp
+++ b/Libraries/LibWebView/WebContentTestClient.cpp
@@ -43,6 +43,32 @@ void WebContentTestClient::did_expire_cookies_with_time_offset(AK::Duration offs
m_client.session().cookie_jar->expire_cookies_with_time_offset(offset);
}
+Messages::WebContentTestClient::SetPermissionForTestingResponse WebContentTestClient::set_permission_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId document_id, String name, String state)
+{
+ if (auto* page = m_client.page(page_id))
+ return page->set_permission_for_testing(document_id, name, state);
+ return Web::Permissions::PermissionSnapshot {};
+}
+
+void WebContentTestClient::set_next_permission_prompt_outcome_for_testing(Web::PageId page_id, String name, String outcome, bool held)
+{
+ if (auto* page = m_client.page(page_id))
+ page->set_next_permission_prompt_outcome_for_testing(name, outcome, held);
+}
+
+void WebContentTestClient::release_held_permission_prompt_for_testing(Web::PageId page_id, u32 waiters)
+{
+ if (auto* page = m_client.page(page_id))
+ page->release_held_permission_prompt_for_testing(waiters);
+}
+
+Messages::WebContentTestClient::AdvancePermissionClockForTestingResponse WebContentTestClient::advance_permission_clock_for_testing(Web::PageId page_id, u64 milliseconds)
+{
+ if (auto* page = m_client.page(page_id))
+ return page->advance_permission_clock_for_testing(milliseconds);
+ return Web::Permissions::PermissionSnapshot {};
+}
+
void WebContentTestClient::did_spoof_document_origin_for_testing(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, URL::Origin origin)
{
if (auto* page = m_client.page(page_id))
diff --git a/Libraries/LibWebView/WebContentTestClient.h b/Libraries/LibWebView/WebContentTestClient.h
index 816bfde98fb..653c175c558 100644
--- a/Libraries/LibWebView/WebContentTestClient.h
+++ b/Libraries/LibWebView/WebContentTestClient.h
@@ -44,6 +44,10 @@ private:
virtual Messages::WebContentTestClient::DidRequestRestoreSessionHistorySnapshotForTestingResponse did_request_restore_session_history_snapshot_for_testing(Web::PageId page_id) override;
virtual Messages::WebContentTestClient::DidRequestRegisterSessionStoreTabForTestingResponse did_request_register_session_store_tab_for_testing(Web::PageId page_id) override;
virtual Messages::WebContentTestClient::DidRequestSessionStoreTabStateForTestingResponse did_request_session_store_tab_state_for_testing(Web::PageId page_id) override;
+ virtual Messages::WebContentTestClient::SetPermissionForTestingResponse set_permission_for_testing(Web::PageId, Web::HTML::CrossProcessId document_id, String name, String state) override;
+ virtual void set_next_permission_prompt_outcome_for_testing(Web::PageId, String name, String outcome, bool held) override;
+ virtual void release_held_permission_prompt_for_testing(Web::PageId, u32 waiters) override;
+ virtual Messages::WebContentTestClient::AdvancePermissionClockForTestingResponse advance_permission_clock_for_testing(Web::PageId, u64 milliseconds) override;
virtual Messages::WebContentTestClient::CreateVirtualGamepadResponse create_virtual_gamepad() override;
virtual void set_virtual_gamepad_button(Web::Gamepad::GamepadHandle handle, i32 button, bool down) override;
virtual void set_virtual_gamepad_axis(Web::Gamepad::GamepadHandle handle, i32 axis, i16 value) override;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index c872033f57f..06b99f656cd 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -3252,10 +3252,10 @@ void ConnectionFromClient::geolocation_position_response(Web::PageId page_id, u6
page->geolocation_position_response(request_id, position, error_code);
}
-void ConnectionFromClient::permission_request_completed(Web::PageId page_id, u64 request_id, bool granted)
+void ConnectionFromClient::permission_request_completed(Web::PageId page_id, u64 request_id, Web::Permissions::EffectiveState state)
{
if (auto page = this->page(page_id); page.has_value())
- page->permission_request_completed(request_id, granted);
+ page->permission_request_completed(request_id, state);
}
void ConnectionFromClient::set_has_focus(Web::PageId page_id, bool has_focus)
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index d8fe563446c..c5c8fc0acc5 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -257,7 +257,7 @@ private:
virtual void set_writing_suggestions_available(Web::PageId page_id, bool available) override;
virtual void set_geolocation_emulated_position(Web::PageId page_id, WebView::GeolocationPositionData, Optional<u16> error_code) override;
virtual void geolocation_position_response(Web::PageId page_id, u64 request_id, WebView::GeolocationPositionData, Optional<u16> error_code) override;
- virtual void permission_request_completed(Web::PageId page_id, u64 request_id, bool granted) override;
+ virtual void permission_request_completed(Web::PageId page_id, u64 request_id, Web::Permissions::EffectiveState state) override;
virtual void set_has_focus(Web::PageId page_id, bool) override;
virtual void set_focused_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) override;
virtual void consume_user_activation(Web::PageId page_id, Web::HTML::UserActivationConsumption) override;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 20ec6a66875..53863728272 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1306,14 +1306,48 @@ void PageClient::page_did_request_geolocation_position(u64 request_id)
client().async_did_request_geolocation_position(m_id, request_id);
}
-void PageClient::page_did_request_permission(u64 request_id, Utf16String const& name)
+void PageClient::page_did_request_permission(u64 request_id, Web::HTML::CrossProcessId requesting_document_id, Utf16String const& name)
{
- client().async_did_request_permission(m_id, request_id, name);
+ client().async_did_request_permission(m_id, request_id, requesting_document_id, name);
}
-void PageClient::permission_request_completed(u64 request_id, bool granted)
+Optional<Web::Permissions::PermissionSnapshot> PageClient::page_did_set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state)
{
- page().permission_request_completed(request_id, granted);
+ auto* test_connection = client().test_connection();
+ if (!test_connection)
+ return {};
+ auto response = test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::SetPermissionForTesting>(m_id, document_id, name, state);
+ if (!response)
+ return {};
+ return response->take_snapshot();
+}
+
+void PageClient::page_did_set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held)
+{
+ if (auto* test_connection = client().test_connection())
+ (void)test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::SetNextPermissionPromptOutcomeForTesting>(m_id, name, outcome, held);
+}
+
+void PageClient::page_did_release_held_permission_prompt_for_testing(u32 waiters)
+{
+ if (auto* test_connection = client().test_connection())
+ (void)test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::ReleaseHeldPermissionPromptForTesting>(m_id, waiters);
+}
+
+Optional<Web::Permissions::PermissionSnapshot> PageClient::page_did_advance_permission_clock_for_testing(u64 milliseconds)
+{
+ auto* test_connection = client().test_connection();
+ if (!test_connection)
+ return {};
+ auto response = test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::AdvancePermissionClockForTesting>(m_id, milliseconds);
+ if (!response)
+ return {};
+ return response->take_snapshot();
+}
+
+void PageClient::permission_request_completed(u64 request_id, Web::Permissions::EffectiveState state)
+{
+ page().permission_request_completed(request_id, state);
}
void PageClient::page_did_cancel_geolocation_position_request(u64 request_id)
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 38aebe9e93f..0150f75f5d9 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -107,7 +107,7 @@ public:
void set_geolocation_emulated_position(WebView::GeolocationPositionData const&, Optional<u16> error_code);
void geolocation_position_response(u64 request_id, WebView::GeolocationPositionData const&, Optional<u16> error_code);
- void permission_request_completed(u64 request_id, bool granted);
+ void permission_request_completed(u64 request_id, Web::Permissions::EffectiveState);
Optional<URL::URL> generate_text_fragment_url(u64 generation_id);
void alert_closed();
@@ -350,7 +350,11 @@ private:
virtual void page_did_cancel_geolocation_position_request(u64 request_id) override;
virtual void page_did_start_geolocation_position_watch(u64 request_id) override;
virtual void page_did_stop_geolocation_position_watch(u64 request_id) override;
- virtual void page_did_request_permission(u64 request_id, Utf16String const& name) override;
+ virtual void page_did_request_permission(u64 request_id, Web::HTML::CrossProcessId requesting_document_id, Utf16String const& name) override;
+ virtual Optional<Web::Permissions::PermissionSnapshot> page_did_set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state) override;
+ virtual void page_did_set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held) override;
+ virtual void page_did_release_held_permission_prompt_for_testing(u32 waiters) override;
+ virtual Optional<Web::Permissions::PermissionSnapshot> page_did_advance_permission_clock_for_testing(u64 milliseconds) override;
virtual void page_did_finish_test(Utf16String const& text) override;
virtual void page_did_set_test_timeout(double milliseconds) override;
virtual void page_did_receive_reference_test_metadata(JsonValue) override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 8d48d136cfe..6e86e529172 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -72,6 +72,7 @@
#include <LibWebCommon/WebView/DOMNodeProperties.h>
#include <LibWebCommon/WebView/Debugger.h>
#include <LibWebCommon/WebView/DictionaryLookup.h>
+#include <LibWebCommon/Permissions/Permissions.h>
#include <LibWebCommon/WebView/Mutation.h>
#include <LibWebCommon/WebView/PageInfo.h>
#include <LibWebCommon/WebView/StorageSetResult.h>
@@ -237,7 +238,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_cancel_geolocation_position_request(Web::PageId page_id, u64 request_id) =|
did_start_geolocation_position_watch(Web::PageId page_id, u64 request_id) =|
did_stop_geolocation_position_watch(Web::PageId page_id, u64 request_id) =|
- did_request_permission(Web::PageId page_id, u64 request_id, Utf16String name) =|
+ did_request_permission(Web::PageId page_id, u64 request_id, Web::HTML::CrossProcessId document_id, Utf16String name) =|
did_request_file_picker(Web::PageId page_id, Web::HTML::FileFilter accepted_file_types, Web::HTML::AllowMultipleFiles allow_multiple_files) =|
did_request_select_dropdown(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, i32 minimum_width, Vector<Web::HTML::SelectItem> items) =|
did_finish_handling_input_event(Web::PageId page_id, u64 event_id, Web::EventResult event_result) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index f110ee987ac..1506944d4be 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -264,7 +264,7 @@ endpoint WebContentServer routed by Web::PageId page_id
set_writing_suggestions_available(Web::PageId page_id, bool available) =|
set_geolocation_emulated_position(Web::PageId page_id, WebView::GeolocationPositionData position, Optional<u16> error_code) =|
geolocation_position_response(Web::PageId page_id, u64 request_id, WebView::GeolocationPositionData position, Optional<u16> error_code) =|
- permission_request_completed(Web::PageId page_id, u64 request_id, bool granted) =|
+ permission_request_completed(Web::PageId page_id, u64 request_id, Web::Permissions::EffectiveState state) =|
set_has_focus(Web::PageId page_id, bool has_focus) =|
set_focused_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) =|
consume_user_activation(Web::PageId page_id, Web::HTML::UserActivationConsumption consumption) =|
diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipc
index f59325c701a..cf3058e8942 100644
--- a/Services/WebContent/WebContentTestClient.ipc
+++ b/Services/WebContent/WebContentTestClient.ipc
@@ -5,6 +5,7 @@
#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
#include <LibWebCommon/HTML/SessionHistoryEntryDescriptor.h>
#include <LibWebCommon/Page/PageId.h>
+#include <LibWebCommon/Permissions/Permissions.h>
#include <LibWebCommon/StorageAPI/StorageEndpoint.h>
endpoint WebContentTestClient routed by Web::PageId page_id
@@ -17,6 +18,11 @@ endpoint WebContentTestClient routed by Web::PageId page_id
did_store_hsts_policy_for_testing(String domain, HTTP::HSTS::ParsedHSTSPolicy policy) => ()
[NotRouted] did_request_clear_storage_for_testing(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id) => ()
did_simulate_worker_request_server_connection_loss(Web::PageId page_id) => ()
+
+ [NotRouted] set_permission_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId document_id, String name, String state) => (Web::Permissions::PermissionSnapshot snapshot)
+ [NotRouted] set_next_permission_prompt_outcome_for_testing(Web::PageId page_id, String name, String outcome, bool held) => ()
+ [NotRouted] release_held_permission_prompt_for_testing(Web::PageId page_id, u32 waiters) => ()
+ [NotRouted] advance_permission_clock_for_testing(Web::PageId page_id, u64 milliseconds) => (Web::Permissions::PermissionSnapshot snapshot)
[NotRouted] did_spoof_document_origin_for_testing(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, URL::Origin origin) => ()
[NotRouted] did_request_ui_process_session_history_for_testing(Web::PageId page_id) => (String session_history)
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 83c6d4baeaf..6a3770c3c9a 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -6,6 +6,8 @@ Text/input/wpt-import/custom-elements/adopted-callback.html
Text/input/wpt-import/custom-elements/connected-callbacks.html
; Picture aspect ratios depend on images loaded by root-relative srcset URLs.
Text/input/wpt-import/html/rendering/replaced-elements/attributes-for-embedded-content-and-images/picture-aspect-ratio.html
+; Permissions are kept for a site's origin, and a file: page has none.
+Text/input/PermissionsAPI/
Text/input/HTML/xml-document-encoding.html
Text/input/HTML/createImageBitmap-video.html
Text/input/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.html
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-allow-once-expires.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-allow-once-expires.txt
new file mode 100644
index 00000000000..0e1dac65904
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-allow-once-expires.txt
@@ -0,0 +1,3 @@
+request: granted
+just under sixteen hours: granted
+sixteen hours: prompt
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-coalesced-dismissal-counts-once.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-coalesced-dismissal-counts-once.txt
new file mode 100644
index 00000000000..9af35ef3a45
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-coalesced-dismissal-counts-once.txt
@@ -0,0 +1,2 @@
+requests: denied, denied, denied
+query: prompt
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-coalesced-requests.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-coalesced-requests.txt
new file mode 100644
index 00000000000..3c83bfa49ce
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-coalesced-requests.txt
@@ -0,0 +1,2 @@
+first: granted, second: granted
+after sixteen hours: prompt
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-dismiss-stays-prompt.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-dismiss-stays-prompt.txt
new file mode 100644
index 00000000000..d55949183d3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-dismiss-stays-prompt.txt
@@ -0,0 +1,2 @@
+dismiss: request denied, query prompt
+ignore: request denied, query prompt
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-embargo.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-embargo.txt
new file mode 100644
index 00000000000..b65e5c96c6e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-embargo.txt
@@ -0,0 +1,9 @@
+after dismissal 1: prompt
+after dismissal 2: prompt
+after dismissal 3: denied
+request during embargo: denied
+after seven days: prompt
+after ignore 1: prompt
+after ignore 2: prompt
+after ignore 3: prompt
+after ignore 4: denied
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-prompt-allow-persists.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-prompt-allow-persists.txt
new file mode 100644
index 00000000000..2f8ccce0091
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-prompt-allow-persists.txt
@@ -0,0 +1,4 @@
+before: prompt
+request: granted
+query: granted
+second request: granted
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-prompt-block.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-prompt-block.txt
new file mode 100644
index 00000000000..bd5a5dfcd54
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-prompt-block.txt
@@ -0,0 +1,2 @@
+request: denied
+query: denied
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-stale-answer-after-block-and-reset.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-stale-answer-after-block-and-reset.txt
new file mode 100644
index 00000000000..3c3b1bd1628
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-stale-answer-after-block-and-reset.txt
@@ -0,0 +1,2 @@
+request: denied
+query: prompt
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/permission-stale-completion-discarded.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-stale-completion-discarded.txt
new file mode 100644
index 00000000000..bd5a5dfcd54
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/permission-stale-completion-discarded.txt
@@ -0,0 +1,2 @@
+request: denied
+query: denied
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/testdriver-set-permission.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/testdriver-set-permission.txt
new file mode 100644
index 00000000000..ffa1aed2bf1
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/testdriver-set-permission.txt
@@ -0,0 +1,3 @@
+granted: granted
+denied: denied
+prompt: prompt
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-allow-once-expires.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-allow-once-expires.html
new file mode 100644
index 00000000000..d16d641ae4a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-allow-once-expires.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ internals.setNextPermissionPromptOutcome("microphone", "allow-once");
+ println(`request: ${await internals.requestPermission("microphone")}`);
+ await internals.advancePermissionClock(16 * 60 * 60 * 1000 - 1000);
+ println(`just under sixteen hours: ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ await internals.advancePermissionClock(1000);
+ println(`sixteen hours: ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-coalesced-dismissal-counts-once.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-coalesced-dismissal-counts-once.html
new file mode 100644
index 00000000000..e4fa5dc156e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-coalesced-dismissal-counts-once.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ // Three requests share one prompt, so dismissing it is one dismissal, not the three that embargo a site.
+ internals.setNextPermissionPromptOutcome("geolocation", "dismiss", true);
+ const requests = [1, 2, 3].map(() => internals.requestPermission("geolocation"));
+ internals.releaseHeldPermissionPrompt(3);
+ println(`requests: ${(await Promise.all(requests)).join(", ")}`);
+ println(`query: ${(await navigator.permissions.query({ name: "geolocation" })).state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-coalesced-requests.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-coalesced-requests.html
new file mode 100644
index 00000000000..fde7ced3dab
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-coalesced-requests.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ // Both requests share the one held prompt, so its one-time answer is the only decision made. A second prompt
+ // would have been answered with the default "Allow while visiting the site", which outlasts sixteen hours.
+ internals.setNextPermissionPromptOutcome("microphone", "allow-once", true);
+ const first = internals.requestPermission("microphone");
+ const second = internals.requestPermission("microphone");
+ internals.releaseHeldPermissionPrompt(2);
+ println(`first: ${await first}, second: ${await second}`);
+ await internals.advancePermissionClock(16 * 60 * 60 * 1000);
+ println(`after sixteen hours: ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-dismiss-stays-prompt.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-dismiss-stays-prompt.html
new file mode 100644
index 00000000000..27fa0048808
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-dismiss-stays-prompt.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ for (const outcome of ["dismiss", "ignore"]) {
+ internals.setNextPermissionPromptOutcome("microphone", outcome);
+ println(`${outcome}: request ${await internals.requestPermission("microphone")}, query ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-embargo.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-embargo.html
new file mode 100644
index 00000000000..979898eb6a8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-embargo.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const query = async name => (await navigator.permissions.query({ name })).state;
+ const sevenDays = 7 * 24 * 60 * 60 * 1000;
+
+ for (let i = 1; i <= 3; ++i) {
+ internals.setNextPermissionPromptOutcome("geolocation", "dismiss");
+ await internals.requestPermission("geolocation");
+ println(`after dismissal ${i}: ${await query("geolocation")}`);
+ }
+ // An embargoed site isn't asked: the next answer set up here goes unused.
+ internals.setNextPermissionPromptOutcome("geolocation", "allow");
+ println(`request during embargo: ${await internals.requestPermission("geolocation")}`);
+ await internals.advancePermissionClock(sevenDays);
+ println(`after seven days: ${await query("geolocation")}`);
+
+ for (let i = 1; i <= 4; ++i) {
+ internals.setNextPermissionPromptOutcome("microphone", "ignore");
+ await internals.requestPermission("microphone");
+ println(`after ignore ${i}: ${await query("microphone")}`);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-prompt-allow-persists.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-prompt-allow-persists.html
new file mode 100644
index 00000000000..aaf218039cc
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-prompt-allow-persists.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const status = await navigator.permissions.query({ name: "microphone" });
+ println(`before: ${status.state}`);
+ internals.setNextPermissionPromptOutcome("microphone", "allow");
+ println(`request: ${await internals.requestPermission("microphone")}`);
+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ println(`second request: ${await internals.requestPermission("microphone")}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-prompt-block.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-prompt-block.html
new file mode 100644
index 00000000000..964910f66a5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-prompt-block.html
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ internals.setNextPermissionPromptOutcome("geolocation", "block");
+ println(`request: ${await internals.requestPermission("geolocation")}`);
+ println(`query: ${(await navigator.permissions.query({ name: "geolocation" })).state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-stale-answer-after-block-and-reset.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-stale-answer-after-block-and-reset.html
new file mode 100644
index 00000000000..b985d560425
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-stale-answer-after-block-and-reset.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ // The user blocks the site and then resets it while its prompt is up: the prompt's answer is stale either way.
+ internals.setNextPermissionPromptOutcome("microphone", "allow", true);
+ const request = internals.requestPermission("microphone");
+ await internals.setPermission("microphone", "denied");
+ await internals.setPermission("microphone", "prompt");
+ internals.releaseHeldPermissionPrompt();
+ println(`request: ${await request}`);
+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/permission-stale-completion-discarded.html b/Tests/LibWeb/Text/input/PermissionsAPI/permission-stale-completion-discarded.html
new file mode 100644
index 00000000000..a5a43ae3e3c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/permission-stale-completion-discarded.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ internals.setNextPermissionPromptOutcome("microphone", "allow", true);
+ const request = internals.requestPermission("microphone");
+ await internals.setPermission("microphone", "denied");
+ internals.releaseHeldPermissionPrompt();
+ println(`request: ${await request}`);
+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/testdriver-set-permission.html b/Tests/LibWeb/Text/input/PermissionsAPI/testdriver-set-permission.html
new file mode 100644
index 00000000000..8dd36654767
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/testdriver-set-permission.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script src="../wpt-import/resources/testdriver.js"></script>
+<script src="../wpt-import/resources/testdriver-vendor.js"></script>
+<script>
+ asyncTest(async done => {
+ for (const state of ["granted", "denied", "prompt"]) {
+ await test_driver.set_permission({ name: "geolocation" }, state);
+ println(`${state}: ${(await navigator.permissions.query({ name: "geolocation" })).state}`);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/resources/testdriver-vendor.js b/Tests/LibWeb/Text/input/wpt-import/resources/testdriver-vendor.js
index f6e6b0e44b0..ad4235a8ff2 100644
--- a/Tests/LibWeb/Text/input/wpt-import/resources/testdriver-vendor.js
+++ b/Tests/LibWeb/Text/input/wpt-import/resources/testdriver-vendor.js
@@ -151,3 +151,7 @@ window.test_driver_internal.action_sequence = async function(actions, context) {
}
}
};
+
+window.test_driver_internal.set_permission = function(permission_params, context) {
+ return window.internals.setPermission(permission_params.descriptor.name, permission_params.state);
+};
diff --git a/Tests/LibWeb/test-web/TestWebView.cpp b/Tests/LibWeb/test-web/TestWebView.cpp
index a9a8bc8f5c4..a406f0afc94 100644
--- a/Tests/LibWeb/test-web/TestWebView.cpp
+++ b/Tests/LibWeb/test-web/TestWebView.cpp
@@ -11,6 +11,7 @@
#include <LibCore/AnonymousBuffer.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/ShareableBitmap.h>
+#include <LibWebView/PermissionManager.h>
namespace TestWeb {
@@ -57,6 +58,14 @@ void TestWebView::reset_geolocation_emulated_position()
geolocation_settings_changed();
}
+// Permissions live in the UI process, and outlive the test that changed them. Each test has an origin of its own, and
+// tests run concurrently, so only this test's origin is reset.
+void TestWebView::reset_permissions()
+{
+ session().permission_manager->reset_origin(url().origin());
+ reset_permission_prompts_for_testing();
+}
+
NonnullRefPtr<Core::Promise<Empty>> TestWebView::reset_state_for_next_test()
{
return WebView::ViewImplementation::reset_state_for_testing();
diff --git a/Tests/LibWeb/test-web/TestWebView.h b/Tests/LibWeb/test-web/TestWebView.h
index f3aeb2dbc95..a82b8de6792 100644
--- a/Tests/LibWeb/test-web/TestWebView.h
+++ b/Tests/LibWeb/test-web/TestWebView.h
@@ -27,6 +27,7 @@ public:
void reset_line_box_borders();
void reset_user_style();
void reset_geolocation_emulated_position();
+ void reset_permissions();
NonnullRefPtr<Core::Promise<Empty>> reset_state_for_next_test();
NonnullRefPtr<Core::Promise<RefPtr<Gfx::Bitmap const>>> take_screenshot();
diff --git a/Tests/LibWeb/test-web/main.cpp b/Tests/LibWeb/test-web/main.cpp
index 921ff66a022..3b65f3b9fcd 100644
--- a/Tests/LibWeb/test-web/main.cpp
+++ b/Tests/LibWeb/test-web/main.cpp
@@ -1271,6 +1271,7 @@ static ErrorOr<int> run_tests(Core::AnonymousBuffer const& theme, Web::DevicePix
view->reset_line_box_borders();
view->reset_user_style();
view->reset_geolocation_emulated_position();
+ view->reset_permissions();
view->reset_viewport_size(window_size);
}
diff --git a/Tests/LibWebView/TestPermissionManager.cpp b/Tests/LibWebView/TestPermissionManager.cpp
index 7b10ce3633c..bb82d065f86 100644
--- a/Tests/LibWebView/TestPermissionManager.cpp
+++ b/Tests/LibWebView/TestPermissionManager.cpp
@@ -369,16 +369,16 @@ TEST_CASE(site_decisions_list_stored_decisions)
EXPECT(site.decision == (site.origin.is_same_origin(maps) ? PermissionDecision::Allow : PermissionDecision::Block));
}
-TEST_CASE(clear_for_testing_forgets_everything)
+TEST_CASE(aging_an_origin_leaves_others_alone)
{
- FakeClock clock;
- auto manager = create_manager(clock, "clear"sv);
- manager->set_decision(PermissionName::Geolocation, maps, PermissionDecision::Block);
- for (int i = 0; i < 3; ++i)
- manager->record_prompt_outcome(PermissionName::Microphone, talk, PromptOutcome::Dismissed);
- manager->clear_for_testing();
+ auto manager = PermissionManager::create_for_ordinary_session(persistence_path("aging"sv));
+ for (auto const& origin : { maps, talk }) {
+ for (int i = 0; i < 3; ++i)
+ manager->record_prompt_outcome(PermissionName::Geolocation, origin, PromptOutcome::Dismissed);
+ }
+ manager->age_origin_for_testing(maps, AK::Duration::from_seconds(7 * 86400));
EXPECT(manager->effective_state(PermissionName::Geolocation, maps) == EffectiveState::Prompt);
- EXPECT(manager->effective_state(PermissionName::Microphone, talk) == EffectiveState::Prompt);
+ EXPECT(manager->effective_state(PermissionName::Geolocation, talk) == EffectiveState::Denied);
}
TEST_CASE(global_block_overrides_stored_allow)
diff --git a/UI/Qt/Tab.cpp b/UI/Qt/Tab.cpp
index 043ec489ef2..3cfa011f0cf 100644
--- a/UI/Qt/Tab.cpp
+++ b/UI/Qt/Tab.cpp
@@ -1574,10 +1574,14 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)
}
if (m_external_url_confirmation_dialog)
m_external_url_confirmation_dialog->close();
- auto pending_permission_requests = AK::move(m_pending_permission_requests);
- for (auto& it : pending_permission_requests) {
- if (it.value.popover)
- it.value.popover->close();
+ // A prompt the page leaves behind counts as ignored, since the user never answered it.
+ auto permission_prompts = AK::move(m_permission_prompts);
+ for (auto& prompt : permission_prompts) {
+ if (prompt.popover) {
+ prompt.popover->on_dismiss = nullptr;
+ prompt.popover->close();
+ }
+ prompt.on_outcome(Web::Permissions::PromptOutcome::Ignored);
}
};
@@ -1618,34 +1622,28 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)
dialog->open();
};
- // A site's request for a permission hangs from the site settings button, and is denied unless it is allowed.
- view().on_request_permission = [this](auto const& name, auto const& origin, auto on_decided) {
- auto requester = origin.is_opaque() ? "This page"_string : origin.host().serialize();
- auto question = MUST(String::formatted("{} wants to use your {}", requester, name));
- if (auto pending = m_pending_permission_requests.get(question); pending.has_value()) {
- pending.value().on_decided.append(AK::move(on_decided));
- return;
- }
+ // A site's request for a permission hangs from the site settings button. Allowing it is a decision the session keeps;
+ // leaving the prompt any other way dismisses it, which decides nothing.
+ view().on_request_permission = [this](WebView::PermissionPromptRequest const& request, WebView::PermissionPromptCallback on_outcome) {
+ auto requester = request.is_file || request.top_level_origin.is_opaque() ? "This page"_string : request.top_level_origin.host().serialize();
+ auto feature = request.name == Web::Permissions::PermissionName::Geolocation ? "know your location"sv : "use your microphone"sv;
+ auto question = MUST(String::formatted("{} wants to {}", requester, feature));
- // NB: The microphone is the only feature a site asks for permission to use.
- auto icon = name == "microphone"sv ? create_chrome_icon(ChromeIcon::Microphone, Theme::panel().link) : QIcon {};
- auto* popover = new MessagePopover(this, PERMISSION_POPOVER_WIDTH, qstring_from_ak_string(question), {}, "Block", "Allow", icon);
+ auto icon = request.name == Web::Permissions::PermissionName::Microphone ? create_chrome_icon(ChromeIcon::Microphone, Theme::panel().link) : QIcon {};
+ auto* popover = new MessagePopover(this, PERMISSION_POPOVER_WIDTH, qstring_from_ak_string(question), {}, "Not now", "Allow", icon);
popover->setAttribute(Qt::WA_DeleteOnClose);
popover->update_chrome_style(palette());
+ m_permission_prompts.append({ .popover = popover, .on_outcome = AK::move(on_outcome) });
- PendingPermissionRequests pending { .popover = popover, .on_decided = {} };
- pending.on_decided.append(AK::move(on_decided));
- m_pending_permission_requests.set(question, AK::move(pending));
-
- auto decide = [this, question](bool granted) {
- auto pending = m_pending_permission_requests.take(question);
- if (!pending.has_value())
+ auto decide = [this, popover = QPointer<MessagePopover> { popover }](Web::Permissions::PromptOutcome outcome) {
+ auto index = m_permission_prompts.find_first_index_if([&](auto const& prompt) { return prompt.popover == popover; });
+ if (!index.has_value())
return;
- for (auto& on_decided : pending.value().on_decided)
- on_decided(granted);
+ auto prompt = m_permission_prompts.take(*index);
+ prompt.on_outcome(outcome);
};
- popover->on_accept = [decide] { decide(true); };
- popover->on_dismiss = [decide] { decide(false); };
+ popover->on_accept = [decide] { decide(Web::Permissions::PromptOutcome::AllowAlways); };
+ popover->on_dismiss = [decide] { decide(Web::Permissions::PromptOutcome::Dismissed); };
auto& anchor = m_location_edit->site_settings_button();
QWidget& anchor_or_field = anchor.isVisible() ? anchor : static_cast<QWidget&>(*m_location_edit);
diff --git a/UI/Qt/Tab.h b/UI/Qt/Tab.h
index bb8f44258fb..ed20db55cf7 100644
--- a/UI/Qt/Tab.h
+++ b/UI/Qt/Tab.h
@@ -323,12 +323,13 @@ private:
QPointer<QColorDialog> m_color_picker_dialog;
QPointer<QFileDialog> m_file_picker_dialog;
QPointer<QMessageBox> m_external_url_confirmation_dialog;
- // Requests the same dialog would answer wait on the one open, so a page cannot stack dialogs by asking again.
- struct PendingPermissionRequests {
+ // The prompts open for the page's permission requests. The view hands identical requests to one prompt, so each
+ // prompt answers for one request, and a page cannot stack prompts by asking again.
+ struct PendingPermissionPrompt {
QPointer<MessagePopover> popover;
- Vector<Function<void(bool granted)>> on_decided;
+ WebView::PermissionPromptCallback on_outcome;
};
- HashMap<String, PendingPermissionRequests> m_pending_permission_requests;
+ Vector<PendingPermissionPrompt> m_permission_prompts;
bool m_suppress_javascript_dialogs_until_navigation { false };
// The dialogs the current document has shown, and whether the user stopped it from showing more.