Truly independent web browser
LibWeb+LibWebView: Report navigation violations in the source's process
Luke Wildee0b99c04a379
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cppindex d639f5aeb04..58db5dacdc6 100644--- a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp+++ b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp@@ -32,35 +32,58 @@namespace Web::ContentSecurityPolicy {-// AD-HOC: A client another process hosts has its global object there, and its violations belong to that global, so-// none is reported here.-// FIXME: Report those violations in the process hosting the client's environment.-static bool may_report_violations_for(Fetch::Infrastructure::Request const& request)+static Optional<RemoteViolationDirective> remote_violation_directive(Utf16FlyString const& directive){- return !Fetch::Fetching::remote_client(request);+ if (directive == Directives::Names::FrameSrc)+ return RemoteViolationDirective::FrameSrc;+ if (directive == Directives::Names::ObjectSrc)+ return RemoteViolationDirective::ObjectSrc;+ if (directive == Directives::Names::FormAction)+ return RemoteViolationDirective::FormAction;+ return {};+}++static Utf16FlyString const& directive_name(RemoteViolationDirective directive)+{+ switch (directive) {+ case RemoteViolationDirective::FrameSrc:+ return Directives::Names::FrameSrc;+ case RemoteViolationDirective::ObjectSrc:+ return Directives::Names::ObjectSrc;+ case RemoteViolationDirective::FormAction:+ return Directives::Names::FormAction;+ }+ VERIFY_NOT_REACHED();}// AD-HOC: A client another process hosts has its global object there, so its page reports the violation to that// process, by the violated policy's index in the client's CSP list.-// FIXME: WebContent's page drops the violation.-static void report_a_violation_of_a_remote_client(Page& page, NonnullRefPtr<Fetch::Infrastructure::Request> const& request, Policy const& policy)+static void report_a_violation_of_a_remote_client(Page& page, Fetch::Infrastructure::Request const& request, Policy const& policy, Utf16FlyString const& directive){- // NB: Request's policy container is a clone of the client's, which lists the policies in the same order.- auto const& policies = request->policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list.policies();+ // NB: Request's policy container is a copy of the client's, which lists the policies in the same order.+ auto const& policies = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list.policies();auto policy_index = policies.find_first_index_if([&](auto const& candidate) { return candidate.ptr() == &policy; });if (!policy_index.has_value())return;- auto effective_directive = Directives::get_the_effective_directive_for_request(request);- VERIFY(effective_directive.has_value());- page.client().page_did_report_violation_of_remote_client(*policy_index, effective_directive->view().to_utf8_but_should_be_ported_to_utf16(), request->url());+ if (auto const& navigation = request.remote_client_navigation(); navigation.has_value()) {+ // NB: The UI process checks a navigation's report against the directives the navigation can violate, and+ // reports the URL the navigation started with, upgraded to https when the request's URL is.+ auto url_is_https = request.url().scheme() == "https"sv;+ if (auto remote_directive = remote_violation_directive(directive); remote_directive.has_value())+ page.client().page_did_report_navigation_violation_of_remote_client(*navigation, *policy_index, *remote_directive, url_is_https);+ return;+ }+ page.client().page_did_report_violation_of_remote_client(*policy_index, directive.view().to_utf8_but_should_be_ported_to_utf16(), request.url());}ViolationReporter violation_reporter_for_request(JS::Realm& realm, NonnullRefPtr<Fetch::Infrastructure::Request> request){return [&realm, request](NonnullRefPtr<Policy const> policy) {if (Fetch::Fetching::remote_client(request)) {- report_a_violation_of_a_remote_client(Bindings::principal_host_defined_page(realm), request, policy);+ auto effective_directive = Directives::get_the_effective_directive_for_request(request);+ VERIFY(effective_directive.has_value());+ report_a_violation_of_a_remote_client(Bindings::principal_host_defined_page(realm), request, policy, *effective_directive);return;}auto violation = Violation::create_a_violation_object_for_request_and_policy(request, move(policy));@@ -93,8 +116,13 @@ void report_a_violation_found_in_another_process(HTML::EnvironmentSettingsObjectviolation->report_a_violation(settings.realm());}+void report_a_violation_found_in_another_process(HTML::EnvironmentSettingsObject& settings, u64 policy_index, RemoteViolationDirective directive, URL::URL resource)+{+ report_a_violation_found_in_another_process(settings, policy_index, directive_name(directive), move(resource));+}+// https://w3c.github.io/webappsec-csp/#should-block-navigation-request-Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_content_security_policy(NonnullRefPtr<Fetch::Infrastructure::Request> navigation_request, Directives::Directive::NavigationType navigation_type)+Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_content_security_policy(NonnullRefPtr<Fetch::Infrastructure::Request> navigation_request, Directives::Directive::NavigationType navigation_type, Page& page){// 1. Let result be "Allowed".auto result = Directives::Directive::Result::Allowed;@@ -111,7 +139,9 @@ Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_coif (directive_result == Directives::Directive::Result::Allowed)continue;- if (may_report_violations_for(*navigation_request)) {+ if (Fetch::Fetching::remote_client(*navigation_request)) {+ report_a_violation_of_a_remote_client(page, *navigation_request, policy, directive.name());+ } else {// 2. Otherwise, let violation be the result of executing § 2.4.1 Create a violation object for global, policy, and directive on navigation request’s// client’s global object, policy, and directive’s name.auto& realm = client->realm();@@ -158,7 +188,9 @@ Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_coif (Directives::inline_check(directive, nullptr, Directives::Directive::InlineType::Navigation, policy, serialized_url_utf16.utf16_view()) == Directives::Directive::Result::Allowed)continue;- if (may_report_violations_for(*navigation_request)) {+ if (Fetch::Fetching::remote_client(*navigation_request)) {+ report_a_violation_of_a_remote_client(page, *navigation_request, policy, directive_name);+ } else {// 3. Otherwise, let violation be the result of executing § 2.4.1 Create a violation object for global,// policy, and directive on navigation request’s client’s global object, policy, and directive-name.auto& realm = client->realm();@@ -257,17 +289,16 @@ Directives::Directive::Result should_navigation_response_to_navigation_request_oif (directive_result == Directives::Directive::Result::Allowed)continue;- if (may_report_violations_for(*navigation_request)) {- // 2. Otherwise, let violation be the result of executing § 2.4.1 Create a violation object for global, policy, and directive on navigation request’s client’s global object, policy, and directive’s name.- auto& realm = client->realm();- auto violation = Violation::create_a_violation_object_for_global_policy_and_directive(client->global_object(), policy, directive.name().view().to_utf8_but_should_be_ported_to_utf16());+ // 2. Otherwise, let violation be the result of executing § 2.4.1 Create a violation object for global, policy, and directive on navigation request’s client’s global object, policy, and directive’s name.+ // NB: No directive's navigation response check acts on the navigation request's own policies.+ auto& realm = client->realm();+ auto violation = Violation::create_a_violation_object_for_global_policy_and_directive(client->global_object(), policy, directive.name().view().to_utf8_but_should_be_ported_to_utf16());- // 3. Set violation’s resource to navigation request’s URL.- violation->set_resource(navigation_request->url());+ // 3. Set violation’s resource to navigation request’s URL.+ violation->set_resource(navigation_request->url());- // 4. Execute § 5.5 Report a violation on violation.- violation->report_a_violation(realm);- }+ // 4. Execute § 5.5 Report a violation on violation.+ violation->report_a_violation(realm);// 5. If policy’s disposition is "enforce", then set result to "Blocked".if (policy->disposition() == Policy::Disposition::Enforce)diff --git a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.hindex e2c0331754a..d9baa167c73 100644--- a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h+++ b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h@@ -11,13 +11,15 @@#include <LibURL/Forward.h>#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>#include <LibWeb/ContentSecurityPolicy/FetchIntegration.h>+#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h>namespace Web::ContentSecurityPolicy {[[nodiscard]] ViolationReporter violation_reporter_for_request(JS::Realm&, NonnullRefPtr<Fetch::Infrastructure::Request>);void report_a_violation_found_in_another_process(HTML::EnvironmentSettingsObject&, u64 policy_index, Utf16FlyString const& directive, URL::URL resource);+WEB_API void report_a_violation_found_in_another_process(HTML::EnvironmentSettingsObject&, u64 policy_index, RemoteViolationDirective, URL::URL resource);-Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_content_security_policy(NonnullRefPtr<Fetch::Infrastructure::Request> navigation_request, Directives::Directive::NavigationType navigation_type);+Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_content_security_policy(NonnullRefPtr<Fetch::Infrastructure::Request> navigation_request, Directives::Directive::NavigationType navigation_type, Page&);Directives::Directive::Result should_navigation_response_to_navigation_request_of_type_in_target_be_blocked_by_content_security_policy(RefPtr<Fetch::Infrastructure::Request> navigation_request,GC::Ref<Fetch::Infrastructure::ResponseView> navigation_response,diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cppindex 100d87e1b65..74affad5d9c 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp@@ -217,6 +217,7 @@ NonnullRefPtr<Request> Request::clone() constnew_request->set_unsafe_request(m_unsafe_request);new_request->set_client(m_client);new_request->set_client_snapshot(m_client_snapshot);+ new_request->set_remote_client_navigation(m_remote_client_navigation);new_request->set_reserved_client_snapshot(m_reserved_client_snapshot);new_request->set_replaces_client_id(m_replaces_client_id);new_request->set_traversable_for_user_prompts(m_traversable_for_user_prompts);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.hindex aff05532a47..8c76909607c 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h@@ -201,6 +201,9 @@ public:[[nodiscard]] RefPtr<ClientContextSnapshot const> const& client_snapshot() const { return m_client_snapshot; }void set_client_snapshot(RefPtr<ClientContextSnapshot const> client_snapshot) { m_client_snapshot = move(client_snapshot); }+ [[nodiscard]] Optional<HTML::RemoteClientNavigation> const& remote_client_navigation() const { return m_remote_client_navigation; }+ void set_remote_client_navigation(Optional<HTML::RemoteClientNavigation> remote_client_navigation) { m_remote_client_navigation = move(remote_client_navigation); }+[[nodiscard]] RefPtr<ReservedClientContextSnapshot const> const& reserved_client_snapshot() const { return m_reserved_client_snapshot; }void set_reserved_client_snapshot(RefPtr<ReservedClientContextSnapshot const> reserved_client_snapshot) { m_reserved_client_snapshot = move(reserved_client_snapshot); }@@ -382,6 +385,10 @@ private:// What fetching reads from the client, null when the client is.RefPtr<ClientContextSnapshot const> m_client_snapshot;+ // The navigation of a navigation request whose client another process hosts, through which the UI process finds that+ // client.+ Optional<HTML::RemoteClientNavigation> m_remote_client_navigation;+// https://fetch.spec.whatwg.org/#concept-request-reserved-client// A request has an associated reserved client (null, an environment, or an environment settings object). Unless// stated otherwise it is null.diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 62665dcaaee..6de840bc99d 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -856,6 +856,7 @@ struct NavigationParams;struct PreparedNavigation;struct PaintConfig;struct PolicyContainer;+struct RemoteClientNavigation;struct SerializedFormData;struct SourceSnapshotParams;struct ToggleTaskTracker;diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex e03c71cacd0..11ea880b151 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -1796,6 +1796,15 @@ GC::Ptr<EnvironmentSettingsObject> EventLoop::environment_settings_object_at(Envreturn m_related_environment_settings_objects.get(address).value_or(nullptr);}+GC::Ptr<EnvironmentSettingsObject> EventLoop::environment_settings_object_with_id(EnvironmentId const& id) const+{+ for (auto const& entry : m_related_environment_settings_objects) {+ if (entry.value->id == id)+ return entry.value;+ }+ return nullptr;+}+// https://html.spec.whatwg.org/multipage/webappapis.html#same-loop-windowsVector<GC::Root<HTML::Window>> EventLoop::same_loop_windows() const{diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h b/Libraries/LibWeb/HTML/EventLoop/EventLoop.hindex e5358f400e1..1b91be04670 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.h@@ -153,6 +153,7 @@ public:void register_environment_settings_object(Badge<EnvironmentSettingsObject>, EnvironmentSettingsObject&);void unregister_environment_settings_object(Badge<EnvironmentSettingsObject>, EnvironmentSettingsObject&);GC::Ptr<EnvironmentSettingsObject> environment_settings_object_at(EnvironmentSettingsObjectAddress) const;+ GC::Ptr<EnvironmentSettingsObject> environment_settings_object_with_id(EnvironmentId const&) const;double compute_deadline() const;diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 19c565bcab1..077c0000670 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -2292,7 +2292,7 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigation}// 3. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then set response to a network error and break. [CSP]- if (ContentSecurityPolicy::should_navigation_request_of_type_be_blocked_by_content_security_policy(state_holder->request, state_holder->csp_navigation_type) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {+ if (ContentSecurityPolicy::should_navigation_request_of_type_be_blocked_by_content_security_policy(state_holder->request, state_holder->csp_navigation_type, state_holder->navigable->page()) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {state_holder->response = Fetch::Infrastructure::ResponseView::network_error("Blocked by Content Security Policy"_string);fetch_completion_steps->function()();return;@@ -2544,8 +2544,12 @@ static void create_navigation_params_by_fetching(// traversable for user prompts: navigable's top-level traversableauto request = Fetch::Infrastructure::Request::create();request->set_url(entry.url);- if (source_snapshot_params->fetch_client.has_value())- request->set_client(Fetch::Fetching::request_client(*source_snapshot_params->fetch_client));+ if (source_snapshot_params->fetch_client.has_value()) {+ auto const& fetch_client = *source_snapshot_params->fetch_client;+ request->set_client(Fetch::Fetching::request_client(fetch_client));+ if (fetch_client.has<NonnullRefPtr<RemoteEnvironmentSettings const>>() && navigation_id.has_value())+ request->set_remote_client_navigation(RemoteClientNavigation { navigable->id(), *navigation_id });+ }request->set_destination(Fetch::Infrastructure::Request::Destination::Document);request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);request->set_use_url_credentials(true);@@ -4167,7 +4171,7 @@ void LocalNavigable::navigate_to_a_javascript_url(NonnullRefPtr<Fetch::Infrastru// 5. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then return.// NB: This can change request's URL, as the require-trusted-types-for pre-navigation check passes the script source// through the default policy.- if (ContentSecurityPolicy::should_navigation_request_of_type_be_blocked_by_content_security_policy(request, csp_navigation_type) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {+ if (ContentSecurityPolicy::should_navigation_request_of_type_be_blocked_by_content_security_policy(request, csp_navigation_type, page()) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {finish_loading_without_navigation();return;}diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.cpp b/Libraries/LibWeb/HTML/Scripting/Environments.cppindex 30f4e3db492..f0c7430e165 100644--- a/Libraries/LibWeb/HTML/Scripting/Environments.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Environments.cpp@@ -414,6 +414,11 @@ GC::Ptr<EnvironmentSettingsObject> environment_settings_object_at(EnvironmentSetreturn main_thread_event_loop().environment_settings_object_at(address);}+GC::Ptr<EnvironmentSettingsObject> environment_settings_object_with_id(EnvironmentId const& id)+{+ return main_thread_event_loop().environment_settings_object_with_id(id);+}+// https://html.spec.whatwg.org/multipage/webappapis.html#incumbent-settings-objectEnvironmentSettingsObject& incumbent_settings_object(){diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.h b/Libraries/LibWeb/HTML/Scripting/Environments.hindex 4fca160bf7a..ef49e6d4147 100644--- a/Libraries/LibWeb/HTML/Scripting/Environments.h+++ b/Libraries/LibWeb/HTML/Scripting/Environments.h@@ -232,6 +232,7 @@ WEB_API bool module_type_allowed(EnvironmentSettingsObject const&, Utf16View modWEB_API void add_module_to_resolved_module_set(EnvironmentSettingsObject&, Utf16View serialized_base_url, Utf16View normalized_specifier, Optional<URL::URL> const& as_url);WEB_API GC::Ptr<EnvironmentSettingsObject> environment_settings_object_at(EnvironmentSettingsObjectAddress);+WEB_API GC::Ptr<EnvironmentSettingsObject> environment_settings_object_with_id(EnvironmentId const&);WEB_API EnvironmentSettingsObject& incumbent_settings_object();WEB_API JS::Realm& incumbent_realm();diff --git a/Libraries/LibWeb/HTML/Scripting/RemoteEnvironmentSettings.h b/Libraries/LibWeb/HTML/Scripting/RemoteEnvironmentSettings.hindex 21c68b0bc93..d8087bd33f7 100644--- a/Libraries/LibWeb/HTML/Scripting/RemoteEnvironmentSettings.h+++ b/Libraries/LibWeb/HTML/Scripting/RemoteEnvironmentSettings.h@@ -7,10 +7,18 @@#pragma once#include <AK/AtomicRefCounted.h>+#include <AK/Utf16String.h>+#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h>namespace Web::HTML {+// A navigation whose request has a client another process hosts, by which the UI process finds that client again.+struct RemoteClientNavigation {+ CrossProcessId navigable_id;+ Utf16String navigation_id;+};+// The settings of an environment another process hosts, as that process serialized them.struct RemoteEnvironmentSettings final : public AtomicRefCounted<RemoteEnvironmentSettings> {static NonnullRefPtr<RemoteEnvironmentSettings const> create(SerializedEnvironmentSettingsObject settings)diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 829371e9ed8..a34dbe056d2 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -63,6 +63,7 @@#include <LibWebCommon/CSS/PreferredColorScheme.h>#include <LibWebCommon/CSS/PreferredContrast.h>#include <LibWebCommon/CSS/PreferredMotion.h>+#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h>#include <LibWebCommon/FileAPI/SerializedBlobURLEntry.h>#include <LibWebCommon/Fullscreen/FullscreenRequestType.h>#include <LibWebCommon/Gamepad/GamepadSnapshot.h>@@ -922,6 +923,8 @@ public:virtual void page_did_report_worker_exception([[maybe_unused]] Utf16String const& message, [[maybe_unused]] Utf16String const& filename, [[maybe_unused]] u32 lineno, [[maybe_unused]] u32 colno) { }// A fetch whose client another process hosts violated the policy at policy_index in that client's CSP list.virtual void page_did_report_violation_of_remote_client([[maybe_unused]] u64 policy_index, [[maybe_unused]] String effective_directive, [[maybe_unused]] URL::URL resource) { }+ // A navigation whose source another process hosts violated the policy at policy_index in the source's CSP list.+ virtual void page_did_report_navigation_violation_of_remote_client([[maybe_unused]] HTML::RemoteClientNavigation const& navigation, [[maybe_unused]] u64 policy_index, [[maybe_unused]] ContentSecurityPolicy::RemoteViolationDirective directive, [[maybe_unused]] bool url_is_https) { }virtual void page_did_register_javascript_source([[maybe_unused]] DOM::Document&, [[maybe_unused]] HTML::ScriptRegistry::Description const&) { }virtual void page_did_post_broadcast_channel_message([[maybe_unused]] HTML::PostedBroadcastChannelMessage const& message) { }diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txtindex 24967e76030..24d44becae0 100644--- a/Libraries/LibWebCommon/CMakeLists.txt+++ b/Libraries/LibWebCommon/CMakeLists.txt@@ -110,6 +110,7 @@ invoke_py_generator("${LADYBIRD_SOURCE_DIR}/Meta/Utils/utils.py")+compile_ipc(ContentSecurityPolicy/RemoteViolationDirective.ipc ContentSecurityPolicy/RemoteViolationDirectiveCodecs.h)compile_ipc(HTML/NavigationResponse.ipc HTML/NavigationResponseCodecs.h)compile_ipc(Page/InputEvent.ipc Page/InputEventCodecs.h)compile_ipc(Page/TextEditingCommand.ipc Page/TextEditingCommandCodecs.h)diff --git a/Libraries/LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h b/Libraries/LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.hnew file mode 100644index 00000000000..2eccca3757f--- /dev/null+++ b/Libraries/LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h@@ -0,0 +1,22 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Types.h>++namespace Web::ContentSecurityPolicy {++// The directive of a violation a navigation found of a policy of its source, which another process hosts.+enum class RemoteViolationDirective : u8 {+ FrameSrc,+ ObjectSrc,+ FormAction,+};++}++#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirectiveCodecs.h>diff --git a/Libraries/LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.ipc b/Libraries/LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.ipcnew file mode 100644index 00000000000..d431aea72a3--- /dev/null+++ b/Libraries/LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.ipc@@ -0,0 +1,10 @@+// Copyright (c) 2026-present, the Ladybird developers.++#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h>++[ExistingCpp]+enum Web::ContentSecurityPolicy::RemoteViolationDirective : u8 {+ FrameSrc,+ ObjectSrc,+ FormAction,+}diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex 2a616895c96..ae4c40c0a41 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -184,7 +184,7 @@ Web::HTML::PreparedNavigationDescriptor CanonicalNavigable::prepare_navigation(U}// Continue the navigate algorithm at step 9 with the values prepared by steps 1-7.-void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescriptor navigation)+void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescriptor navigation, RefPtr<WebContentPage> source_page){auto& traversable = top_level_traversable();auto const& url = navigation.url;@@ -339,6 +339,7 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto.sequence_number = traversable.next_sequence_number(),.state = CanonicalNavigation::CheckingIfUnloadingIsCanceled { move(start_request) },.page = worker,+ .source_page = move(source_page),});worker->async_set_ongoing_navigation(id(), navigation_id);worker->begin_navigation_unload_check(*this, navigation_id);diff --git a/Libraries/LibWebView/CanonicalNavigable.h b/Libraries/LibWebView/CanonicalNavigable.hindex 08767e86114..0d820d90997 100644--- a/Libraries/LibWebView/CanonicalNavigable.h+++ b/Libraries/LibWebView/CanonicalNavigable.h@@ -120,7 +120,7 @@ public:// https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigatevoid navigate(URL::URL, Web::HTML::DocumentResource = {}, Web::Bindings::NavigationHistoryBehavior = Web::Bindings::NavigationHistoryBehavior::Auto);Web::HTML::PreparedNavigationDescriptor prepare_navigation(URL::URL, Web::HTML::DocumentResource = {}, Web::Bindings::NavigationHistoryBehavior = Web::Bindings::NavigationHistoryBehavior::Auto);- void begin_navigation(Web::HTML::PreparedNavigationDescriptor);+ void begin_navigation(Web::HTML::PreparedNavigationDescriptor, RefPtr<WebContentPage> source_page = {});CanonicalBrowsingContext::BrowsingContextAndDocument obtain_a_browsing_context_to_use_for_a_navigation_response(NavigationLoader::ResponseDocument const&);NonnullRefPtr<CanonicalDocument> create_and_initialize_a_document(NavigationLoader::ResponseDocument const&);diff --git a/Libraries/LibWebView/CanonicalNavigation.h b/Libraries/LibWebView/CanonicalNavigation.hindex 1ba02a5c4ac..6fbaa08cfc8 100644--- a/Libraries/LibWebView/CanonicalNavigation.h+++ b/Libraries/LibWebView/CanonicalNavigation.h@@ -76,6 +76,7 @@ public:State state;RefPtr<WebContentPage> page {};RefPtr<CanonicalSessionHistoryEntry> history_entry {};+ RefPtr<WebContentPage> source_page {};};static NonnullRefPtr<CanonicalNavigation> create(Start start){@@ -95,6 +96,8 @@ public:RefPtr<CanonicalSessionHistoryEntry> history_entry {};// Held so that revoking the blob URL the navigation is to cannot take the entry away from it.BlobURLHandle blob_url;+ // The page hosting the source document, as checked when another page requested the navigation.+ RefPtr<WebContentPage> source_page {};RefPtr<WebContentPage> worker() const;RefPtr<WebContentPage> host() const;@@ -112,6 +115,7 @@ private:, state(move(start.state)), page(move(start.page)), history_entry(move(start.history_entry))+ , source_page(move(start.source_page)){}};diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 9f778f69d68..470f1121deb 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -705,11 +705,13 @@ void WebContentPage::did_request_navigation_of_navigable(Web::HTML::CrossProcess// again, with the sourceDocument and sandboxing flags it holds. sourceDocument can be in another tab, in this// process's page for it.Optional<CanonicalNavigable&> source;+ RefPtr<WebContentPage> source_page;client().for_each_page([&](WebContentPage& page) {auto navigable = page.traversable().find(source_navigable_id);if (!navigable.has_value() || navigable->active_document().id() != source_document_id || navigable->active_document().host() != &page)return IterationDecision::Continue;source = *navigable;+ source_page = page;return IterationDecision::Break;});if (!source.has_value())@@ -735,7 +737,54 @@ void WebContentPage::did_request_navigation_of_navigable(Web::HTML::CrossProcess// 3. Set initiatorOriginSnapshot to sourceDocument's origin.navigation.initiator_origin_snapshot = source_document.origin();- target->begin_navigation(move(navigation));+ target->begin_navigation(move(navigation), move(source_page));+}++static bool navigation_can_violate(Web::ContentSecurityPolicy::RemoteViolationDirective directive, CanonicalNavigable const& navigable, Web::HTML::NavigationPopulationRequest const& request)+{+ switch (directive) {+ case Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc:+ case Web::ContentSecurityPolicy::RemoteViolationDirective::ObjectSrc:+ return !navigable.is_top_level_traversable();+ case Web::ContentSecurityPolicy::RemoteViolationDirective::FormAction:+ return request.csp_navigation_type == Web::ContentSecurityPolicy::Directives::NavigationType::FormSubmission;+ }+ VERIFY_NOT_REACHED();+}++// The process populating a navigation reports a violation of a policy of its source, which goes to the page found+// hosting the source when the navigation was requested, while that page still hosts it.+void WebContentPage::did_report_navigation_violation(Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective directive, bool url_is_https)+{+ auto navigable = population_worker_navigable(navigable_id);+ if (!navigable.has_value())+ return;+ auto navigation = navigable->navigation_with_id(navigation_id);+ auto* creating = navigation ? navigation->state.get_pointer<CanonicalNavigation::CreatingNavigationParams>() : nullptr;+ if (!creating || navigation->worker() != this)+ return;++ auto const& request = creating->loader->request();+ auto const& fetch_client = request.source_snapshot_params.fetch_client;+ if (!fetch_client.has_value() || !navigation_can_violate(directive, *navigable, request)) {+ client().did_misbehave("did_report_navigation_violation"sv, "violation the navigation cannot have"sv);+ return;+ }++ auto const& source_page = navigation->source_page;+ if (!source_page || !source_page->is_open() || !source_page->hosted_environment(fetch_client->id).has_value())+ return;++ // The request's URL can be upgraded from http to https before the check, by upgrade-insecure-requests or HSTS, so+ // the report then names the upgraded URL.+ auto url = request.history_entry.url;+ if (url_is_https && url.scheme() == "http"sv) {+ url.set_scheme("https"_string);+ // NB: Unlike the URL parser, setting the scheme does not remove a port that is the new scheme's default port.+ if (url.port() == 443)+ url.set_port({});+ }+ source_page->async_report_violation_of_environment(fetch_client->id, policy_index, directive, move(url));}void WebContentPage::did_post_message_to_navigable(Web::HTML::CrossProcessId navigable_id, Web::HTML::PostedMessageDescriptor posted_message)diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 55025504e1f..cc930b8b12d 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -185,6 +185,7 @@ private:virtual void did_request_navigation_of_navigable(Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId source_navigable_id, Web::HTML::CrossProcessId source_document_id, Web::HTML::PreparedNavigationDescriptor navigation) override;virtual void did_post_message_to_navigable(Web::HTML::CrossProcessId navigable_id, Web::HTML::PostedMessageDescriptor posted_message) override;+ virtual void did_report_navigation_violation(Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective, bool url_is_https) override;virtual void did_request_focusing_steps_for_navigable(Web::HTML::CrossProcessId navigable_id, Web::HTML::FocusTrigger focus_trigger) override;virtual void did_request_window_focus_of_navigable(Web::HTML::CrossProcessId navigable_id) override;virtual void did_request_set_opener_of_navigable(Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId opener_navigable_id) override;diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex a488a708f2c..1d4e584fbe0 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -307,6 +307,12 @@ void ConnectionFromClient::deliver_posted_message(Web::PageId page_id, Web::HTMLpage->deliver_posted_message(navigable_id, move(message));}+void ConnectionFromClient::report_violation_of_environment(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective directive, URL::URL resource)+{+ if (auto page = this->page(page_id); page.has_value())+ page->report_violation_of_environment(environment_id, policy_index, directive, move(resource));+}+void ConnectionFromClient::close_traversable_from_script(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id){auto page = this->page(page_id);diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex b46c0a8246e..833b50f7098 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -131,6 +131,7 @@ private:virtual void create_navigation_params(Web::PageId page_id, Web::HTML::NavigationPopulationRequest) override;virtual void cancel_navigation_params_creation(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id) override;virtual void deliver_posted_message(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::MessageDescriptor) override;+ virtual void report_violation_of_environment(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective, URL::URL resource) override;virtual void close_traversable_from_script(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) override;virtual void run_focusing_steps_for_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::FocusTrigger) override;virtual void focus_window_of_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 7b75dcee2cc..20ec6a66875 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -31,6 +31,7 @@#include <LibWeb/CSS/StyleSheetImport.h>#include <LibWeb/CSS/StyleSheetState.h>#include <LibWeb/Compositor/CompositorHost.h>+#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>#include <LibWeb/DOM/CharacterData.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>@@ -49,6 +50,8 @@#include <LibWeb/HTML/NavigableContainer.h>#include <LibWeb/HTML/RemoteNavigable.h>#include <LibWeb/HTML/Scripting/ClassicScript.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/RemoteEnvironmentSettings.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/SessionHistoryEntry.h>#include <LibWeb/HTML/TextDirectiveGenerator.h>@@ -316,6 +319,14 @@ void PageClient::deliver_posted_message(Web::HTML::CrossProcessId navigable_id,navigable->deliver_posted_message_from_another_process(move(message));}+void PageClient::report_violation_of_environment(Web::HTML::EnvironmentId const& environment_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective directive, URL::URL resource)+{+ auto settings = Web::HTML::environment_settings_object_with_id(environment_id);+ if (!settings)+ return;+ Web::ContentSecurityPolicy::report_a_violation_found_in_another_process(*settings, policy_index, directive, move(resource));+}+void PageClient::navigation_params_creation_finished(Web::HTML::LocalNavigable& navigable, Web::HTML::NavigationPopulationRequest request, Web::HTML::NavigationPopulationResult result){client().async_did_finish_navigation_params_creation(m_id, navigable.id(), request.navigation_id, move(result));@@ -1598,6 +1609,12 @@ void PageClient::page_did_post_broadcast_channel_message(Web::HTML::PostedBroadcclient().async_did_post_broadcast_channel_message(m_id, message);}+// The UI process passes the violation on to the process hosting the navigation's source, while it still hosts it.+void PageClient::page_did_report_navigation_violation_of_remote_client(Web::HTML::RemoteClientNavigation const& navigation, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective directive, bool url_is_https)+{+ client().async_did_report_navigation_violation(m_id, navigation.navigable_id, navigation.navigation_id, policy_index, directive, url_is_https);+}+void PageClient::page_did_update_resource_count(i32 count_waiting){client().async_did_update_resource_count(m_id, count_waiting);diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex e09d1607dcf..38aebe9e93f 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -151,6 +151,7 @@ public:void did_receive_unload_check_result(Web::HTML::CrossProcessId check_id, Web::HTML::CheckIfUnloadingIsCanceledResult);void create_navigation_params(Web::HTML::NavigationPopulationRequest);void deliver_posted_message(Web::HTML::CrossProcessId navigable_id, Web::HTML::MessageDescriptor);+ void report_violation_of_environment(Web::HTML::EnvironmentId const&, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective, URL::URL resource);void cancel_navigation_params_creation(Web::HTML::CrossProcessId navigable_id, Utf16String const& navigation_id);void populate_navigation(Web::HTML::NavigationPopulationRequest, Web::HTML::NavigationPopulationResult);void cancel_download(u64 download_id);@@ -391,6 +392,7 @@ private:virtual void page_did_finish_network_request(u64 request_id, u64 body_size, Requests::RequestTimingInfo const&, Optional<Requests::NetworkError> const&) override;virtual void page_did_register_javascript_source(Web::DOM::Document&, Web::HTML::ScriptRegistry::Description const&) override;virtual void page_did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage const&) override;+ virtual void page_did_report_navigation_violation_of_remote_client(Web::HTML::RemoteClientNavigation const&, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective, bool url_is_https) override;void setup_palette();ConnectionFromClient& client() const;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 10faa6dfa6e..8d48d136cfe 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -20,6 +20,7 @@#include <LibWebCommon/CSS/StyleSheetIdentifier.h>#include <LibWebCommon/Clipboard/SystemClipboard.h>#include <LibWebCommon/ContentSecurityPolicy/Directives/NavigationType.h>+#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h>#include <LibWebCommon/Fetch/Infrastructure/HTTP/RequestPriority.h>#include <LibWebCommon/FileAPI/SerializedBlobURLEntry.h>#include <LibWebCommon/Fullscreen/FullscreenRequestType.h>@@ -90,6 +91,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_complete_navigation_unload_check(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id) =|did_request_navigation_of_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId source_navigable_id, Web::HTML::CrossProcessId source_document_id, Web::HTML::PreparedNavigationDescriptor navigation) =|did_post_message_to_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::PostedMessageDescriptor message) =|+ did_report_navigation_violation(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective directive, bool url_is_https) =|did_request_close_of_traversable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId source_navigable_id, Web::HTML::NavigationSourceSnapshot source_snapshot) =|did_request_focusing_steps_for_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::FocusTrigger focus_trigger) =|did_request_window_focus_of_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) =|diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex a029936f714..40a836bb3ac 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -14,6 +14,7 @@#include <LibWebCommon/CSS/StyleSheetIdentifier.h>#include <LibWebCommon/Clipboard/SystemClipboard.h>#include <LibWebCommon/ContentSecurityPolicy/Directives/NavigationType.h>+#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h>#include <LibWebCommon/Fullscreen/FullscreenRequestType.h>#include <LibWebCommon/Gamepad/GamepadSnapshot.h>#include <LibWebCommon/Gamepad/GamepadStateBuffer.h>@@ -108,6 +109,7 @@ endpoint WebContentServer routed by Web::PageId page_idcreate_navigation_params(Web::PageId page_id, Web::HTML::NavigationPopulationRequest request) =|cancel_navigation_params_creation(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Utf16String navigation_id) =|deliver_posted_message(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::MessageDescriptor message) =|+ report_violation_of_environment(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, u64 policy_index, Web::ContentSecurityPolicy::RemoteViolationDirective directive, URL::URL resource) =|close_traversable_from_script(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) =|run_focusing_steps_for_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::FocusTrigger focus_trigger) =|focus_window_of_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) =|diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-csp-violation-is-reported-in-the-source.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-csp-violation-is-reported-in-the-source.txtnew file mode 100644index 00000000000..6d7f31911a4--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-csp-violation-is-reported-in-the-source.txt@@ -0,0 +1,5 @@+securitypolicyviolation in the source: frame-src, disposition: enforce, blocked URL matches: true, document URL matches: true+sibling navigated+WebContent#0+ iframe#0: remote WebContent#1+ iframe#1: remote WebContent#2diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-csp-violation-names-the-navigations-url.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-csp-violation-names-the-navigations-url.txtnew file mode 100644index 00000000000..dbbb694b161--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-csp-violation-names-the-navigations-url.txt@@ -0,0 +1,2 @@+After a redirect, the violation names the navigation's first URL: true+Under upgrade-insecure-requests, the violation names the https URL: truediff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-form-action-violation-is-reported-in-the-source.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-form-action-violation-is-reported-in-the-source.txtnew file mode 100644index 00000000000..7f4e2d5721f--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-form-action-violation-is-reported-in-the-source.txt@@ -0,0 +1,5 @@+securitypolicyviolation in the source: form-action, disposition: enforce, blocked URL path matches: true, document URL matches: true+sibling navigated+WebContent#0+ iframe#0: remote WebContent#1+ iframe#1: remote WebContent#2diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-csp-violation-is-reported-in-the-source.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-csp-violation-is-reported-in-the-source.htmlnew file mode 100644index 00000000000..93d28398c59--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-csp-violation-is-reported-in-the-source.html@@ -0,0 +1,91 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script>+ // An isolated iframe's frame-src blocks its navigation of a sibling that another process hosts. The process+ // fetching for the sibling finds the violation, and the source iframe sees it as a securitypolicyviolation event.+ promiseTest(async () => {+ const httpServer = httpTestServer();+ const runId = uniqueID();+ const targetHostname = uniqueLocalhostHostname("reported-violation-target");++ const echo = async (path, headers, body, hostname) => {+ const url = new URL(+ await httpServer.createEcho("GET", path, {+ status: 200,+ headers: { "Content-Type": "text/html", ...headers },+ body,+ })+ );+ url.hostname = hostname;+ return url;+ };++ const targetFirstUrl = await echo(`/reported-violation-target-first-${runId}`, {}, "<!DOCTYPE html>first", targetHostname);+ const targetSecondUrl = await echo(+ `/reported-violation-target-second-${runId}`,+ {},+ `<!DOCTYPE html><script>top.postMessage("sibling navigated", "*");<\/script>`,+ targetHostname+ );+ const blockedUrl = await echo(+ `/reported-violation-blocked-${runId}`,+ {},+ `<!DOCTYPE html><script>top.postMessage("blocked navigation went through", "*");<\/script>`,+ uniqueLocalhostHostname("reported-violation-blocked")+ );+ const sourceUrl = await echo(+ `/reported-violation-source-${runId}`,+ { "Content-Security-Policy": `frame-src ${targetSecondUrl.origin}` },+ `<!DOCTYPE html>+ <a id="blocked" target="target" href="${blockedUrl.href}">blocked</a>+ <a id="allowed" target="target" href="${targetSecondUrl.href}">allowed</a>+ <script>+ document.addEventListener("securitypolicyviolation", event => {+ top.postMessage([+ "securitypolicyviolation in the source: " + event.effectiveDirective,+ "disposition: " + event.disposition,+ "blocked URL matches: " + (event.blockedURI === "${blockedUrl.href}"),+ "document URL matches: " + (event.documentURI === location.href),+ ].join(", "), "*");+ });+ addEventListener("message", () => document.getElementById("allowed").click());+ document.getElementById("blocked").click();+ <\/script>`,+ uniqueLocalhostHostname("reported-violation-source")+ );++ const target = document.createElement("iframe");+ target.name = "target";+ target.src = targetFirstUrl;+ document.body.appendChild(target);+ await new Promise(resolve => (target.onload = resolve));++ const messages = [];+ let violationReported;+ const reported = new Promise(resolve => (violationReported = resolve));+ const navigated = new Promise(resolve => {+ addEventListener("message", event => {+ messages.push(event.data);+ if (event.data.startsWith("securitypolicyviolation"))+ violationReported();+ if (event.data === "sibling navigated")+ resolve();+ });+ });+ const blockedNavigationLoaded = new Promise(resolve => target.addEventListener("load", resolve, { once: true }));++ const source = document.createElement("iframe");+ source.src = sourceUrl;+ document.body.appendChild(source);++ // The source navigates the sibling again only once its blocked navigation has finished.+ await reported;+ await blockedNavigationLoaded;+ source.contentWindow.postMessage("navigate the sibling", "*");+ await navigated;++ for (const message of messages)+ println(message);+ println(internals.dumpSiteIsolationProcessTree().trimEnd());+ });+</script>diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-csp-violation-names-the-navigations-url.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-csp-violation-names-the-navigations-url.htmlnew file mode 100644index 00000000000..3667e808f02--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-csp-violation-names-the-navigations-url.html@@ -0,0 +1,91 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script>+ // A violation that the process fetching for an isolated sibling finds names the URL the navigation started with:+ // not a later redirect's, and upgraded to https when the source's upgrade-insecure-requests upgrades it.+ promiseTest(async () => {+ const httpServer = httpTestServer();+ const runId = uniqueID();+ const targetHostname = uniqueLocalhostHostname("named-violation-target");++ const echo = async (path, options, hostname) => {+ const url = new URL(await httpServer.createEcho("GET", path, options));+ url.hostname = hostname;+ return url;+ };+ const html = body => ({ status: 200, headers: { "Content-Type": "text/html" }, body });++ const targetUrl = await echo(`/named-violation-target-${runId}`, html("<!DOCTYPE html>target"), targetHostname);+ const blockedUrl = await echo(+ `/named-violation-blocked-${runId}`,+ html(`<!DOCTYPE html><script>top.postMessage("blocked navigation went through", "*");<\/script>`),+ uniqueLocalhostHostname("named-violation-blocked")+ );+ const redirectUrl = await echo(+ `/named-violation-redirect-${runId}`,+ { status: 302, headers: { Location: blockedUrl.href }, body: "" },+ targetHostname+ );++ const target = document.createElement("iframe");+ target.name = "target";+ target.src = targetUrl;+ document.body.appendChild(target);+ await new Promise(resolve => (target.onload = resolve));++ const messages = [];+ addEventListener("message", event => messages.push(event.data));++ // The source navigates the sibling once, and posts the blocked URL of each violation it sees.+ const blockedURIOfNavigation = async (name, policy, href) => {+ const sourceUrl = await echo(+ `/named-violation-source-${name}-${runId}`,+ {+ status: 200,+ headers: { "Content-Type": "text/html", "Content-Security-Policy": policy },+ body: `<!DOCTYPE html>+ <a id="navigate" target="target" href="${href}">navigate</a>+ <script>+ document.addEventListener("securitypolicyviolation", event => {+ top.postMessage({ name: "${name}", blockedURI: event.blockedURI }, "*");+ });+ document.getElementById("navigate").click();+ <\/script>`,+ },+ uniqueLocalhostHostname(`named-violation-source-${name}`)+ );++ const reported = new Promise(resolve => {+ addEventListener("message", function receive(event) {+ if (event.data?.name !== name)+ return;+ removeEventListener("message", receive);+ resolve(event.data.blockedURI);+ });+ });+ const source = document.createElement("iframe");+ source.src = sourceUrl;+ document.body.appendChild(source);+ const blockedURI = await reported;+ source.remove();+ return blockedURI;+ };++ const afterRedirect = await blockedURIOfNavigation("redirect", `frame-src ${targetUrl.origin}`, redirectUrl.href);+ println(`After a redirect, the violation names the navigation's first URL: ${afterRedirect === redirectUrl.href}`);++ const upgradedUrl = new URL(blockedUrl);+ upgradedUrl.protocol = "https:";+ const upgraded = await blockedURIOfNavigation(+ "upgraded",+ `upgrade-insecure-requests; frame-src ${targetUrl.origin}`,+ blockedUrl.href+ );+ println(`Under upgrade-insecure-requests, the violation names the https URL: ${upgraded === upgradedUrl.href}`);++ for (const message of messages) {+ if (typeof message === "string")+ println(message);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-form-action-violation-is-reported-in-the-source.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-form-action-violation-is-reported-in-the-source.htmlnew file mode 100644index 00000000000..7b719c499ba--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-form-action-violation-is-reported-in-the-source.html@@ -0,0 +1,91 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script>+ // An isolated iframe's form-action blocks a form it submits to a sibling that another process hosts. The process+ // fetching for the sibling finds the violation, and the source iframe sees it as a securitypolicyviolation event.+ promiseTest(async () => {+ const httpServer = httpTestServer();+ const runId = uniqueID();+ const targetHostname = uniqueLocalhostHostname("form-action-target");++ const echo = async (path, headers, body, hostname) => {+ const url = new URL(+ await httpServer.createEcho("GET", path, {+ status: 200,+ headers: { "Content-Type": "text/html", ...headers },+ body,+ })+ );+ url.hostname = hostname;+ return url;+ };++ const targetFirstUrl = await echo(`/form-action-target-first-${runId}`, {}, "<!DOCTYPE html>first", targetHostname);+ const targetSecondUrl = await echo(+ `/form-action-target-second-${runId}`,+ {},+ `<!DOCTYPE html><script>top.postMessage("sibling navigated", "*");<\/script>`,+ targetHostname+ );+ const blockedUrl = await echo(+ `/form-action-blocked-${runId}`,+ {},+ `<!DOCTYPE html><script>top.postMessage("blocked form submission went through", "*");<\/script>`,+ uniqueLocalhostHostname("form-action-blocked")+ );+ const sourceUrl = await echo(+ `/form-action-source-${runId}`,+ { "Content-Security-Policy": `form-action ${targetSecondUrl.origin}` },+ `<!DOCTYPE html>+ <form id="blocked" target="target" method="GET" action="${blockedUrl.href}"></form>+ <a id="allowed" target="target" href="${targetSecondUrl.href}">allowed</a>+ <script>+ document.addEventListener("securitypolicyviolation", event => {+ top.postMessage([+ "securitypolicyviolation in the source: " + event.effectiveDirective,+ "disposition: " + event.disposition,+ "blocked URL path matches: " + (new URL(event.blockedURI).pathname === "${blockedUrl.pathname}"),+ "document URL matches: " + (event.documentURI === location.href),+ ].join(", "), "*");+ });+ addEventListener("message", () => document.getElementById("allowed").click());+ document.getElementById("blocked").submit();+ <\/script>`,+ uniqueLocalhostHostname("form-action-source")+ );++ const target = document.createElement("iframe");+ target.name = "target";+ target.src = targetFirstUrl;+ document.body.appendChild(target);+ await new Promise(resolve => (target.onload = resolve));++ const messages = [];+ let violationReported;+ const reported = new Promise(resolve => (violationReported = resolve));+ const navigated = new Promise(resolve => {+ addEventListener("message", event => {+ messages.push(event.data);+ if (event.data.startsWith("securitypolicyviolation"))+ violationReported();+ if (event.data === "sibling navigated")+ resolve();+ });+ });+ const blockedNavigationLoaded = new Promise(resolve => target.addEventListener("load", resolve, { once: true }));++ const source = document.createElement("iframe");+ source.src = sourceUrl;+ document.body.appendChild(source);++ // The source navigates the sibling again only once its blocked navigation has finished.+ await reported;+ await blockedNavigationLoaded;+ source.contentWindow.postMessage("navigate the sibling", "*");+ await navigated;++ for (const message of messages)+ println(message);+ println(internals.dumpSiteIsolationProcessTree().trimEnd());+ });+</script>diff --git a/Tests/LibWebCommon/CMakeLists.txt b/Tests/LibWebCommon/CMakeLists.txtindex a4ae7caf552..84348eca3d3 100644--- a/Tests/LibWebCommon/CMakeLists.txt+++ b/Tests/LibWebCommon/CMakeLists.txt@@ -5,6 +5,7 @@ set(TEST_SOURCESTestInsecureRequestsPolicy.cppTestKeyEvent.cppTestPermissionsPolicy.cpp+ TestRemoteViolationDirective.cppTestSiteCompatibility.cppTestStorageEndpoint.cppTestStorageKey.cpp@@ -21,5 +22,6 @@ target_link_libraries(TestGamepadStateBuffer PRIVATE LibCore LibIPC)target_link_libraries(TestInsecureRequestsPolicy PRIVATE LibIPC)target_link_libraries(TestKeyEvent PRIVATE LibIPC)target_link_libraries(TestPermissionsPolicy PRIVATE LibHTTP LibIPC LibURL)+target_link_libraries(TestRemoteViolationDirective PRIVATE LibIPC)target_link_libraries(TestStorageEndpoint PRIVATE LibIPC)target_link_libraries(TestStorageKey PRIVATE LibURL)diff --git a/Tests/LibWebCommon/TestRemoteViolationDirective.cpp b/Tests/LibWebCommon/TestRemoteViolationDirective.cppnew file mode 100644index 00000000000..775795592d4--- /dev/null+++ b/Tests/LibWebCommon/TestRemoteViolationDirective.cpp@@ -0,0 +1,37 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/MemoryStream.h>+#include <LibIPC/Decoder.h>+#include <LibIPC/Encoder.h>+#include <LibTest/TestCase.h>+#include <LibWebCommon/ContentSecurityPolicy/RemoteViolationDirective.h>++using Web::ContentSecurityPolicy::RemoteViolationDirective;++template<typename T>+static ErrorOr<RemoteViolationDirective> decode_directive_from(T const& value)+{+ IPC::MessageBuffer message;+ IPC::Encoder encoder { message };+ MUST(encoder.encode(value));+ Queue<IPC::Attachment> attachments;+ FixedMemoryStream stream { message.data().span() };+ IPC::Decoder decoder { stream, attachments };+ return decoder.decode<RemoteViolationDirective>();+}++TEST_CASE(directives_survive_ipc)+{+ for (auto directive : { RemoteViolationDirective::FrameSrc, RemoteViolationDirective::ObjectSrc, RemoteViolationDirective::FormAction })+ EXPECT_EQ(MUST(decode_directive_from(directive)), directive);+}++TEST_CASE(a_value_the_declaration_does_not_list_is_refused)+{+ EXPECT(decode_directive_from<u8>(3).is_error());+ EXPECT(decode_directive_from<u8>(255).is_error());+}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 46ea770b984..2e43cbb183f 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -399,6 +399,13 @@ if (NOT WIN32)target_compile_definitions(TestRendererOriginClaims PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")endif()+ add_executable(TestRendererViolationReports TestRendererViolationReports.cpp)+ add_dependencies(TestRendererViolationReports ladybird_build_resource_files ${ladybird_helper_processes})+ target_link_libraries(TestRendererViolationReports PRIVATE AK LibCore LibFileSystem LibGfx LibIPC LibMain LibThreading LibURL LibWeb LibWebView)+ if (APPLE)+ target_compile_definitions(TestRendererViolationReports PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")+ endif()+add_executable(TestImageDecoderIsolation TestImageDecoderIsolation.cpp)add_dependencies(TestImageDecoderIsolation ladybird_build_resource_files ${ladybird_helper_processes})target_link_libraries(TestImageDecoderIsolation PRIVATE AK LibCore LibFileSystem LibGfx LibIPC LibMain LibWebView)@@ -493,6 +500,8 @@ if (BUILD_TESTING AND NOT WIN32)set_tests_properties(TestRendererCookieAccess PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})add_test(NAME TestRendererOriginClaims COMMAND $<TARGET_FILE:TestRendererOriginClaims>)set_tests_properties(TestRendererOriginClaims PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})+ add_test(NAME TestRendererViolationReports COMMAND $<TARGET_FILE:TestRendererViolationReports>)+ set_tests_properties(TestRendererViolationReports PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})add_test(NAME TestImageDecoderIsolation COMMAND $<TARGET_FILE:TestImageDecoderIsolation>)set_tests_properties(TestImageDecoderIsolation PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})add_test(NAME TestCrashReportSubmission COMMAND $<TARGET_FILE:TestCrashReportSubmission>)diff --git a/Tests/LibWebView/TestRendererViolationReports.cpp b/Tests/LibWebView/TestRendererViolationReports.cppnew file mode 100644index 00000000000..a582ddb1ec8--- /dev/null+++ b/Tests/LibWebView/TestRendererViolationReports.cpp@@ -0,0 +1,426 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <AK/Atomic.h>+#include <AK/HashMap.h>+#include <AK/LexicalPath.h>+#include <AK/Random.h>+#include <AK/ScopeGuard.h>+#include <AK/StringBuilder.h>+#include <LibCore/Directory.h>+#include <LibCore/Environment.h>+#include <LibCore/EventLoop.h>+#include <LibCore/StandardPaths.h>+#include <LibCore/System.h>+#include <LibCore/Timer.h>+#include <LibFileSystem/FileSystem.h>+#include <LibGfx/SystemTheme.h>+#include <LibMain/Main.h>+#include <LibThreading/Thread.h>+#include <LibURL/Parser.h>+#include <LibWebView/Application.h>+#include <LibWebView/CanonicalEnvironmentSettingsObject.h>+#include <LibWebView/CanonicalNavigable.h>+#include <LibWebView/CanonicalNavigation.h>+#include <LibWebView/CanonicalTraversable.h>+#include <LibWebView/CanonicalWindow.h>+#include <LibWebView/HeadlessWebView.h>+#include <LibWebView/Utilities.h>+#include <LibWebView/WebContentClient.h>+#include <LibWebView/WebContentPage.h>+#include <netinet/in.h>+#include <signal.h>+#include <sys/socket.h>++namespace {++class TestApplication : public WebView::Application {+ WEB_VIEW_APPLICATION(TestApplication)++public:+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)+ : WebView::Application(move(ladybird_binary_path))+ {+ }++ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options) override+ {+ browser_options.headless_mode = WebView::HeadlessMode::Test;+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;+ web_content_options.is_test_mode = WebView::IsTestMode::Yes;+ }++ virtual bool should_coordinate_browser_process() const override { return false; }+};++struct Page {+ ByteString headers;+ ByteString body;+};++// Answers each path with its page, leaves a request for /held unanswered while the server lives, and counts the+// requests for /violation-report and /report-barrier.+class TestHttpServer {+public:+ explicit TestHttpServer(HashMap<ByteString, Page> pages)+ : m_pages(move(pages))+ {+ m_socket = MUST(Core::System::socket(AF_INET, SOCK_STREAM, 0));++ int reuse_address = 1;+ MUST(Core::System::setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_address, sizeof(reuse_address)));++ sockaddr_in address {};+ address.sin_family = AF_INET;+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ MUST(Core::System::bind(m_socket, reinterpret_cast<sockaddr*>(&address), sizeof(address)));+ MUST(Core::System::listen(m_socket, 16));++ socklen_t address_size = sizeof(address);+ VERIFY(::getsockname(m_socket, reinterpret_cast<sockaddr*>(&address), &address_size) == 0);+ m_port = ntohs(address.sin_port);++ m_thread = Threading::Thread::construct("TestHttpServer"sv, [this] -> intptr_t {+ run();+ return 0;+ });+ m_thread->start();+ }++ ~TestHttpServer()+ {+ m_shutting_down.store(true);+ wake_server();+ (void)m_thread->join();+ for (auto client : m_held_clients)+ (void)Core::System::close(client);+ (void)Core::System::close(m_socket);+ }++ URL::URL url(StringView host, StringView path) const+ {+ return URL::Parser::basic_parse(ByteString::formatted("http://{}:{}{}", host, m_port, path)).release_value();+ }++ size_t violation_reports() const { return m_violation_reports.load(); }+ size_t report_barriers() const { return m_report_barriers.load(); }++private:+ void run()+ {+ while (!m_shutting_down.load()) {+ auto client = ::accept(m_socket, nullptr, nullptr);+ if (client < 0)+ return;+ if (respond(client))+ m_held_clients.append(client);+ else+ (void)Core::System::close(client);+ }+ }++ void wake_server()+ {+ auto socket = Core::System::socket(AF_INET, SOCK_STREAM, 0);+ if (socket.is_error())+ return;++ sockaddr_in address {};+ address.sin_family = AF_INET;+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ address.sin_port = htons(m_port);+ (void)::connect(socket.value(), reinterpret_cast<sockaddr*>(&address), sizeof(address));+ (void)Core::System::close(socket.value());+ }++ // Returns whether the request is held, unanswered.+ bool respond(int client)+ {+ StringBuilder request;+ Array<u8, 4096> buffer;+ while (!request.string_view().contains("\r\n\r\n"sv)) {+ auto read = Core::System::read(client, buffer);+ if (read.is_error() || read.value() == 0)+ return false;+ request.append(StringView { buffer.span().trim(read.value()) });+ }++ auto request_line = request.string_view().split_view("\r\n"sv).first().split_view(' ');+ if (request_line.size() < 2)+ return false;+ auto path = request_line[1];+ if (path == "/held"sv)+ return true;+ if (path == "/violation-report"sv)+ m_violation_reports.fetch_add(1);+ if (path == "/report-barrier"sv)+ m_report_barriers.fetch_add(1);++ auto page = m_pages.get(path);+ auto response = page.has_value()+ ? ByteString::formatted("HTTP/1.1 200 OK\r\n{}Content-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", page->headers, page->body.length(), page->body)+ : ByteString { "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"sv };+ (void)write_all(client, response.bytes());+ return false;+ }++ static bool write_all(int fd, ReadonlyBytes bytes)+ {+ while (!bytes.is_empty()) {+ auto written = Core::System::write(fd, bytes);+ if (written.is_error() || written.value() == 0)+ return false;+ bytes = bytes.slice(written.value());+ }+ return true;+ }++ HashMap<ByteString, Page> m_pages;+ Vector<int> m_held_clients;+ int m_socket { -1 };+ u16 m_port { 0 };+ RefPtr<Threading::Thread> m_thread;+ Atomic<bool> m_shutting_down { false };+ Atomic<size_t> m_violation_reports { 0 };+ Atomic<size_t> m_report_barriers { 0 };+};++bool spin_until_or_timeout(Function<bool()> condition, int timeout_ms)+{+ bool timed_out = false;+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(timeout_ms), [&] { timed_out = true; });+ timer->start();+ Core::EventLoop::current().spin_until([&] { return condition() || timed_out; });+ return condition();+}++void expect(bool condition, StringView what)+{+ if (condition)+ return;+ warnln("FAIL: {}", what);+ VERIFY_NOT_REACHED();+}++// The liar's page holds a child frame whose document has the given environment's id.+void claim_environment(WebView::HeadlessWebView& liar, Web::HTML::EnvironmentId const& environment_id, u64 namespace_id)+{+ auto& stub = static_cast<WebContentClientStub&>(liar.page().client());+ auto& traversable = liar.traversable();++ Web::HTML::PendingSessionHistoryEntryDescriptor initial_history_entry;+ initial_history_entry.url = URL::about_blank();+ initial_history_entry.document_state.id = { .namespace_id = namespace_id, .local_id = 1 };++ Web::HTML::CrossProcessId frame_id { .namespace_id = namespace_id, .local_id = 2 };+ Web::HTML::CrossProcessId document_id { .namespace_id = namespace_id, .local_id = 3 };+ stub.did_create_child_frame(liar.page().id(), traversable.id(), traversable.active_document().id(), frame_id, {}, move(initial_history_entry), URL::Origin::create_opaque(), environment_id, document_id);+ expect(liar.page().hosted_environment(environment_id).has_value(), "a liar claims the source's environment"sv);+}++}++// A violation of a policy of a navigation's source is reported in the page the UI process found hosting the source+// document when the navigation was requested, whichever other pages claim the source's environment. The navigation's+// population worker is terminated for a report of a directive its kind of navigation rules out, such as form-action+// outside a form submission; a report from another page, or for a navigation the worker is not running, is dropped.++ErrorOr<int> ladybird_main(Main::Arguments arguments)+{+ auto test_config_directory = ByteString::formatted("{}/Ladybird-TestRendererViolationReports-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid());+ TRY(Core::Directory::create(test_config_directory, Core::Directory::CreateDirectories::Yes));+ auto cleanup_test_config_directory = ScopeGuard([&] {+ MUST(FileSystem::remove(test_config_directory, FileSystem::RecursionMode::Allowed));+ });+ MUST(Core::Environment::set("XDG_CONFIG_HOME"sv, test_config_directory, Core::Environment::Overwrite::Yes));++ signal(SIGPIPE, SIG_IGN);++#if defined(LADYBIRD_BINARY_PATH)+ auto app = TRY(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));+#else+ auto app = TRY(TestApplication::create(arguments, OptionalNone {}));+#endif++ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);+ auto theme = TRY(Gfx::load_system_theme(theme_path.string()));++ // The source's policy allows its frame's own site only. Each load of the frame and each violation retitles it.+ HashMap<ByteString, Page> pages;+ pages.set("/source"sv, {+ .headers = "Content-Security-Policy: frame-src http://target.test:*\r\n",+ .body = R"(<!DOCTYPE html><body><script>+ let loads = 0;+ let violations = 0;+ document.addEventListener("securitypolicyviolation", event => (document.title = `violation ${++violations}: ${event.effectiveDirective}`));+ const frame = document.createElement("iframe");+ frame.name = "target";+ frame.onload = () => (document.title = `loaded ${++loads}`);+ frame.src = `http://target.test:${location.port}/target`;+ document.body.append(frame);+ function navigateTarget(host, path) {+ const link = document.createElement("a");+ link.target = "target";+ link.href = `http://${host}:${location.port}${path}`;+ document.body.append(link);+ link.click();+ }+ </script>)",+ });+ pages.set("/target"sv, { .headers = {}, .body = "<!DOCTYPE html>target" });++ // A source frame beside its sibling, in a parent of its own origin that keeps the source's document alive once+ // the source navigates away. A violation of the source's policy posts to /violation-report.+ pages.set("/frames"sv, { .headers = {}, .body = R"(<!DOCTYPE html><body><script>+ let sourceLoads = 0;+ let siblingLoads = 0;+ const sourceFrame = document.createElement("iframe");+ sourceFrame.onload = () => (document.title = `source loaded ${++sourceLoads}`);+ sourceFrame.src = "/source-frame";+ const sibling = document.createElement("iframe");+ sibling.name = "sibling";+ sibling.onload = () => (document.title = `sibling loaded ${++siblingLoads}`);+ sibling.src = `http://target.test:${location.port}/target`;+ document.body.append(sourceFrame, sibling);+ function replaceSource() {+ window.replacedSourceDocument = sourceFrame.contentDocument;+ sourceFrame.contentWindow.replacedSourceGlobal = true;+ sourceFrame.onload = () => (document.title = `source replaced, ${"replacedSourceGlobal" in sourceFrame.contentWindow ? "same" : "new"} global`);+ sourceFrame.src = "/source-replacement";+ }+ </script>)" });+ pages.set("/source-frame"sv, {+ .headers = "Content-Security-Policy: frame-src http://target.test:*; report-uri /violation-report\r\n",+ .body = R"(<!DOCTYPE html><body><script>+ function navigateSibling(host, path) {+ const link = document.createElement("a");+ link.target = "sibling";+ link.href = `http://${host}:${location.port}${path}`;+ document.body.append(link);+ link.click();+ }+ </script>)",+ });+ pages.set("/source-replacement"sv, { .headers = {}, .body = "<!DOCTYPE html>replacement" });+ TestHttpServer server { move(pages) };++ Vector<NonnullOwnPtr<WebView::HeadlessWebView>> liars;+ auto create_liar = [&] {+ auto liar = WebView::HeadlessWebView::create(theme, { 800, 600 });+ bool loaded = false;+ liar->on_load_finish = [&](auto const&) { loaded = true; };+ liar->load(server.url("liar.test"sv, "/target"sv));+ expect(spin_until_or_timeout([&] { return loaded; }, 10'000), "a liar's page loads"sv);+ liar->on_load_finish = {};+ liars.append(move(liar));+ };++ // Liars are created both before and after the source.+ create_liar();+ create_liar();+ auto source_view = WebView::HeadlessWebView::create(theme, { 800, 600 });+ create_liar();+ create_liar();++ Vector<ByteString> titles;+ source_view->on_title_change = [&](auto const& title) { titles.append(title.to_utf8().to_byte_string()); };+ auto saw_title = [&](StringView title) { return titles.contains_slow(title); };++ source_view->load(server.url("source.test"sv, "/source"sv));+ expect(spin_until_or_timeout([&] { return saw_title("loaded 1"sv); }, 10'000), "the source's frame loads"sv);++ auto& target = *source_view->traversable().children().first();+ auto environment_id = source_view->traversable().active_document().relevant_global_object().relevant_settings_object().id();+ for (size_t i = 0; i < liars.size(); ++i)+ claim_environment(*liars[i], environment_id, 0xfeed0000 + i);++ source_view->run_javascript("navigateTarget('blocked.test', '/blocked')"_string);+ expect(spin_until_or_timeout([&] { return saw_title("violation 1: frame-src"sv) && saw_title("loaded 2"sv); }, 10'000), "the source sees the violation of its frame-src"sv);++ source_view->run_javascript("navigateTarget('target.test', '/held')"_string);+ RefPtr<WebView::CanonicalNavigation> held_navigation;+ expect(spin_until_or_timeout([&] {+ held_navigation = target.uncommitted_navigation();+ return held_navigation && held_navigation->state.has<WebView::CanonicalNavigation::CreatingNavigationParams>();+ },+ 10'000),+ "the frame's navigation is fetching"sv);++ // The page running a navigation's population is its worker.+ auto worker = held_navigation->page;+ auto& source_page = source_view->page();+ expect(worker && &worker->client() != &source_page.client(), "another renderer runs the frame's navigation"sv);++ auto report = [&](WebView::WebContentPage& page, WebView::CanonicalNavigable& navigable, Utf16String navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective directive, u64 policy_index = 0) {+ auto& stub = static_cast<WebContentClientStub&>(page.client());+ stub.did_report_navigation_violation(page.id(), navigable.id(), move(navigation_id), policy_index, directive, false);+ };++ report(*worker, target, "not-the-navigation"_utf16, Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc);+ expect(worker->client().is_open(), "a report for another navigation is dropped"sv);++ report(source_page, target, held_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc);+ expect(source_page.client().is_open(), "a report from a page that is not the navigation's worker is dropped"sv);++ // The source reports only for its policy at the given index, and only one governing the directive. Both channels+ // keep their order, so the last report's violation comes after every earlier report's.+ report(*worker, target, held_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc, 7);+ report(*worker, target, held_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::ObjectSrc);+ report(*worker, target, held_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc);+ report(*worker, target, held_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc);+ expect(spin_until_or_timeout([&] { return saw_title("violation 3: frame-src"sv); }, 10'000), "the source reports the reports for its governing policy"sv);+ expect(!any_of(titles, [](auto const& title) { return title.contains("object-src"sv); }), "the source drops a report its policy does not govern"sv);+ expect(saw_title("violation 2: frame-src"sv), "the source drops a report for a policy it does not have"sv);++ report(*worker, target, held_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::FormAction);+ expect(!worker->client().is_open(), "the worker is terminated for a directive the navigation cannot violate"sv);++ // A source replaced while its navigation runs is no longer reported in, though its document is still alive.+ auto frames_view = WebView::HeadlessWebView::create(theme, { 800, 600 });+ Vector<ByteString> frames_titles;+ frames_view->on_title_change = [&](auto const& title) { frames_titles.append(title.to_utf8().to_byte_string()); };+ auto frames_saw_title = [&](StringView title) { return frames_titles.contains_slow(title); };++ frames_view->load(server.url("source.test"sv, "/frames"sv));+ expect(spin_until_or_timeout([&] { return frames_saw_title("source loaded 1"sv) && frames_saw_title("sibling loaded 1"sv); }, 10'000), "the source and its sibling load"sv);++ frames_view->run_javascript("sourceFrame.contentWindow.navigateSibling('blocked.test', '/blocked')"_string);+ expect(spin_until_or_timeout([&] { return server.violation_reports() == 1; }, 10'000), "the source posts its violation's report"sv);++ frames_view->run_javascript("sourceFrame.contentWindow.navigateSibling('target.test', '/held')"_string);+ RefPtr<WebView::CanonicalNavigation> sibling_navigation;+ WebView::CanonicalNavigable* sibling = nullptr;+ expect(spin_until_or_timeout([&] {+ for (auto& child : frames_view->traversable().children()) {+ auto navigation = child->uncommitted_navigation();+ if (navigation && navigation->state.has<WebView::CanonicalNavigation::CreatingNavigationParams>()) {+ sibling_navigation = navigation;+ sibling = child.ptr();+ return true;+ }+ }+ return false;+ },+ 10'000),+ "the sibling's navigation is fetching"sv);+ auto sibling_worker = sibling_navigation->page;+ expect(sibling_worker && &sibling_worker->client() != &frames_view->page().client(), "another renderer runs the sibling's navigation"sv);++ frames_view->run_javascript("replaceSource()"_string);+ expect(spin_until_or_timeout([&] { return frames_saw_title("source replaced, new global"sv); }, 10'000), "the source is replaced by a document with an environment of its own"sv);++ // Listeners on a replaced document do not run, but a report its policy sent would reach the report endpoint soon+ // after a request the parent makes in a later task.+ report(*sibling_worker, *sibling, sibling_navigation->navigation_id, Web::ContentSecurityPolicy::RemoteViolationDirective::FrameSrc);+ frames_view->run_javascript("setTimeout(() => fetch('/report-barrier', { method: 'POST', keepalive: true }))"_string);+ expect(spin_until_or_timeout([&] { return server.report_barriers() == 1; }, 10'000), "the parent makes a request in a later task"sv);+ expect(!spin_until_or_timeout([&] { return server.violation_reports() > 1; }, 500), "a report for a replaced source is dropped"sv);+ expect(sibling_worker->client().is_open(), "a report for a replaced source is no fault of its worker"sv);++ outln("PASS: violation reports reach the source's page, and a report of a directive the navigation rules out terminates its renderer");+ return 0;+}