Truly independent web browser
LibWeb: Keep a fetch's WebDriver BiDi network state with its agent
Luke Wildeefc15d623b03
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 40cd7541086..193e6c6d15d 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -629,7 +629,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamauto request = fetch_params.request();if (WebDriver::BiDi::network_events_enabled())- WebDriver::BiDi::initialize_network_request(*request);+ WebDriver::BiDi::initialize_network_request(fetch_params);// 2. Let response be null.RefPtr<Infrastructure::Response> response;@@ -1739,8 +1739,6 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParamif (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {// 1. Let requestForServiceWorker be a clone of request.auto request_for_service_worker = request->clone();- if (WebDriver::BiDi::network_events_enabled() || WebDriver::BiDi::network_configuration_enabled())- request_for_service_worker->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());// 2. If requestForServiceWorker’s body is non-null, then:if (!request_for_service_worker->body().has<Empty>()) {@@ -2036,10 +2034,7 @@ GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm& realm, Infrastructure::F// 1. Set request’s method to `GET` and request’s body to null.request->set_method("GET"sv);request->set_body({});- if (auto state = request->webdriver_bidi_network_request(); state && state->request_header_overrides) {- request->header_list()->delete_("Content-Length"sv);- state->request_header_overrides->delete_("Content-Length"sv);- }+ WebDriver::BiDi::remove_network_request_content_length_override(fetch_params);static constexpr Array request_body_header_names {"Content-Encoding"sv,@@ -2346,9 +2341,8 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&response->set_url_list(http_request->url_list());if (WebDriver::BiDi::network_events_enabled()) {- // NB: Instrumentation may have been enabled after httpRequest was cloned. The controller's original- // request must share the identity reported by the prepared request, including on cancellation.- WebDriver::BiDi::synchronize_network_request(*fetch_params->request(), *http_request);+ // NB: Instrumentation may have been enabled after httpRequest was cloned.+ WebDriver::BiDi::initialize_network_request_with_its_navigable(*http_fetch_params);auto intercepts = WebDriver::BiDi::get_network_intercepts(*http_fetch_params, "responseStarted"sv);if (!response->is_network_error() && !intercepts.is_empty()) {WebDriver::BiDi::block_network_request(*http_fetch_params, response, "responseStarted"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), GC::create_function(realm.heap(), GC::captures(realm, fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials), [](auto& realm, auto& fetch_params, auto& http_request, auto& returned_pending_response, auto& is_authentication_fetch, auto& is_new_connection_fetch, auto& include_credentials, WebDriver::BiDi::NetworkContinuationAction, RefPtr<Infrastructure::Response> continued_response) {@@ -2376,10 +2370,10 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastruauto request = fetch_params.request();if (WebDriver::BiDi::network_events_enabled())- WebDriver::BiDi::initialize_network_request(*request);+ WebDriver::BiDi::initialize_network_request(fetch_params);if (WebDriver::BiDi::network_configuration_enabled())- WebDriver::BiDi::apply_network_cache_behavior(*request);+ WebDriver::BiDi::apply_network_cache_behavior(fetch_params);// 2. Let httpFetchParams be null.RefPtr<Infrastructure::FetchParams const> http_fetch_params;@@ -2425,8 +2419,6 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// source is null as only a single body is needed in that case. E.g., when request’s body’s source// is null, redirects and authentication will end up failing the fetch.http_request = request->clone();- // NB: Existing interception overrides still apply after subscriptions or intercepts are removed.- http_request->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());// 2. Set httpFetchParams to a copy of fetchParams.auto new_http_fetch_params = Infrastructure::FetchParams::copy(fetch_params);@@ -2632,9 +2624,10 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// FIXME: 22. If there’s a proxy-authentication entry, use it as appropriate.// NOTE: This intentionally does not depend on httpRequest’s credentials mode.- WebDriver::BiDi::apply_network_request_header_overrides(*http_request);+ // NB: Existing interception overrides still apply after subscriptions or intercepts are removed.+ WebDriver::BiDi::apply_network_request_header_overrides(*http_fetch_params);if (WebDriver::BiDi::network_configuration_enabled())- WebDriver::BiDi::apply_network_extra_headers(*http_request);+ WebDriver::BiDi::apply_network_extra_headers(*http_fetch_params);// 23. Set httpCache to the result of determining the HTTP cache partition, given httpRequest.http_cache = determine_the_http_cache_partition(*http_request);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex 5a10ab0cf01..a177067f427 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -88,6 +88,12 @@ void FetchController::set_original_fetch_params(Badge<FetchParams>, FetchParamsm_original_fetch_params = fetch_params;}+void FetchController::set_network_observation(Badge<FetchParams>, NonnullRefPtr<NetworkObservation> network_observation)+{+ VERIFY(!m_network_observation);+ m_network_observation = move(network_observation);+}+void FetchController::report_webdriver_bidi_fetch_error(StringView error_text) const{if (!WebDriver::BiDi::network_events_enabled())diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.hindex 477633b8142..5cc67d25fea 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h@@ -20,6 +20,7 @@#include <LibWeb/Fetch/Infrastructure/FetchControlBlock.h>#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>+#include <LibWeb/Fetch/Infrastructure/NetworkObservation.h>#include <LibWeb/Fetch/Infrastructure/Task.h>#include <LibWeb/Forward.h>#include <LibWeb/HTML/EventLoop/Task.h>@@ -73,6 +74,10 @@ public:void set_original_fetch_params(Badge<FetchParams>, FetchParams const&);[[nodiscard]] RefPtr<FetchParams> original_fetch_params() const;+ // The network observation of the request the controller's fetch params were created with.+ void set_network_observation(Badge<FetchParams>, NonnullRefPtr<NetworkObservation>);+ [[nodiscard]] RefPtr<NetworkObservation> const& network_observation() const { return m_network_observation; }+[[nodiscard]] TaskDestination const& task_destination() const { return m_task_destination; }void set_task_destination(TaskDestination task_destination) { m_task_destination = move(task_destination); }@@ -118,6 +123,7 @@ private:FetchControllerToken m_token;NonnullRefPtr<FetchControlBlock> m_control_block;WeakPtr<FetchParams> m_original_fetch_params;+ RefPtr<NetworkObservation> m_network_observation;// https://fetch.spec.whatwg.org/#fetch-controller-report-timing-steps// report timing steps (default null)diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cppindex da918aafa72..7b1ad17fdd2 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp@@ -19,6 +19,7 @@ FetchParams::FetchParams(NonnullRefPtr<Request> request, GC::Ref<FetchAlgorithms{controller.set_algorithms({}, algorithms);controller.set_original_fetch_params({}, *this);+ controller.set_network_observation({}, m_request->ensure_network_observation());}FetchParams::FetchParams(FetchParams const& params)diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cppindex 741a22b6628..11c1babb512 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp@@ -15,7 +15,6 @@#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>#include <LibWeb/HTML/LocalTraversableNavigable.h>#include <LibWeb/HTML/PolicyContainers.h>-#include <LibWeb/WebDriver/BiDi/Network.h>namespace Web::Fetch::Infrastructure {@@ -39,14 +38,11 @@ Request::Request(NonnullRefPtr<HTTP::HeaderList> header_list)Request::~Request() = default;-RefPtr<WebDriver::BiDi::NetworkRequest> Request::webdriver_bidi_network_request() const+NonnullRefPtr<NetworkObservation> Request::ensure_network_observation(){- return m_webdriver_bidi_network_request;-}--void Request::set_webdriver_bidi_network_request(RefPtr<WebDriver::BiDi::NetworkRequest> state)-{- m_webdriver_bidi_network_request = move(state);+ if (!m_network_observation)+ m_network_observation = NetworkObservation::create();+ return *m_network_observation;}// https://fetch.spec.whatwg.org/#concept-request-urldiff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.hindex f6ac3eb1e58..ffc251545c0 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h@@ -30,6 +30,7 @@#include <LibWeb/Fetch/Infrastructure/HTTP.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>#include <LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h>+#include <LibWeb/Fetch/Infrastructure/NetworkObservation.h>#include <LibWeb/HTML/Scripting/EnvironmentSettingsObjectAddress.h>#include <LibWeb/HTML/Scripting/RemoteEnvironmentSettings.h>#include <LibWebCommon/Fetch/Infrastructure/HTTP/RequestPriority.h>@@ -37,12 +38,6 @@#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>-namespace Web::WebDriver::BiDi {--class NetworkRequest;--}-namespace Web::Fetch::Infrastructure {class Response;@@ -358,8 +353,8 @@ public:UnixDateTime request_time() const { return m_request_time; }- RefPtr<WebDriver::BiDi::NetworkRequest> webdriver_bidi_network_request() const;- void set_webdriver_bidi_network_request(RefPtr<WebDriver::BiDi::NetworkRequest>);+ [[nodiscard]] RefPtr<NetworkObservation> const& network_observation() const { return m_network_observation; }+ [[nodiscard]] NonnullRefPtr<NetworkObservation> ensure_network_observation();private:explicit Request(NonnullRefPtr<HTTP::HeaderList>);@@ -586,7 +581,7 @@ private:// Non-standardUnixDateTime m_request_time;- RefPtr<WebDriver::BiDi::NetworkRequest> m_webdriver_bidi_network_request;+ RefPtr<NetworkObservation> m_network_observation;};WEB_API StringView request_destination_to_string(Request::Destination);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/NetworkObservation.h b/Libraries/LibWeb/Fetch/Infrastructure/NetworkObservation.hnew file mode 100644index 00000000000..5cae98f4e2d--- /dev/null+++ b/Libraries/LibWeb/Fetch/Infrastructure/NetworkObservation.h@@ -0,0 +1,43 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/NonnullRefPtr.h>+#include <AK/RefCounted.h>+#include <AK/RefPtr.h>+#include <LibGC/Forward.h>++namespace Web::Fetch::Infrastructure {++// What a network observer keeps for one request, opaque to Fetch.+class NetworkObserverState : public RefCounted<NetworkObserverState> {+public:+ GC_HOLDS_NO_CELL_EDGES;++ virtual ~NetworkObserverState() = default;++protected:+ NetworkObserverState() = default;+};++// The network observer state of a request, which the request shares with the controller of each of its fetches.+class NetworkObservation final : public RefCounted<NetworkObservation> {+public:+ GC_HOLDS_NO_CELL_EDGES;++ [[nodiscard]] static NonnullRefPtr<NetworkObservation> create() { return adopt_ref(*new NetworkObservation); }++ [[nodiscard]] RefPtr<NetworkObserverState> const& observer_state() const { return m_observer_state; }+ void set_observer_state(NonnullRefPtr<NetworkObserverState> observer_state) { m_observer_state = move(observer_state); }++private:+ NetworkObservation() = default;++ RefPtr<NetworkObserverState> m_observer_state;+};++}diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cppindex d3c6664a4b0..aa6aac0ea48 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp@@ -90,30 +90,34 @@ static HashMap<String, GC::Root<NetworkContinuation>>& blocked_requests()return *requests;}-static GC::Ptr<NetworkContinuation> blocked_request(Request const& request)+static RefPtr<NetworkRequest> network_request_of(RefPtr<NetworkObservation> const& observation){- auto state = request.webdriver_bidi_network_request();- if (!state)+ if (!observation)return nullptr;- auto it = blocked_requests().find(state->id);+ return static_cast<NetworkRequest*>(observation->observer_state().ptr());+}++// The state of the request the fetch was started with.+static RefPtr<NetworkRequest> network_request_of(FetchParams const& fetch_params)+{+ return network_request_of(fetch_params.controller()->network_observation());+}++static GC::Ptr<NetworkContinuation> blocked_request(NetworkRequest const& state)+{+ auto it = blocked_requests().find(state.id);return it == blocked_requests().end() ? nullptr : it->value.ptr();}static GC::Ptr<NetworkContinuation> blocked_request(FetchController const& controller){- auto fetch_params = controller.original_fetch_params();- if (!fetch_params)+ auto state = network_request_of(controller.network_observation());+ if (!state)return nullptr;- auto blocked = blocked_request(*fetch_params->request());+ auto blocked = blocked_request(*state);return blocked && blocked->controller.ptr() == &controller ? blocked : nullptr;}-static void share_blocked_request_identity(FetchParams const& fetch_params)-{- if (auto blocked = blocked_request(*fetch_params.controller()))- fetch_params.request()->set_webdriver_bidi_network_request(blocked->fetch_params->request()->webdriver_bidi_network_request());-}-static void stop_response_transport(FetchController& controller, Response const& response){response.release_request_transfer_lease();@@ -141,7 +145,6 @@ static void cancel_network_interception_impl(FetchParams const& fetch_params, Stauto blocked = blocked_request(*fetch_params.controller());if (!blocked)return;- share_blocked_request_identity(fetch_params);resume_blocked_request(blocked->request_id, NetworkContinuationAction::Fail, Response::network_error(String::from_utf8_with_replacement_character(error_text)));}@@ -172,9 +175,9 @@ static GC::Ptr<HTML::LocalNavigable> navigable_of(NetworkRequest const& state)return HTML::local_navigable_with_id(*state.navigable_id);}-static GC::Ptr<HTML::Navigable> request_navigable(Request const& request)+static GC::Ptr<HTML::Navigable> request_navigable(NetworkRequest const* state, Request const& request){- if (auto state = request.webdriver_bidi_network_request())+ if (state)return navigable_of(*state);if (auto const& client = request.client_snapshot(); client && client->navigable_id.has_value())return HTML::local_navigable_with_id(*client->navigable_id);@@ -190,14 +193,15 @@ static String network_context_id(HTML::Navigable& navigable)}// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-cache-behavior-void apply_network_cache_behavior(Request& request)+void apply_network_cache_behavior(FetchParams const& fetch_params){auto const& state = session_state();+ auto request = fetch_params.request();auto behavior = state.network_default_cache_behavior;- if (auto navigable = request_navigable(request))+ if (auto navigable = request_navigable(network_request_of(fetch_params).ptr(), *request))behavior = state.network_navigable_cache_behavior.get(network_context_id(*navigable)).value_or(behavior);if (behavior == "bypass"sv)- request.set_cache_mode(HTTP::CacheMode::NoStore);+ request->set_cache_mode(HTTP::CacheMode::NoStore);}// https://w3c.github.io/webdriver-bidi/#update-request-headers@@ -212,33 +216,44 @@ static constexpr Array fetch_generated_request_header_names {"Sec-Fetch-User"sv,};-void apply_network_request_header_overrides(Request& request)+void apply_network_request_header_overrides(FetchParams const& fetch_params){- auto state = request.webdriver_bidi_network_request();+ auto state = network_request_of(fetch_params);if (!state || !state->request_header_overrides)return;+ auto request = fetch_params.request();for (auto name : fetch_generated_request_header_names) {if (!state->request_header_overrides->contains(name))continue;- request.header_list()->delete_(name);+ request->header_list()->delete_(name);for (auto const& header : *state->request_header_overrides) {if (header.name.equals_ignoring_ascii_case(name))- request.header_list()->append(header);+ request->header_list()->append(header);}}}-void apply_network_extra_headers(Request& request)+void remove_network_request_content_length_override(FetchParams const& fetch_params)+{+ auto state = network_request_of(fetch_params);+ if (!state || !state->request_header_overrides)+ return;+ fetch_params.request()->header_list()->delete_("Content-Length"sv);+ state->request_header_overrides->delete_("Content-Length"sv);+}++void apply_network_extra_headers(FetchParams const& fetch_params){auto const& state = session_state();+ auto request = fetch_params.request();// https://w3c.github.io/webdriver-bidi/#update-headersauto update_headers = [&](auto const& headers) {for (auto const& header : headers)- request.header_list()->set(header);+ request->header_list()->set(header);};// 2. Update headers with request and session's extra headers' default headersupdate_headers(state.network_default_headers);- if (auto navigable = request_navigable(request)) {+ if (auto navigable = request_navigable(network_request_of(fetch_params).ptr(), *request)) {if (auto it = state.network_user_context_headers.find("default"_string); it != state.network_user_context_headers.end())update_headers(it->value);auto id = network_context_id(*navigable);@@ -254,16 +269,16 @@ JsonArray get_network_intercepts(FetchParams const& fetch_params, StringView phaif (session_state().network_intercepts.is_empty() || !is_event_enabled(MUST(String::formatted("network.{}", phase))))return intercepts;auto request = fetch_params.request();- auto state = request->webdriver_bidi_network_request();+ auto state = network_request_of(fetch_params);if (state && ((phase == "beforeRequestSent"sv && state->before_request_sent.contains(request->redirect_count())) || (phase == "responseStarted"sv && state->response_started.contains(request->redirect_count()))))return intercepts;// NB: An existing request keeps its original context. A request first observed after instrumentation was// enabled can still discover its context, and blocking must use that same context.- auto navigable = request_navigable(*request);+ auto navigable = request_navigable(state.ptr(), *request);if (!navigable || fetch_params.is_canceled() || fetch_params.control_block().state() == FetchControlBlock::State::Stopped)return intercepts;if (!state)- initialize_network_request(*request, navigable);+ initialize_network_request(fetch_params, navigable);auto context = network_context_id(*navigable);auto event_name = MUST(String::formatted("network.{}", phase));auto scope = session_state().enabled_event_contexts.find(event_name);@@ -286,9 +301,9 @@ NetworkRequest::NetworkRequest(){}-void initialize_network_request(Request& request, GC::Ptr<HTML::Navigable> navigable, Optional<Utf16String> const& navigation)+static void initialize_network_request(NetworkObservation& observation, Request const& request, GC::Ptr<HTML::Navigable> navigable, Optional<Utf16String> const& navigation){- if ((!g_network_events_enabled && !g_network_configuration_enabled) || request.webdriver_bidi_network_request())+ if ((!g_network_events_enabled && !g_network_configuration_enabled) || observation.observer_state())return;auto state = NetworkRequest::create();if (navigable)@@ -297,20 +312,28 @@ void initialize_network_request(Request& request, GC::Ptr<HTML::Navigable> navigstate->navigable_id = client->navigable_id;if (navigation.has_value())state->navigation = navigation->to_utf8();- request.set_webdriver_bidi_network_request(state);+ observation.set_observer_state(state);}-void synchronize_network_request(Request& original, Request& prepared)+void initialize_network_request(Request& request, GC::Ptr<HTML::Navigable> navigable, Optional<Utf16String> const& navigation){- auto state = original.webdriver_bidi_network_request();- if (!state)- state = prepared.webdriver_bidi_network_request();- if (!state) {- initialize_network_request(original, request_navigable(original));- state = original.webdriver_bidi_network_request();- }- original.set_webdriver_bidi_network_request(state);- prepared.set_webdriver_bidi_network_request(state);+ if (!g_network_events_enabled && !g_network_configuration_enabled)+ return;+ initialize_network_request(*request.ensure_network_observation(), request, navigable, navigation);+}++void initialize_network_request(FetchParams const& fetch_params, GC::Ptr<HTML::Navigable> navigable)+{+ auto observation = fetch_params.controller()->network_observation();+ VERIFY(observation);+ initialize_network_request(*observation, *fetch_params.request(), navigable, {});+}++void initialize_network_request_with_its_navigable(FetchParams const& fetch_params)+{+ if (network_request_of(fetch_params))+ return;+ initialize_network_request(fetch_params, request_navigable(nullptr, *fetch_params.request()));}// https://w3c.github.io/webdriver-bidi/#serialize-protocol-bytes@@ -385,10 +408,10 @@ static JsonObject get_the_fetch_timings(Request const& request, FetchTimingInfo}// https://w3c.github.io/webdriver-bidi/#get-the-request-data-static JsonObject get_the_request_data(Request const& request, FetchTimingInfo const& timings)+static JsonObject get_the_request_data(NetworkRequest const& state, Request const& request, FetchTimingInfo const& timings){JsonObject result;- result.set("request"sv, request.webdriver_bidi_network_request()->id);+ result.set("request"sv, state.id);result.set("url"sv, request.current_url().serialize());result.set("method"sv, MUST(String::from_utf8(request.method().view())));// NB: RequestServer sends one field per name, combining repeated values in order.@@ -510,23 +533,22 @@ static JsonObject get_the_response_data(Response const& response, FetchTimingInf}// https://w3c.github.io/webdriver-bidi/#process-a-network-event-static JsonObject process_a_network_event(HTML::Navigable const& navigable, Request const& request, FetchTimingInfo const& timing_info)+static JsonObject process_a_network_event(HTML::Navigable const& navigable, NetworkRequest const& state, Request const& request, FetchTimingInfo const& timing_info){- auto state = request.webdriver_bidi_network_request();JsonObject params;params.set("context"sv, navigable_id(navigable));params.set("userContext"sv, "default"sv);- auto blocked = blocked_request(request);+ auto blocked = blocked_request(state);params.set("isBlocked"sv, blocked != nullptr);if (blocked)params.set("intercepts"sv, blocked->intercepts);- params.set("navigation"sv, state->navigation.has_value() ? JsonValue(*state->navigation) : JsonValue {});+ params.set("navigation"sv, state.navigation.has_value() ? JsonValue(*state.navigation) : JsonValue {});params.set("redirectCount"sv, request.redirect_count());JsonObject request_data;- if (auto cached = state->request_data.get(request.redirect_count()); cached.has_value())+ if (auto cached = state.request_data.get(request.redirect_count()); cached.has_value())request_data = *cached;else- request_data = get_the_request_data(request, timing_info);+ request_data = get_the_request_data(state, request, timing_info);request_data.set("timings"sv, get_the_fetch_timings(request, timing_info));params.set("request"sv, move(request_data));params.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());@@ -535,16 +557,8 @@ static JsonObject process_a_network_event(HTML::Navigable const& navigable, Requvoid block_network_request(FetchParams const& fetch_params, RefPtr<Fetch::Infrastructure::Response> response, String phase, JsonArray intercepts, GC::Ref<NetworkContinuation> continuation, RefPtr<Fetch::Infrastructure::Request> original_request){- auto request = fetch_params.request();- // NB: Cancellation runs through the controller's original parameters, rather than a prepared HTTP clone.- // Bind both requests to the same identity before exposing a blocked request.- if (auto original_params = fetch_params.controller()->original_fetch_params()) {- synchronize_network_request(*original_params->request(), *request);- if (!original_request)- original_request = original_params->request();- }- initialize_network_request(*request);- auto state = request->webdriver_bidi_network_request();+ initialize_network_request(fetch_params);+ auto state = network_request_of(fetch_params);if (fetch_params.is_canceled() || fetch_params.control_block().state() == FetchControlBlock::State::Stopped) {if (response)stop_response_transport(*fetch_params.controller(), *response);@@ -565,8 +579,6 @@ void block_network_request(FetchParams const& fetch_params, RefPtr<Fetch::Infrascontinuation->controller = fetch_params.controller();continuation->original_request = original_request;continuation->response = response;- if (original_request)- original_request->set_webdriver_bidi_network_request(state);blocked_requests().set(state->id, GC::make_root(continuation));if (continuation->phase == "beforeRequestSent"sv) {network_before_request_sent(fetch_params);@@ -598,7 +610,7 @@ static ErrorOr<JsonValue, Error> continue_network_request_impl(StringView methodreturn Error::from_code(ErrorCode::InvalidArgument, "Command does not apply to the blocked phase"sv);auto overrides = TRY(Network::deserialize_interception_overrides(method, params));auto request = blocked->fetch_params->request();- auto state = request->webdriver_bidi_network_request();+ auto state = network_request_of(*blocked->fetch_params);auto response = blocked->response;auto action = NetworkContinuationAction::Continue;if (method == "network.continueRequest"sv) {@@ -646,7 +658,7 @@ static ErrorOr<JsonValue, Error> continue_network_request_impl(StringView methodrequest->header_list()->set({ "Content-Length"sv, ByteString::number(*body.length()) });}- state->request_data.set(request->redirect_count(), get_the_request_data(*request, *blocked->fetch_params->timing_info()));+ state->request_data.set(request->redirect_count(), get_the_request_data(*state, *request, *blocked->fetch_params->timing_info()));if (params.has("url"sv) || params.has("method"sv) || params.has("headers"sv) || params.has("body"sv) || params.has("cookies"sv))action = NetworkContinuationAction::ContinueWithModifiedRequest;} else if (method == "network.failRequest"sv) {@@ -729,10 +741,9 @@ WebDriver::Response continue_network_request(StringView method, JsonObject const// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-before-request-sentvoid network_before_request_sent(FetchParams const& fetch_params){- share_blocked_request_identity(fetch_params);auto request = fetch_params.request();- initialize_network_request(*request);- auto state = request->webdriver_bidi_network_request();+ initialize_network_request(fetch_params);+ auto state = network_request_of(fetch_params);if (!state || state->before_request_sent.contains(request->redirect_count()))return;auto navigable = navigable_of(*state);@@ -741,9 +752,9 @@ void network_before_request_sent(FetchParams const& fetch_params)// 4. Let redirect count be request's redirect count.// 5. Add redirect count to before request sent map[request].state->before_request_sent.set(request->redirect_count());- state->request_data.set(request->redirect_count(), get_the_request_data(*request, *fetch_params.timing_info()));+ state->request_data.set(request->redirect_count(), get_the_request_data(*state, *request, *fetch_params.timing_info()));if (is_event_enabled("network.beforeRequestSent"sv))- emit_event(*navigable, "network.beforeRequestSent"_string, process_a_network_event(*navigable, *fetch_params.request(), *fetch_params.timing_info()));+ emit_event(*navigable, "network.beforeRequestSent"_string, process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info()));}// https://w3c.github.io/webdriver-bidi/#event-network-responseStarted@@ -751,7 +762,7 @@ void network_response_started(FetchParams const& fetch_params, Response& respons{network_before_request_sent(fetch_params);auto request = fetch_params.request();- auto state = request->webdriver_bidi_network_request();+ auto state = network_request_of(fetch_params);if (!state || state->response_started.contains(request->redirect_count()) || response.is_network_error())return;auto navigable = navigable_of(*state);@@ -760,7 +771,7 @@ void network_response_started(FetchParams const& fetch_params, Response& responsstate->response_started.set(request->redirect_count());// 5. Let sessions be the set of sessions for which an event is enabled given "network.responseStarted" and related navigables.if (is_event_enabled("network.responseStarted"sv)) {- auto params = process_a_network_event(*navigable, *fetch_params.request(), *fetch_params.timing_info());+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));emit_event(*navigable, "network.responseStarted"_string, move(params));}@@ -769,13 +780,13 @@ void network_response_started(FetchParams const& fetch_params, Response& respons// https://w3c.github.io/webdriver-bidi/#event-network-authRequiredvoid network_auth_required(FetchParams const& fetch_params, Response const& response){- auto state = fetch_params.request()->webdriver_bidi_network_request();+ auto state = network_request_of(fetch_params);if (!state || !is_event_enabled("network.authRequired"sv))return;auto navigable = navigable_of(*state);if (!navigable)return;- auto params = process_a_network_event(*navigable, *fetch_params.request(), *fetch_params.timing_info());+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));emit_event(*navigable, "network.authRequired"_string, move(params));}@@ -784,7 +795,7 @@ void network_auth_required(FetchParams const& fetch_params, Response const& respvoid network_response_completed(FetchParams const& fetch_params, Response const& response){auto request = fetch_params.request();- auto state = request->webdriver_bidi_network_request();+ auto state = network_request_of(fetch_params);if (!state || (state->completed.contains(request->redirect_count()) || state->transferred.contains(request->redirect_count())))return;auto navigable = navigable_of(*state);@@ -796,7 +807,7 @@ void network_response_completed(FetchParams const& fetch_params, Response const&// 5. Let sessions be the set of sessions for which an event is enabled given "network.responseCompleted" and related navigables.if (!is_event_enabled("network.responseCompleted"sv))return;- auto params = process_a_network_event(*navigable, *fetch_params.request(), *fetch_params.timing_info());+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));emit_event(*navigable, "network.responseCompleted"_string, move(params));}@@ -807,7 +818,7 @@ void network_fetch_error(FetchParams const& fetch_params, StringView error_text)// 1. If before request sent map[request] does not contain request's redirect count, then run the WebDriver BiDi before request sent steps with request.network_before_request_sent(fetch_params);auto request = fetch_params.request();- auto state = request->webdriver_bidi_network_request();+ auto state = network_request_of(fetch_params);bool is_first_terminal = state && !state->completed.contains(request->redirect_count()) && !state->transferred.contains(request->redirect_count());if (is_first_terminal)state->completed.set(request->redirect_count());@@ -819,7 +830,7 @@ void network_fetch_error(FetchParams const& fetch_params, StringView error_text)return;if (!is_event_enabled("network.fetchError"sv))return;- auto params = process_a_network_event(*navigable, *fetch_params.request(), *fetch_params.timing_info());+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());// 4.2. Set the errorText field of params to an implementation-defined string describing the error which caused the request to be aborted.params.set("errorText"sv, String::from_utf8_with_replacement_character(error_text));emit_event(*navigable, "network.fetchError"_string, move(params));@@ -830,7 +841,7 @@ Optional<JsonObject> network_response_for_navigation(Request const& request, Fet{if (!g_network_events_enabled)return {};- auto state = request.webdriver_bidi_network_request();+ auto state = network_request_of(request.network_observation());if (!state || state->completed.contains(request.redirect_count()))return {};auto navigable = navigable_of(*state);@@ -838,7 +849,7 @@ Optional<JsonObject> network_response_for_navigation(Request const& request, Fetreturn {};state->transferred.set(request.redirect_count());JsonObject result;- result.set("parameters"sv, process_a_network_event(*navigable, request, timing_info));+ result.set("parameters"sv, process_a_network_event(*navigable, *state, request, timing_info));result.set("response"sv, get_the_response_data(response, timing_info));result.set("postRedirectStartTime"sv, timing_info.post_redirect_start_time());auto const& client = request.client_snapshot();diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.h b/Libraries/LibWeb/WebDriver/BiDi/Network.hindex f965f1b3a8a..d5dfa350fad 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Network.h+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.h@@ -20,6 +20,7 @@#include <LibGC/Ptr.h>#include <LibHTTP/HeaderList.h>#include <LibJS/Heap/Cell.h>+#include <LibWeb/Fetch/Infrastructure/NetworkObservation.h>#include <LibWeb/Forward.h>#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebCommon/WebDriver/Response.h>@@ -66,7 +67,7 @@ private:// https://w3c.github.io/webdriver-bidi/#request-id// NB: Fetch's internal request clones and redirects share this identity.-class NetworkRequest final : public RefCounted<NetworkRequest> {+class NetworkRequest final : public Fetch::Infrastructure::NetworkObserverState {AK_ALLOC_WITH_KMALLOC;public:@@ -95,15 +96,17 @@ WEB_API bool network_configuration_enabled();void network_session_state_changed();void cancel_network_interception(Fetch::Infrastructure::FetchParams const&);-void apply_network_cache_behavior(Fetch::Infrastructure::Request&);-void apply_network_extra_headers(Fetch::Infrastructure::Request&);-void apply_network_request_header_overrides(Fetch::Infrastructure::Request&);+void apply_network_cache_behavior(Fetch::Infrastructure::FetchParams const&);+void apply_network_extra_headers(Fetch::Infrastructure::FetchParams const&);+void apply_network_request_header_overrides(Fetch::Infrastructure::FetchParams const&);+void remove_network_request_content_length_override(Fetch::Infrastructure::FetchParams const&);JsonArray get_network_intercepts(Fetch::Infrastructure::FetchParams const&, StringView phase);void block_network_request(Fetch::Infrastructure::FetchParams const&, RefPtr<Fetch::Infrastructure::Response>, String phase, JsonArray intercepts, GC::Ref<NetworkContinuation>, RefPtr<Fetch::Infrastructure::Request> original_request = nullptr);WEB_API Response continue_network_request(StringView method, JsonObject const&);-void initialize_network_request(Fetch::Infrastructure::Request&, GC::Ptr<HTML::Navigable> = nullptr, Optional<Utf16String> const& navigation = {});-void synchronize_network_request(Fetch::Infrastructure::Request& original, Fetch::Infrastructure::Request& prepared);+void initialize_network_request(Fetch::Infrastructure::Request&, GC::Ptr<HTML::Navigable>, Optional<Utf16String> const& navigation);+void initialize_network_request(Fetch::Infrastructure::FetchParams const&, GC::Ptr<HTML::Navigable> = nullptr);+void initialize_network_request_with_its_navigable(Fetch::Infrastructure::FetchParams const&);void network_before_request_sent(Fetch::Infrastructure::FetchParams const&);void network_response_started(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response&);void network_auth_required(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response const&);diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppindex 0357a0366eb..d2cbb29daf8 100644--- a/Tests/LibWeb/TestFetchAlgorithms.cpp+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -5,7 +5,9 @@*/#include "FetchTestDocument.h"+#include <AK/JsonObject.h>#include <AK/RefCounted.h>+#include <AK/ScopeGuard.h>#include <LibCore/EventLoop.h>#include <LibCore/Timer.h>#include <LibGC/Function.h>@@ -31,6 +33,7 @@#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/Streams/ReadableStreamDefaultReader.h>+#include <LibWeb/WebDriver/BiDi/BiDi.h>#include <LibWeb/WebIDL/DOMException.h>using Web::Fetch::Engine::Event::ReadRequestBodyStream;@@ -546,3 +549,70 @@ TEST_CASE(a_null_request_body_ends_before_the_response)harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 2; }));EXPECT_EQ(record->calls, (Vector<ByteString> { "end of body", "network error" }));}++namespace {++// The WebDriver BiDi network events that reached the event sink, by name and request id.+struct ReportedNetworkEvents : RefCounted<ReportedNetworkEvents> {+ GC_HOLDS_NO_CELL_EDGES;++ Vector<String> names;+ Vector<String> request_ids;+};++}++TEST_CASE(a_request_fetched_again_keeps_its_webdriver_bidi_request_id)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto events = make_ref_counted<ReportedNetworkEvents>();+ Web::WebDriver::BiDi::set_event_sink({+ .on_event = [events](Web::HTML::Navigable const&, String const& name, JsonValue params) {+ events->names.append(name);+ events->request_ids.append(*params.as_object().get_object("request"sv)->get_string("request"sv));+ },+ .on_navigation_event = {},+ });+ Web::WebDriver::BiDiSessionState session_state;+ session_state.is_active = true;+ session_state.enabled_events = { "network.beforeRequestSent"_string, "network.fetchError"_string };+ Web::WebDriver::BiDi::set_session_state(move(session_state));+ ScopeGuard end_session = [] {+ Web::WebDriver::BiDi::set_session_state({});+ Web::WebDriver::BiDi::set_event_sink({});+ };++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<AlgorithmCalls>();+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard };+ input.process_response_end_of_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>) { ++record->call_count; });+ auto algorithms = FetchAlgorithms::create(move(input));+ auto run_fetch = [&](Request& request) {+ auto expected_call_count = record->call_count + 1;+ (void)harness.fetch_with(request, algorithms);+ harness.run_tasks_until(GC::create_function(heap, GC::captures(record, expected_call_count), [](auto& record, auto& expected_call_count) { return record->call_count == expected_call_count; }));+ VERIFY(record->call_count == expected_call_count);+ };++ // With no RequestServer, an http: fetch reports its request, then a network error.+ auto request = harness.create_request_for("http://localhost/"sv);+ run_fetch(request);+ EXPECT_EQ(events->names, (Vector<String> { "network.beforeRequestSent"_string, "network.fetchError"_string }));+ VERIFY(events->request_ids.size() == 2);+ EXPECT_EQ(events->request_ids[1], events->request_ids[0]);++ // Fetched again, the request keeps its id, so it reports nothing new for the same redirect count.+ run_fetch(request);+ EXPECT_EQ(events->names.size(), 2u);++ // Another request gets an id of its own.+ auto other_request = harness.create_request_for("http://localhost/"sv);+ run_fetch(other_request);+ EXPECT_EQ(events->names, (Vector<String> { "network.beforeRequestSent"_string, "network.fetchError"_string, "network.beforeRequestSent"_string, "network.fetchError"_string }));+ VERIFY(events->request_ids.size() == 4);+ EXPECT_EQ(events->request_ids[3], events->request_ids[2]);+ EXPECT_NE(events->request_ids[2], events->request_ids[0]);+}diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.pyindex c1edddcedb3..7de3d7c6680 100755--- a/Tests/LibWebView/test-webdriver-bidi.py+++ b/Tests/LibWebView/test-webdriver-bidi.py@@ -135,6 +135,8 @@ class ReloadServer(http.server.ThreadingHTTPServer):self.release_interception = threading.Event()self.detached_final_received = threading.Event()self.interception_transport_closed = threading.Event()+ self.failing_body_sent = threading.Event()+ self.release_failing_body = threading.Event()self.document_headers_sent: threading.Event = threading.Event()self.release_document: threading.Event = threading.Event()self.preflight_received: threading.Event = threading.Event()@@ -168,6 +170,19 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):except (ConnectionResetError, BrokenPipeError):server.interception_transport_closed.set()return+ if self.path == "/network-events/failing-body":+ self.send_response(200)+ self.send_header("Content-Length", "1000000")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(b"unfinished body")+ self.wfile.flush()+ server.failing_body_sent.set()+ if not server.release_failing_body.wait(30):+ raise TimeoutError("The test did not release the failing body")+ # The connection closes with the body unfinished, which fails the body.+ self.close_connection = True+ returnif self.path.startswith("/network-interception/"):# NB: Preserve duplicate fields for assertions even if the transport combines their length values.# A stale length on the redirected GET is an assertion failure, not a reason for the fixture to wait.@@ -1157,6 +1172,62 @@ def check_network_stopped_fetch_reports_error(bidi, context, server):bidi.evaluate(context, "objectFrame.remove(); 0")+def check_network_body_error_after_late_subscription(bidi, context, server):+ url = f"http://127.0.0.1:{server.server_port}/network-events/failing-body"+ server.failing_body_sent.clear()+ server.release_failing_body.clear()+ pending = bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "expression": "window.failingBodyAbort = new AbortController(); window.failingBodyResponse = false; "+ f"fetch({json.dumps(url)}, {{signal: failingBodyAbort.signal}}).then(response => "+ "{ failingBodyResponse = true; return response.text(); }).then(() => 'fulfilled', error => error.name)",+ "awaitPromise": True,+ },+ )+ subscription = None++ def reported_events():+ return [+ (event["method"], event["params"]["request"]["request"])+ for event in bidi.events+ if event["method"].startswith("network.") and event["params"]["request"]["url"] == url+ ]++ try:+ assert server.failing_body_sent.wait(30), "The request did not reach the server"+ # No network event is enabled until the fetch has handed its response over.+ deadline = time.monotonic() + 30+ while not bidi.evaluate(context, "failingBodyResponse")["result"]["value"]:+ assert time.monotonic() < deadline, "The response did not arrive"+ time.sleep(0.01)+ subscription = bidi.command(+ "session.subscribe", {"events": ["network.beforeRequestSent", "network.fetchError"]}+ )["subscription"]+ # NB: State broadcasts and response delivery come from different IPC peers.+ bidi.evaluate(context, "0")+ server.release_failing_body.set()+ result = bidi.response(pending)+ assert result["type"] == "success" and result["result"]["result"]["value"] == "TypeError", result+ events = reported_events()+ assert [method for method, _ in events] == ["network.beforeRequestSent", "network.fetchError"], events+ assert events[0][1] == events[1][1], events++ # An abort after the body failed reports nothing more, and no other id for the request.+ bidi.evaluate(context, "failingBodyAbort.abort(); 0")+ assert reported_events() == events, (events, reported_events())+ bidi.events = [+ event+ for event in bidi.events+ if not event["method"].startswith("network.") or event["params"]["request"]["url"] != url+ ]+ finally:+ server.release_failing_body.set()+ if sys.exc_info()[0] is None and subscription is not None:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})++def check_network_continue_after_gc(bidi, context, server):subscription = bidi.command("session.subscribe",@@ -1528,6 +1599,8 @@ def check_network_interception(bidi, context, server, case="all"):check_network_cancel_with_events_off(bidi, context, server, kind)if case in ["all", "events-on-stop"]:check_network_stopped_fetch_reports_error(bidi, context, server)+ if case in ["all", "late-events-body-error"]:+ check_network_body_error_after_late_subscription(bidi, context, server)if case in ["all", "continue-after-gc"]:check_network_continue_after_gc(bidi, context, server)if case in ["all", "preflight-body"]:@@ -2774,6 +2847,7 @@ if __name__ == "__main__":"events-off-abort","events-off-stop","events-on-stop",+ "late-events-body-error","continue-after-gc","preflight-body","adopted-navigation-continue",