Truly independent web browser
LibWeb: Intercept WebDriver BiDi network requests
Andreas Klingcb9b8cb542d3
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 0278c662d16..20906b1e049 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -1609,7 +1609,7 @@ 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::g_network_events_enabled)+ if (WebDriver::BiDi::g_network_events_enabled || WebDriver::BiDi::g_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:@@ -1904,6 +1904,10 @@ 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);+ }static constexpr Array request_body_header_names {"Content-Encoding"sv,@@ -1971,6 +1975,265 @@ GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm& realm, Infrastructure::Freturn main_fetch(realm, fetch_params, recursive);}+enum class AuthenticationHandled {+ No,+ Yes,+};++// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch+static void process_http_network_or_cache_response(JS::Object& global_object, Infrastructure::FetchParams const& fetch_params, NonnullRefPtr<Infrastructure::Request> http_request, GC::Ref<Infrastructure::Response> response, GC::Ref<PendingResponse> returned_pending_response, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch, HTTP::Cookie::IncludeCredentials include_credentials, AuthenticationHandled authentication_handled = AuthenticationHandled::No)+{+ auto& realm = HTML::relevant_realm(global_object);+ auto request = fetch_params.request();+ // 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.+ if (http_request->header_list()->contains("Range"sv))+ response->set_range_requested(true);++ // 13. Set response’s request-includes-credentials to includeCredentials.+ response->set_request_includes_credentials(include_credentials == HTTP::Cookie::IncludeCredentials::Yes);++ auto inner_pending_response = PendingResponse::create(fetch_params, *response);++ // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", includeCredentials is true,+ // and request’s traversable for user prompts is a traversable navigable:+ // AD-HOC: Only enter the 401 handling path if the server is requesting an authentication+ // scheme we can handle with a username/password prompt (Basic or Digest).+ // Other schemes like PrivateToken (RFC 9577) are not user-prompt-based and should+ // not trigger credential prompting or request retries.+ auto www_authenticate_has_credential_based_scheme = [&] {+ auto www_authenticate = response->header_list()->get("WWW-Authenticate"sv);+ if (!www_authenticate.has_value())+ return false;+ // The value is a comma-separated list of challenges. Each challenge starts with a scheme name.+ // We check if any of the schemes are ones we can handle with a username/password prompt.+ auto value = *www_authenticate;+ for (auto challenge : value.view().split_view(',')) {+ auto trimmed = challenge.trim_whitespace();+ auto space_index = trimmed.find(' ');+ auto scheme = space_index.has_value() ? trimmed.substring_view(0, *space_index) : trimmed;+ if (scheme.equals_ignoring_ascii_case("Basic"sv) || scheme.equals_ignoring_ascii_case("Digest"sv))+ return true;+ }+ return false;+ };++ if (response->status() == 401+ && http_request->response_tainting() != Infrastructure::Request::ResponseTainting::CORS+ && include_credentials == HTTP::Cookie::IncludeCredentials::Yes+ && request->traversable_for_user_prompts().has<HTML::CrossProcessId>()+ && www_authenticate_has_credential_based_scheme()) {+ // 1. Needs testing: multiple `WWW-Authenticate` headers, missing, parsing issues.+ // (Red box in the spec, no-op)++ // 2. If request’s body is non-null, then:+ if (!request->body().has<Empty>()) {+ // 1. If request’s body’s source is null, then return a network error.+ auto source = request->body().get<Infrastructure::FetchBody>().source();+ if (!source.has_value()) {+ stop_discarded_response_body(*fetch_params.controller(), *response);+ returned_pending_response->resolve(Infrastructure::Response::network_error("Request has body but no body source"_string));+ return;+ }++ // 2. Set request’s body to the body of the result of safely extracting request’s body’s source.+ request->set_body(Infrastructure::FetchBody::from_bytes(*source));+ }++ // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:+ if (!request->use_url_credentials() || is_authentication_fetch == IsAuthenticationFetch::Yes) {+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.+ if (fetch_params.is_canceled()) {+ stop_discarded_response_body(*fetch_params.controller(), *response);+ returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));+ return;+ }++ if (WebDriver::BiDi::g_network_events_enabled && authentication_handled == AuthenticationHandled::No) {+ auto intercepts = WebDriver::BiDi::get_network_intercepts(fetch_params, "authRequired"sv);+ if (!intercepts.is_empty()) {+ WebDriver::BiDi::block_network_request(realm.global_object(), fetch_params, response, "authRequired"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction action, GC::Ptr<Infrastructure::Response> continued_response) {+ if (action == WebDriver::BiDi::NetworkContinuationAction::ProvideCredentials) {+ stop_discarded_response_body(*fetch_params.controller(), *continued_response);+ auto pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);+ pending_response->when_loaded([returned_pending_response](auto response) { returned_pending_response->resolve(response); });+ } else if (first_is_one_of(action, WebDriver::BiDi::NetworkContinuationAction::CancelAuthentication, WebDriver::BiDi::NetworkContinuationAction::Fail, WebDriver::BiDi::NetworkContinuationAction::ProvideResponse)) {+ returned_pending_response->resolve(*continued_response);+ } else {+ process_http_network_or_cache_response(realm.global_object(), fetch_params, http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, action == WebDriver::BiDi::NetworkContinuationAction::RetryAuthentication ? AuthenticationHandled::No : AuthenticationHandled::Yes);+ }+ }));+ return;+ }+ WebDriver::BiDi::network_auth_required(fetch_params, *response);+ }++ // FIXME: 2. Let username and password be the result of prompting the end user for a username and password,+ // respectively, in request’s window.+ // FIXME: 3. Set the username given request’s current URL and username.+ // FIXME: 4. Set the password given request’s current URL and password.+ stop_discarded_response_body(*fetch_params.controller(), *response);+ dbgln("Fetch: Username/password prompt is not implemented. Aborting the request.");+ returned_pending_response->resolve(Infrastructure::Response::aborted_network_error());+ return;+ }++ // 4. Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.+ stop_discarded_response_body(*fetch_params.controller(), *response);+ inner_pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);+ }++ inner_pending_response->when_loaded([&realm, &fetch_params, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](GC::Ref<Infrastructure::Response> response) {+ dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");+ // 15. If response’s status is 407, then:+ if (response->status() == 407) {+ // 1. If request’s traversable for user prompts is "no-traversable", then return a network error.+ if (request->traversable_for_user_prompts().has<Infrastructure::Request::TraversableForUserPrompts>()+ && request->traversable_for_user_prompts().get<Infrastructure::Request::TraversableForUserPrompts>() == Infrastructure::Request::TraversableForUserPrompts::NoTraversable) {+ returned_pending_response->resolve(Infrastructure::Response::network_error("Request requires proxy authentication but has 'no-window' set"_string));+ return;+ }++ // 2. Needs testing: multiple `Proxy-Authenticate` headers, missing, parsing issues.+ // (Red box in the spec, no-op)++ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.+ if (fetch_params.is_canceled()) {+ returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));+ return;+ }++ // FIXME: 4. Prompt the end user as appropriate in request’s window and store the result as a+ // proxy-authentication entry.+ // NOTE: Remaining details surrounding proxy authentication are defined by HTTP.++ // FIXME: 5. Set response to the result of running HTTP-network-or-cache fetch given fetchParams.+ // (Doing this without step 4 would potentially lead to an infinite request cycle.)+ }++ auto inner_pending_response = PendingResponse::create(fetch_params, *response);++ // 16. If all of the following are true+ if (+ // - response’s status is 421+ response->status() == 421+ // - isNewConnectionFetch is false+ && is_new_connection_fetch == IsNewConnectionFetch::No+ // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null+ && (request->body().has<Empty>() || request->body().get<Infrastructure::FetchBody>().source().has_value())+ // then:+ ) {+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.+ if (fetch_params.is_canceled()) {+ returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));+ return;+ }+ // 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,+ // isAuthenticationFetch, and true.+ inner_pending_response = http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes);+ }++ inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](GC::Ref<Infrastructure::Response> response) {+ // 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given+ // realm.+ if (is_authentication_fetch == IsAuthenticationFetch::Yes) {+ // FIXME: "create an authentication entry for request and the given realm"+ }++ returned_pending_response->resolve(response);+ });+ });+}++// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch+static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object& global_object, Infrastructure::FetchParams const& fetch_params, GC::Ref<Infrastructure::FetchParams const> http_fetch_params, GC::Ptr<Infrastructure::Response> response, GC::Ptr<Infrastructure::Response> stored_response, RefPtr<HTTP::MemoryCache> http_cache, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch, HTTP::Cookie::IncludeCredentials include_credentials)+{+ auto& realm = HTML::relevant_realm(global_object);+ auto request = fetch_params.request();+ auto http_request = http_fetch_params->request();++ GC::Ptr<PendingResponse> pending_forward_response;++ // 10. If response is null, then:+ if (!response) {+ // 1. If httpRequest’s cache mode is "only-if-cached", then return a network error.+ // NB: We skip this step in order to allow the disk cache in RequestServer to handle this request. If a disk+ // cache entry does not exist, it will return a network error itself.++ // 2. Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams, includeCredentials,+ // and isNewConnectionFetch.+ pending_forward_response = nonstandard_resource_loader_file_or_http_network_fetch(realm, *http_fetch_params, include_credentials, is_new_connection_fetch, http_cache);+ } else {+ pending_forward_response = PendingResponse::create(fetch_params, Infrastructure::Response::create());+ }++ // AD-HOC: If the controller is already in the non-spec Stopped state, we should cancel the network request immediately.+ if (http_fetch_params->controller()->state() == Infrastructure::FetchController::State::Stopped)+ http_fetch_params->controller()->stop_fetch();++ auto returned_pending_response = PendingResponse::create(fetch_params);++ pending_forward_response->when_loaded([&realm, &fetch_params, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](GC::Ref<Infrastructure::Response> resolved_forward_response) mutable {+ dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");+ if (response_was_null) {+ auto forward_response = resolved_forward_response;++ // NOTE: TRACE is omitted as it is a forbidden method in Fetch.+ auto method_is_unsafe = !http_request->method().is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv);++ // 3. If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399, inclusive,+ // invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP+ // Caching, and set storedResponse to null.+ if (method_is_unsafe && forward_response->status() >= 200 && forward_response->status() <= 399) {+ if (http_cache)+ http_cache->invalidate(http_request->current_url());+ stored_response = nullptr;+ }++ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, then:+ // 1. Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening+ // Stored Responses upon Validation" chapter of HTTP Caching.+ // 2. Set response to storedResponse.+ // 3. Set response’s cache state to "validated".+ // NB: We only cache fresh responses in WebContent. Revalidation is handled by RequestServer.++ // 5. If response is null, then:+ if (!response) {+ // 1. Set response to forwardResponse.+ response = forward_response;++ // 2. Store httpRequest and forwardResponse in httpCache, as per the "Storing Responses in Caches" chapter of HTTP Caching.+ // NOTE: If forwardResponse is a network error, this effectively caches the network error, which is+ // sometimes known as "negative caching".+ // NOTE: The associated body info is stored in the cache alongside the response.+ // NB: The network fetch stores forwardResponse as its headers arrive, before the end of its body can+ // finalize the entry.+ }+ }++ // 11. Set response’s URL list to a clone of httpRequest’s URL list.+ response->set_url_list(http_request->url_list());++ if (WebDriver::BiDi::g_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);+ 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(realm.global_object(), *http_fetch_params, response, "responseStarted"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction, GC::Ptr<Infrastructure::Response> continued_response) {+ process_http_network_or_cache_response(realm.global_object(), fetch_params, *http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);+ }));+ return;+ }+ WebDriver::BiDi::network_response_started(*http_fetch_params, *response);+ }+ process_http_network_or_cache_response(realm.global_object(), fetch_params, *http_request, *response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);+ });++ // 18. Return response.+ // NOTE: Typically response’s body’s stream is still being enqueued to after returning.+ return returned_pending_response;+}+// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetchGC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch){@@ -1983,6 +2246,9 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastruif (WebDriver::BiDi::g_network_events_enabled)WebDriver::BiDi::initialize_network_request(*request);+ if (WebDriver::BiDi::g_network_configuration_enabled)+ WebDriver::BiDi::apply_network_cache_behavior(*request);+// 2. Let httpFetchParams be null.GC::Ptr<Infrastructure::FetchParams const> http_fetch_params;@@ -2027,8 +2293,8 @@ 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();- if (WebDriver::BiDi::g_network_events_enabled)- http_request->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());+ // 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);@@ -2234,6 +2500,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);+ if (WebDriver::BiDi::g_network_configuration_enabled)+ WebDriver::BiDi::apply_network_extra_headers(*http_request);+// 23. Set httpCache to the result of determining the HTTP cache partition, given httpRequest.http_cache = determine_the_http_cache_partition(*http_request);@@ -2271,220 +2541,29 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru}}- if (WebDriver::BiDi::g_network_events_enabled)- WebDriver::BiDi::network_before_request_sent(*http_fetch_params);-// 9. If aborted, then return the appropriate network error for fetchParams.if (aborted)return PendingResponse::create(fetch_params, Infrastructure::Response::appropriate_network_error(fetch_params));- GC::Ptr<PendingResponse> pending_forward_response;-- // 10. If response is null, then:- if (!response) {- // 1. If httpRequest’s cache mode is "only-if-cached", then return a network error.- // NB: We skip this step in order to allow the disk cache in RequestServer to handle this request. If a disk- // cache entry does not exist, it will return a network error itself.-- // 2. Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams, includeCredentials,- // and isNewConnectionFetch.- pending_forward_response = nonstandard_resource_loader_file_or_http_network_fetch(realm, *http_fetch_params, include_credentials, is_new_connection_fetch, http_cache);- } else {- pending_forward_response = PendingResponse::create(fetch_params, Infrastructure::Response::create());- }-- // AD-HOC: If the controller is already in the non-spec Stopped state, we should cancel the network request immediately.- if (http_fetch_params->controller()->state() == Infrastructure::FetchController::State::Stopped)- http_fetch_params->controller()->stop_fetch();-- auto returned_pending_response = PendingResponse::create(fetch_params);-- pending_forward_response->when_loaded([&realm, &fetch_params, request, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](GC::Ref<Infrastructure::Response> resolved_forward_response) mutable {- dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");- if (response_was_null) {- auto forward_response = resolved_forward_response;-- // NOTE: TRACE is omitted as it is a forbidden method in Fetch.- auto method_is_unsafe = !http_request->method().is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv);-- // 3. If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399, inclusive,- // invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP- // Caching, and set storedResponse to null.- if (method_is_unsafe && forward_response->status() >= 200 && forward_response->status() <= 399) {- if (http_cache)- http_cache->invalidate(http_request->current_url());- stored_response = nullptr;- }-- // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, then:- // 1. Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening- // Stored Responses upon Validation" chapter of HTTP Caching.- // 2. Set response to storedResponse.- // 3. Set response’s cache state to "validated".- // NB: We only cache fresh responses in WebContent. Revalidation is handled by RequestServer.-- // 5. If response is null, then:- if (!response) {- // 1. Set response to forwardResponse.- response = forward_response;-- // 2. Store httpRequest and forwardResponse in httpCache, as per the "Storing Responses in Caches" chapter of HTTP Caching.- // NOTE: If forwardResponse is a network error, this effectively caches the network error, which is- // sometimes known as "negative caching".- // NOTE: The associated body info is stored in the cache alongside the response.- // NB: The network fetch stores forwardResponse as its headers arrive, before the end of its body can- // finalize the entry.- }- }-- // 11. Set response’s URL list to a clone of httpRequest’s URL list.- response->set_url_list(http_request->url_list());-- if (WebDriver::BiDi::g_network_events_enabled)- WebDriver::BiDi::network_response_started(*http_fetch_params, *response);-- // 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.- if (http_request->header_list()->contains("Range"sv))- response->set_range_requested(true);-- // 13. Set response’s request-includes-credentials to includeCredentials.- response->set_request_includes_credentials(include_credentials == HTTP::Cookie::IncludeCredentials::Yes);-- auto inner_pending_response = PendingResponse::create(fetch_params, *response);-- // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", includeCredentials is true,- // and request’s traversable for user prompts is a traversable navigable:- // AD-HOC: Only enter the 401 handling path if the server is requesting an authentication- // scheme we can handle with a username/password prompt (Basic or Digest).- // Other schemes like PrivateToken (RFC 9577) are not user-prompt-based and should- // not trigger credential prompting or request retries.- auto www_authenticate_has_credential_based_scheme = [&] {- auto www_authenticate = response->header_list()->get("WWW-Authenticate"sv);- if (!www_authenticate.has_value())- return false;- // The value is a comma-separated list of challenges. Each challenge starts with a scheme name.- // We check if any of the schemes are ones we can handle with a username/password prompt.- auto value = *www_authenticate;- for (auto challenge : value.view().split_view(',')) {- auto trimmed = challenge.trim_whitespace();- auto space_index = trimmed.find(' ');- auto scheme = space_index.has_value() ? trimmed.substring_view(0, *space_index) : trimmed;- if (scheme.equals_ignoring_ascii_case("Basic"sv) || scheme.equals_ignoring_ascii_case("Digest"sv))- return true;- }- return false;- };-- if (response->status() == 401- && http_request->response_tainting() != Infrastructure::Request::ResponseTainting::CORS- && include_credentials == HTTP::Cookie::IncludeCredentials::Yes- && request->traversable_for_user_prompts().has<HTML::CrossProcessId>()- && www_authenticate_has_credential_based_scheme()) {- // NB: Every branch below drops this response, for a network error or a new fetch's response.- stop_discarded_response_body(*fetch_params.controller(), *response);-- // 1. Needs testing: multiple `WWW-Authenticate` headers, missing, parsing issues.- // (Red box in the spec, no-op)-- // 2. If request’s body is non-null, then:- if (!request->body().has<Empty>()) {- // 1. If request’s body’s source is null, then return a network error.- auto source = request->body().get<Infrastructure::FetchBody>().source();- if (!source.has_value()) {- returned_pending_response->resolve(Infrastructure::Response::network_error("Request has body but no body source"_string));- return;- }-- // 2. Set request’s body to the body of the result of safely extracting request’s body’s source.- request->set_body(Infrastructure::FetchBody::from_bytes(*source));- }-- // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:- if (!request->use_url_credentials() || is_authentication_fetch == IsAuthenticationFetch::Yes) {- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.+ if (WebDriver::BiDi::g_network_events_enabled) {+ auto intercepts = WebDriver::BiDi::get_network_intercepts(*http_fetch_params, "beforeRequestSent"sv);+ if (!intercepts.is_empty()) {+ auto returned_pending_response = PendingResponse::create(fetch_params);+ WebDriver::BiDi::block_network_request(realm.global_object(), *http_fetch_params, nullptr, "beforeRequestSent"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_fetch_params, response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials, returned_pending_response](WebDriver::BiDi::NetworkContinuationAction action, GC::Ptr<Infrastructure::Response> continued_response) {+ // AD-HOC: The fetch can be canceled while its request is blocked.if (fetch_params.is_canceled()) {returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));return;}-- // FIXME: 2. Let username and password be the result of prompting the end user for a username and password,- // respectively, in request’s window.- // FIXME: 3. Set the username given request’s current URL and username.- // FIXME: 4. Set the password given request’s current URL and password.- dbgln("Fetch: Username/password prompt is not implemented. Aborting the request.");- returned_pending_response->resolve(Infrastructure::Response::aborted_network_error());- return;- }-- // 4. Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.- inner_pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);+ auto pending_response = continue_http_network_or_cache_fetch(realm.global_object(), fetch_params, *http_fetch_params, action == WebDriver::BiDi::NetworkContinuationAction::Continue ? response : continued_response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials);+ pending_response->when_loaded([returned_pending_response](auto response) { returned_pending_response->resolve(response); });+ }),+ request);+ return returned_pending_response;}-- inner_pending_response->when_loaded([&realm, &fetch_params, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](GC::Ref<Infrastructure::Response> response) {- dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");- // 15. If response’s status is 407, then:- if (response->status() == 407) {- // 1. If request’s traversable for user prompts is "no-traversable", then return a network error.- if (request->traversable_for_user_prompts().has<Infrastructure::Request::TraversableForUserPrompts>()- && request->traversable_for_user_prompts().get<Infrastructure::Request::TraversableForUserPrompts>() == Infrastructure::Request::TraversableForUserPrompts::NoTraversable) {- returned_pending_response->resolve(Infrastructure::Response::network_error("Request requires proxy authentication but has 'no-window' set"_string));- return;- }-- // 2. Needs testing: multiple `Proxy-Authenticate` headers, missing, parsing issues.- // (Red box in the spec, no-op)-- // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.- if (fetch_params.is_canceled()) {- returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));- return;- }-- // FIXME: 4. Prompt the end user as appropriate in request’s window and store the result as a- // proxy-authentication entry.- // NOTE: Remaining details surrounding proxy authentication are defined by HTTP.-- // FIXME: 5. Set response to the result of running HTTP-network-or-cache fetch given fetchParams.- // (Doing this without step 4 would potentially lead to an infinite request cycle.)- }-- auto inner_pending_response = PendingResponse::create(fetch_params, *response);-- // 16. If all of the following are true- if (- // - response’s status is 421- response->status() == 421- // - isNewConnectionFetch is false- && is_new_connection_fetch == IsNewConnectionFetch::No- // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null- && (request->body().has<Empty>() || request->body().get<Infrastructure::FetchBody>().source().has_value())- // then:- ) {- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.- if (fetch_params.is_canceled()) {- returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));- return;- }- // 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,- // isAuthenticationFetch, and true.- inner_pending_response = http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes);- }-- inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](GC::Ref<Infrastructure::Response> response) {- // 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given- // realm.- if (is_authentication_fetch == IsAuthenticationFetch::Yes) {- // FIXME: "create an authentication entry for request and the given realm"- }-- returned_pending_response->resolve(response);- });- });- });-- // 18. Return response.- // NOTE: Typically response’s body’s stream is still being enqueued to after returning.- return returned_pending_response;+ WebDriver::BiDi::network_before_request_sent(*http_fetch_params);+ }+ return continue_http_network_or_cache_fetch(realm.global_object(), fetch_params, *http_fetch_params, response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials);}#if defined(WEB_FETCH_DEBUG)diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex b870ffac1d7..7e04c9b623b 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -15,6 +15,7 @@#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/Page/RenderingStats.h>+#include <LibWeb/WebDriver/BiDi/BiDi.h>#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebIDL/DOMException.h>@@ -117,6 +118,8 @@ void FetchController::abort(JS::Realm& realm, Optional<JS::Value> error)m_state = State::Aborted;if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)WebDriver::BiDi::network_fetch_error(*m_fetch_params, "Fetch was aborted"sv);+ else if (WebDriver::BiDi::is_active() && m_fetch_params)+ WebDriver::BiDi::cancel_network_interception(*m_fetch_params);// 2. Let fallbackError be an "AbortError" DOMException.auto fallback_error = WebIDL::AbortError::create("Fetch was aborted"_utf16);@@ -146,6 +149,8 @@ void FetchController::terminate()m_state = State::Terminated;if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)WebDriver::BiDi::network_fetch_error(*m_fetch_params, "Fetch was terminated"sv);+ else if (WebDriver::BiDi::is_active() && m_fetch_params)+ WebDriver::BiDi::cancel_network_interception(*m_fetch_params);stop_request();}@@ -156,6 +161,8 @@ void FetchController::stop_fetch()return;m_state = State::Stopped;+ if (WebDriver::BiDi::is_active() && m_fetch_params)+ WebDriver::BiDi::cancel_network_interception(*m_fetch_params);// AD-HOC: Some HTML elements need to stop an ongoing fetching process without causing any network error to be raised// (which abort() and terminate() will both do). This is tricky because the fetch process runs across severaldiff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 5f8bf9283f3..e2c1a44b9e1 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -2557,7 +2557,7 @@ static void create_navigation_params_by_fetching(request->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Manual);request->set_replaces_client_id(active_document.relevant_settings_object().id);request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);- if (WebDriver::BiDi::g_network_events_enabled)+ if (WebDriver::BiDi::g_network_events_enabled || WebDriver::BiDi::g_network_configuration_enabled)WebDriver::BiDi::initialize_network_request(*request, navigable, navigation_id);request->set_referrer(document_state.request_referrer);request->set_referrer_policy(document_state.request_referrer_policy);diff --git a/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp b/Libraries/LibWeb/WebDriver/BiDi/BiDi.cppindex d947e5ca88c..7cd6febf2ba 100644--- a/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp@@ -65,7 +65,7 @@ void set_session_state(BiDiSessionState session_state)state() = move(session_state);g_is_active = state().is_active;- g_network_events_enabled = g_is_active && any_of(state().enabled_events, [](auto const& name) { return name.starts_with_bytes("network."sv); });+ network_session_state_changed();// NB: The documents that existed before the session started run the console steps from now on.if (g_is_active && !was_active)diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cppindex 9a8fec978ac..859f9d7b404 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp@@ -11,6 +11,8 @@#include <AK/StringBuilder.h>#include <AK/Time.h>#include <LibRequests/Request.h>+#include <LibWeb/DOM/Document.h>+#include <LibWeb/Fetch/BodyInit.h>#include <LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h>#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>@@ -24,8 +26,252 @@namespace Web::WebDriver::BiDi {using namespace Fetch::Infrastructure;+using Response = Fetch::Infrastructure::Response;++GC_DEFINE_ALLOCATOR(NetworkContinuation);++NetworkContinuation::NetworkContinuation(Callback callback)+ : m_callback(move(callback))+{+}++GC::Ref<NetworkContinuation> NetworkContinuation::create(GC::Heap& heap, Callback callback)+{+ return heap.allocate<NetworkContinuation>(move(callback));+}++void NetworkContinuation::finalize()+{+ Base::finalize();+ clear_blocked_state();+ m_callback = nullptr;+}++void NetworkContinuation::visit_edges(JS::Cell::Visitor& visitor)+{+ Base::visit_edges(visitor);+ visitor.visit(fetch_params);+ visitor.visit(response);+ visitor.visit(global_object);+ visitor.visit_possible_values(m_callback.raw_capture_range());+}++void NetworkContinuation::invoke(NetworkContinuationAction action, GC::Ptr<Response> response)+{+ m_callback(action, response);+ m_callback = nullptr;+}bool g_network_events_enabled { false };+bool g_network_configuration_enabled { false };++void NetworkContinuation::clear_blocked_state()+{+ request_id = {};+ phase = {};+ intercepts = {};+ fetch_params = nullptr;+ original_request = nullptr;+ response = nullptr;+ global_object = nullptr;+}++static HashMap<String, GC::Root<NetworkContinuation>>& blocked_requests()+{+ static auto& requests = *new HashMap<String, GC::Root<NetworkContinuation>>;+ return requests;+}++static GC::Ptr<NetworkContinuation> blocked_request(Request const& request)+{+ auto state = request.webdriver_bidi_network_request();+ if (!state)+ return nullptr;+ 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.fetch_params();+ if (!fetch_params)+ return nullptr;+ auto blocked = blocked_request(*fetch_params->request());+ return blocked && blocked->fetch_params->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(FetchParams const& fetch_params, Response const& response)+{+ response.release_request_transfer_lease();+ fetch_params.controller()->stop_body_transport();+}++static void resume_blocked_request(String id, NetworkContinuationAction action, GC::Ptr<Fetch::Infrastructure::Response> response)+{+ auto it = blocked_requests().find(id);+ if (it == blocked_requests().end())+ return;+ GC::Ptr<NetworkContinuation> continuation = it->value.ptr();+ auto fetch_params = continuation->fetch_params;+ auto original_response = continuation->response;+ // NB: Remove the entry before stopping transport or invoking a continuation, which can reenter Fetch.+ blocked_requests().remove(it);+ continuation->clear_blocked_state();+ if (action == NetworkContinuationAction::Fail && original_response)+ stop_response_transport(*fetch_params, *original_response);+ continuation->invoke(action, response);+}++static void cancel_network_interception_impl(FetchParams const& fetch_params, StringView error_text)+{+ auto 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)));+}++void cancel_network_interception(FetchParams const& fetch_params)+{+ cancel_network_interception_impl(fetch_params, "Intercepted fetch was stopped"sv);+}++void network_session_state_changed()+{+ auto const& state = session_state();+ g_network_events_enabled = state.is_active && any_of(state.enabled_events, [](auto const& name) { return name.starts_with_bytes("network."sv); });+ g_network_configuration_enabled = state.is_active && (!state.network_default_headers.is_empty() || !state.network_user_context_headers.is_empty() || !state.network_navigable_headers.is_empty() || state.network_default_cache_behavior != "default"sv || !state.network_navigable_cache_behavior.is_empty());+ if (!state.is_active) {+ // https://w3c.github.io/webdriver-bidi/#cleanup-the-session+ while (!blocked_requests().is_empty()) {+ auto const& entry = *blocked_requests().begin();+ auto response = entry.value->response;+ resume_blocked_request(entry.key, NetworkContinuationAction::Continue, response);+ }+ }+}++static GC::Ptr<HTML::LocalNavigable> navigable_of(NetworkRequest const& state)+{+ if (!state.navigable_id.has_value())+ return {};+ return HTML::local_navigable_with_id(*state.navigable_id);+}++static GC::Ptr<HTML::Navigable> request_navigable(Request const& request)+{+ if (auto state = request.webdriver_bidi_network_request())+ 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);+ if (auto const* id = request.traversable_for_user_prompts().get_pointer<HTML::CrossProcessId>())+ return HTML::local_navigable_with_id(*id);+ return nullptr;+}++static String network_context_id(HTML::Navigable& navigable)+{+ auto id = navigable.top_level_traversable()->id();+ return MUST(String::formatted("{}-{}", id.namespace_id, id.local_id));+}++// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-cache-behavior+void apply_network_cache_behavior(Request& request)+{+ auto const& state = session_state();+ auto behavior = state.network_default_cache_behavior;+ if (auto navigable = request_navigable(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);+}++// https://w3c.github.io/webdriver-bidi/#update-request-headers+static constexpr Array fetch_generated_request_header_names {+ "Content-Length"sv,+ "Accept-Encoding"sv,+ "Referer"sv,+ "Origin"sv,+ "Sec-Fetch-Dest"sv,+ "Sec-Fetch-Mode"sv,+ "Sec-Fetch-Site"sv,+ "Sec-Fetch-User"sv,+};++void apply_network_request_header_overrides(Request& request)+{+ auto state = request.webdriver_bidi_network_request();+ if (!state || !state->request_header_overrides)+ return;+ for (auto name : fetch_generated_request_header_names) {+ if (!state->request_header_overrides->contains(name))+ continue;+ 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);+ }+ }+}++void apply_network_extra_headers(Request& request)+{+ auto const& state = session_state();+ // https://w3c.github.io/webdriver-bidi/#update-headers+ auto update_headers = [&](auto const& headers) {+ for (auto const& header : headers)+ request.header_list()->set(header);+ };+ // 2. Update headers with request and session's extra headers' default headers+ update_headers(state.network_default_headers);+ if (auto navigable = request_navigable(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);+ if (auto it = state.network_navigable_headers.find(id); it != state.network_navigable_headers.end())+ update_headers(it->value);+ }+}++// https://w3c.github.io/webdriver-bidi/#get-the-network-intercepts+JsonArray get_network_intercepts(FetchParams const& fetch_params, StringView phase)+{+ JsonArray intercepts;+ if (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();+ 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);+ if (!navigable || fetch_params.is_canceled() || fetch_params.controller()->state() == FetchController::State::Stopped)+ return intercepts;+ if (!state)+ initialize_network_request(*request, 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);+ if (scope == session_state().enabled_event_contexts.end() || (scope->value.has_value() && !scope->value->contains_slow(context)))+ return intercepts;+ // 5. For each intercept id → intercept of session intercepts:+ for (auto const& intercept : session_state().network_intercepts) {+ if (intercept.browsing_contexts.has_value() && !intercept.browsing_contexts->contains_slow(context))+ continue;+ if (!intercept.phases.contains_slow(phase))+ continue;+ if (intercept.url_patterns.is_empty() || any_of(intercept.url_patterns, [&](auto const& pattern) { return pattern.matches(request->current_url()); }))+ MUST(intercepts.append(intercept.id));+ }+ return intercepts;+}NetworkRequest::NetworkRequest(): id(generate_random_uuid())@@ -34,7 +280,7 @@ NetworkRequest::NetworkRequest()void initialize_network_request(Request& request, GC::Ptr<HTML::Navigable> navigable, Optional<Utf16String> const& navigation){- if (!g_network_events_enabled || request.webdriver_bidi_network_request())+ if ((!g_network_events_enabled && !g_network_configuration_enabled) || request.webdriver_bidi_network_request())return;auto state = NetworkRequest::create();if (navigable)@@ -46,11 +292,17 @@ void initialize_network_request(Request& request, GC::Ptr<HTML::Navigable> navigrequest.set_webdriver_bidi_network_request(state);}-static GC::Ptr<HTML::LocalNavigable> navigable_of(NetworkRequest const& state)+void synchronize_network_request(Request& original, Request& prepared){- if (!state.navigable_id.has_value())- return {};- return HTML::local_navigable_with_id(*state.navigable_id);+ 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);}// https://w3c.github.io/webdriver-bidi/#serialize-protocol-bytes@@ -131,10 +383,16 @@ static JsonObject get_the_request_data(Request const& request, FetchTimingInfo cresult.set("request"sv, request.webdriver_bidi_network_request()->id);result.set("url"sv, request.current_url().serialize());result.set("method"sv, MUST(String::from_utf8(request.method().view())));- result.set("headers"sv, serialize_headers(request.header_list()));+ // NB: RequestServer sends one field per name, combining repeated values in order.+ auto headers = HTTP::HeaderList::create();+ for (auto const& header : *request.header_list()) {+ if (!headers->contains(header.name))+ headers->append({ header.name, request.header_list()->get(header.name).release_value() });+ }+ result.set("headers"sv, serialize_headers(headers));// FIXME: Include the cookies attached by RequestServer.result.set("cookies"sv, JsonArray {});- result.set("headersSize"sv, headers_size(request.header_list()));+ result.set("headersSize"sv, headers_size(headers));JsonValue body_size;if (auto const* bytes = request.body().get_pointer<ByteBuffer>())body_size = bytes->size();@@ -250,7 +508,10 @@ static JsonObject process_a_network_event(HTML::Navigable const& navigable, RequJsonObject params;params.set("context"sv, navigable_id(navigable));params.set("userContext"sv, "default"sv);- params.set("isBlocked"sv, false);+ auto blocked = blocked_request(request);+ 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("redirectCount"sv, request.redirect_count());JsonObject request_data;@@ -264,9 +525,203 @@ static JsonObject process_a_network_event(HTML::Navigable const& navigable, Requreturn params;}+void block_network_request(JS::Object& global_object, FetchParams const& fetch_params, GC::Ptr<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()->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();+ if (fetch_params.is_canceled() || fetch_params.controller()->state() == FetchController::State::Stopped) {+ if (response)+ stop_response_transport(fetch_params, *response);+ continuation->invoke(NetworkContinuationAction::Fail, Response::network_error("Intercepted fetch was stopped"_string));+ return;+ }+ // NB: Allocating the continuation after selecting intercepts can collect an otherwise unreachable origin.+ // Continue the fetch without blocking when that context has gone away.+ if (!state || !navigable_of(*state)) {+ continuation->invoke(NetworkContinuationAction::Continue, response);+ return;+ }+ VERIFY(!blocked_requests().contains(state->id));+ continuation->request_id = state->id;+ continuation->phase = move(phase);+ continuation->intercepts = move(intercepts);+ continuation->fetch_params = fetch_params;+ continuation->original_request = original_request;+ continuation->response = response;+ continuation->global_object = global_object;+ 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);+ } else if (continuation->phase == "responseStarted"sv) {+ network_response_started(fetch_params, *response);+ } else {+ network_auth_required(fetch_params, *response);+ }+}++// https://w3c.github.io/webdriver-bidi/#command-network-continueRequest+// https://w3c.github.io/webdriver-bidi/#update-the-response+static ErrorOr<JsonValue, Error> continue_network_request_impl(StringView method, JsonObject const& params)+{+ TRY(Network::validate_interception_parameters(method, params));+ // 1. Let blocked requests be session's blocked request map.+ // 2. Let request id be command parameters["request"].+ auto id = params.get_string("request"sv).release_value();+ // 3. If blocked requests does not contain request id then return error with error code no such request.+ auto it = blocked_requests().find(id);+ if (it == blocked_requests().end())+ return Error::from_code(ErrorCode::NoSuchRequest, "Blocked request not found"sv);+ GC::Ptr<NetworkContinuation> blocked = it->value.ptr();+ auto phase = blocked->phase;+ if ((method == "network.continueRequest"sv && phase != "beforeRequestSent"sv)+ || (method == "network.continueResponse"sv && phase == "beforeRequestSent"sv)+ || (method == "network.continueWithAuth"sv && phase != "authRequired"sv)+ || (method == "network.failRequest"sv && phase == "authRequired"sv))+ return 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 response = blocked->response;+ auto action = NetworkContinuationAction::Continue;+ if (method == "network.continueRequest"sv) {+ // NB: A supplied header list may include Fetch-generated fields echoed from the event. Remember those+ // explicit values separately, so preparation can restore them without appending duplicate fields.+ if (overrides.headers.has_value()) {+ state->request_header_overrides = HTTP::HeaderList::create();+ for (auto const& header : *overrides.headers) {+ if (any_of(fetch_generated_request_header_names, [&](auto name) { return header.name.equals_ignoring_ascii_case(name); }))+ state->request_header_overrides->append(header);+ }+ }+ auto original_request = blocked->original_request;+ if (original_request && original_request != request) {+ if (overrides.url.has_value())+ original_request->url_list().last() = *overrides.url;+ if (overrides.method.has_value())+ original_request->set_method(*overrides.method);+ if (overrides.headers.has_value()) {+ auto headers = HTTP::HeaderList::create(*overrides.headers);+ for (auto name : fetch_generated_request_header_names)+ headers->delete_(name);+ original_request->set_header_list(move(headers));+ }+ if (overrides.cookie_header.has_value())+ original_request->header_list()->set({ "Cookie"sv, *overrides.cookie_header });+ }+ if (overrides.url.has_value())+ request->url_list().last() = overrides.url.release_value();+ if (overrides.method.has_value())+ request->set_method(overrides.method.release_value());+ if (overrides.headers.has_value())+ request->set_header_list(HTTP::HeaderList::create(overrides.headers.release_value()));+ if (overrides.cookie_header.has_value())+ request->header_list()->set({ "Cookie"sv, overrides.cookie_header.release_value() });+ if (overrides.body.has_value()) {+ if (state->request_header_overrides)+ state->request_header_overrides->delete_("Content-Length"sv);+ if (original_request)+ original_request->header_list()->delete_("Content-Length"sv);+ auto body = FetchBody::from_bytes(Core::ImmutableBytes::adopt(overrides.body.release_value()));+ request->set_body(body);+ if (original_request && original_request != request)+ original_request->set_body(body);+ request->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()));+ 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) {+ action = NetworkContinuationAction::Fail;+ response = Fetch::Infrastructure::Response::network_error("Request failed by WebDriver BiDi"_string);+ } else if (method != "network.continueWithAuth"sv) {+ if (!response) {+ response = Fetch::Infrastructure::Response::create();+ response->set_url_list(request->url_list());+ }+ // 7. If command parameters contains "statusCode":+ if (overrides.status.has_value())+ response->set_status(*overrides.status);+ // 8. If command parameters contains "reasonPhrase":+ if (overrides.reason.has_value())+ response->set_status_message(overrides.reason.release_value());+ // 9. If command parameters contains "headers":+ if (overrides.headers.has_value())+ response->set_header_list(HTTP::HeaderList::create(overrides.headers.release_value()));+ if (overrides.set_cookie_headers.has_value()) {+ if (!params.has("headers"sv)) {+ response->set_header_list(HTTP::HeaderList::create(response->header_list()->headers()));+ response->header_list()->delete_("Set-Cookie"sv);+ }+ for (auto const& header : *overrides.set_cookie_headers)+ response->header_list()->append(header);+ }+ if (method == "network.provideResponse"sv)+ action = NetworkContinuationAction::ProvideResponse;+ if (method == "network.provideResponse"sv && overrides.body.has_value()) {+ // NB: A replacement body has no RequestServer transport to transfer to a new navigation process.+ if (blocked->response) {+ blocked->response->release_request_transfer_lease();+ blocked->fetch_params->controller()->stop_body_transport();+ }+ auto replacement = Response::create();+ replacement->set_url_list(response->url_list());+ replacement->set_status(response->status());+ replacement->set_status_message(response->status_message());+ replacement->set_header_list(response->header_list());+ response = replacement;+ auto bytes = overrides.body.release_value();+ auto body = Fetch::safely_extract_body(HTML::relevant_realm(*blocked->global_object), ReadonlyBytes { bytes.bytes() }).body;+ response->set_body(body);+ auto info = response->body_info();+ info.encoded_size = *body->length();+ info.decoded_size = *body->length();+ response->set_body_info(info);+ }+ }+ if (phase == "authRequired"sv && method != "network.failRequest"sv && method != "network.provideResponse"sv) {+ action = NetworkContinuationAction::UseDefaultAuthentication;+ if (method == "network.continueWithAuth"sv) {+ auto auth_action = params.get_string("action"sv).release_value();+ if (auth_action == "default"sv)+ action = NetworkContinuationAction::UseDefaultAuthentication;+ else if (auth_action == "cancel"sv)+ action = NetworkContinuationAction::CancelAuthentication;+ else+ action = NetworkContinuationAction::ProvideCredentials;+ }+ if (auto credentials = params.get_object("credentials"sv); credentials.has_value() && (method == "network.continueResponse"sv || action == NetworkContinuationAction::ProvideCredentials)) {+ auto payload = MUST(String::formatted("{}:{}", *credentials->get_string("username"sv), *credentials->get_string("password"sv)));+ request->header_list()->set({ "Authorization"sv, ByteString::formatted("Basic {}", MUST(encode_base64(payload.bytes()))) });+ action = NetworkContinuationAction::ProvideCredentials;+ }+ }+ resume_blocked_request(id, action, response);+ return JsonValue {};+}++WebDriver::Response continue_network_request(StringView method, JsonObject const& params)+{+ auto result = continue_network_request_impl(method, params);+ if (result.is_error())+ return result.release_error();+ return result.release_value();+}+// 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();@@ -303,6 +758,20 @@ void network_response_started(FetchParams const& fetch_params, Response& respons}}+// https://w3c.github.io/webdriver-bidi/#event-network-authRequired+void network_auth_required(FetchParams const& fetch_params, Response const& response)+{+ auto state = fetch_params.request()->webdriver_bidi_network_request();+ 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());+ params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));+ emit_event(*navigable, "network.authRequired"_string, move(params));+}+// https://w3c.github.io/webdriver-bidi/#event-network-responseCompletedvoid network_response_completed(FetchParams const& fetch_params, Response const& response){@@ -331,12 +800,15 @@ void network_fetch_error(FetchParams const& fetch_params, StringView error_text)network_before_request_sent(fetch_params);auto request = fetch_params.request();auto state = request->webdriver_bidi_network_request();- if (!state || (state->completed.contains(request->redirect_count()) || state->transferred.contains(request->redirect_count())))+ 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());+ cancel_network_interception_impl(fetch_params, error_text);+ if (!is_first_terminal)return;auto navigable = navigable_of(*state);if (!navigable)return;- state->completed.set(request->redirect_count());if (!is_event_enabled("network.fetchError"sv))return;auto params = process_a_network_event(*navigable, *fetch_params.request(), *fetch_params.timing_info());diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.h b/Libraries/LibWeb/WebDriver/BiDi/Network.hindex 9b15470a9ec..efeccba6292 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Network.h+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.h@@ -6,19 +6,64 @@#pragma once+#include <AK/Function.h>#include <AK/HashMap.h>#include <AK/HashTable.h>+#include <AK/JsonArray.h>#include <AK/JsonObject.h>#include <AK/Optional.h>#include <AK/RefCounted.h>+#include <AK/RefPtr.h>#include <AK/String.h>#include <AK/Utf16String.h>+#include <LibGC/Forward.h>#include <LibGC/Ptr.h>+#include <LibHTTP/HeaderList.h>+#include <LibJS/Heap/Cell.h>#include <LibWeb/Forward.h>#include <LibWebCommon/HTML/CrossProcessId.h>+#include <LibWebCommon/WebDriver/Response.h>namespace Web::WebDriver::BiDi {+// NB: How Fetch proceeds with a blocked request once a command or the end of the fetch resumes it.+enum class NetworkContinuationAction : u8 {+ Continue,+ ContinueWithModifiedRequest,+ ProvideResponse,+ Fail,+ UseDefaultAuthentication,+ CancelAuthentication,+ ProvideCredentials,+ RetryAuthentication,+};++// NB: Drop a resumed interception's captured fetch state immediately, rather than waiting for collection.+class NetworkContinuation final : public JS::Cell {+ GC_CELL(NetworkContinuation, JS::Cell);+ GC_DECLARE_ALLOCATOR(NetworkContinuation);++public:+ using Callback = Function<void(NetworkContinuationAction, GC::Ptr<Fetch::Infrastructure::Response>)>;+ static GC::Ref<NetworkContinuation> create(GC::Heap&, Callback);+ void invoke(NetworkContinuationAction, GC::Ptr<Fetch::Infrastructure::Response>);+ void clear_blocked_state();++ String request_id;+ String phase;+ JsonArray intercepts;+ GC::Ptr<Fetch::Infrastructure::FetchParams const> fetch_params;+ RefPtr<Fetch::Infrastructure::Request> original_request;+ GC::Ptr<Fetch::Infrastructure::Response> response;+ GC::Ptr<JS::Object> global_object;++private:+ explicit NetworkContinuation(Callback);+ virtual void finalize() override;+ virtual void visit_edges(JS::Cell::Visitor&) override;+ Callback m_callback;+};+// 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> {@@ -36,6 +81,8 @@ public:HashTable<u8> completed;HashTable<u8> transferred;HashMap<u8, JsonObject> request_data;+ // Explicit overrides for headers Fetch appends during preparation. Keep them out of the unprepared list.+ RefPtr<HTTP::HeaderList> request_header_overrides;private:NetworkRequest();@@ -43,10 +90,22 @@ private:// NB: Fetch checks this cached flag before doing any network instrumentation.WEB_API extern bool g_network_events_enabled;+WEB_API extern bool g_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&);+JsonArray get_network_intercepts(Fetch::Infrastructure::FetchParams const&, StringView phase);+void block_network_request(JS::Object&, Fetch::Infrastructure::FetchParams const&, GC::Ptr<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 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&);void network_response_completed(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response const&);void network_fetch_error(Fetch::Infrastructure::FetchParams const&, StringView);diff --git a/Libraries/LibWebCommon/WebDriver/BiDi.h b/Libraries/LibWebCommon/WebDriver/BiDi.hindex b272241c490..59c31f4ee3f 100644--- a/Libraries/LibWebCommon/WebDriver/BiDi.h+++ b/Libraries/LibWebCommon/WebDriver/BiDi.h@@ -6,6 +6,7 @@#pragma once+#include <AK/HashMap.h>#include <AK/JsonValue.h>#include <AK/Optional.h>#include <AK/String.h>@@ -13,6 +14,7 @@#include <AK/kmalloc.h>#include <LibWebCommon/Export.h>#include <LibWebCommon/WebDriver/Error.h>+#include <LibWebCommon/WebDriver/Network.h>namespace Web::WebDriver {@@ -53,7 +55,15 @@ struct WEBCOMMON_API BiDiSessionState {bool is_active { false };Vector<String> enabled_events;+ // NB: A null scope enables the event globally; otherwise it names top-level traversables.+ HashMap<String, Optional<Vector<String>>> enabled_event_contexts;Vector<BiDiPreloadScript> preload_scripts;+ Vector<Network::Intercept> network_intercepts;+ Vector<Network::Header> network_default_headers;+ HashMap<String, Vector<Network::Header>> network_user_context_headers;+ HashMap<String, Vector<Network::Header>> network_navigable_headers;+ String network_default_cache_behavior { "default"_string };+ HashMap<String, String> network_navigable_cache_behavior;};}diff --git a/Libraries/LibWebCommon/WebDriver/BiDi.ipc b/Libraries/LibWebCommon/WebDriver/BiDi.ipcindex f6a47711c5f..3a4328a4b84 100644--- a/Libraries/LibWebCommon/WebDriver/BiDi.ipc+++ b/Libraries/LibWebCommon/WebDriver/BiDi.ipc@@ -5,6 +5,23 @@#include <LibWebCommon/WebDriver/BiDi.h>+[ExistingCpp]+struct Web::WebDriver::Network::UrlPattern {+ Optional<String> protocol;+ Optional<String> hostname;+ Optional<String> port;+ Optional<String> pathname;+ Optional<String> search;+}++[ExistingCpp]+struct Web::WebDriver::Network::Intercept {+ String id;+ Vector<Web::WebDriver::Network::UrlPattern> url_patterns;+ Vector<String> phases;+ Optional<Vector<String>> browsing_contexts;+}+[ExistingCpp]struct Web::WebDriver::BiDiPreloadScript {String id;@@ -19,5 +36,12 @@ struct Web::WebDriver::BiDiPreloadScript {struct Web::WebDriver::BiDiSessionState {bool is_active;Vector<String> enabled_events;+ HashMap<String, Optional<Vector<String>>> enabled_event_contexts;Vector<Web::WebDriver::BiDiPreloadScript> preload_scripts;+ Vector<Web::WebDriver::Network::Intercept> network_intercepts;+ Vector<HTTP::Header> network_default_headers;+ HashMap<String, Vector<HTTP::Header>> network_user_context_headers;+ HashMap<String, Vector<HTTP::Header>> network_navigable_headers;+ String network_default_cache_behavior;+ HashMap<String, String> network_navigable_cache_behavior;}diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex b80aea8adfd..d582e884f66 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -1177,7 +1177,7 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(// NB: A WebDriver BiDi session gives its state to every process hosting web content when it changes.if (auto* webdriver_bidi = WebDriverBiDi::the(); webdriver_bidi && webdriver_bidi->session_state().is_active)- client->async_set_webdriver_bidi_session_state(webdriver_bidi->session_state());+ webdriver_bidi->push_session_state_for_client(*client);if (m_content_blocker_list_buffer.has_value())client->async_set_content_blockers(*m_content_blocker_list_buffer);diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex 5bdfe772965..29d882af80e 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -1018,6 +1018,8 @@ void CanonicalNavigable::abandon_populated_document(NonnullRefPtr<CanonicalDocumvoid CanonicalNavigable::place_populated_document(CanonicalDocument& document, WebContentPage& page){document.set_host(page);+ if (auto* bidi = WebDriverBiDi::the())+ bidi->push_session_state_for_client(page.client());send_viewport_to_host();}diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cppindex d1fcfc21f3b..762e70bfe37 100644--- a/Libraries/LibWebView/CanonicalTraversable.cpp+++ b/Libraries/LibWebView/CanonicalTraversable.cpp@@ -400,6 +400,8 @@ void CanonicalTraversable::release_page_if_unused(NonnullRefPtr<WebContentPage>return;if (page_hosts_any(page))return;+ if (auto* bidi = WebDriverBiDi::the())+ bidi->push_session_state_for_client(page->client());// A page left hosting none of the tab's documents goes on representing the tab to a process holding part of// another tab of its group, whose documents can hold the tab's WindowProxies.if (page->client().holds_part_of_a_tab_in_the_group_of(*this)) {@@ -439,6 +441,8 @@ void CanonicalTraversable::set_page_standing_in_for_lost_document(Badge<ViewImpl{did_lose_active_document();m_page_standing_in_for_lost_document = move(page);+ if (auto* bidi = WebDriverBiDi::the())+ bidi->push_session_state_for_client(m_page_standing_in_for_lost_document->client());}void CanonicalTraversable::did_activate_document_in(Badge<CanonicalNavigable>, WebContentPage& host)diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex e1c45994eca..6d6929bf4de 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -3064,6 +3064,17 @@ void ViewImplementation::run_webdriver_bidi_content_command(u64 command_id, Web:run_webdriver_content_command(command_id, navigable_id, method, move(params), {}, WebDriverProtocol::BiDi);}+// NB: An intercepted request resumes in the page that paused it, even during a document handoff.+void ViewImplementation::run_webdriver_bidi_content_command(WebContentPage& target, u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params)+{+ if (!target.is_open()) {+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchRequest, "Blocked request's page is closed"sv));+ return;+ }+ m_pending_webdriver_commands.set(command_id, { target, method, navigable_id, WebDriverProtocol::BiDi, true });+ target.async_run_webdriver_bidi_command(command_id, navigable_id, method, move(params));+}+void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol protocol){if (Web::WebDriver::is_input_state_command(name)) {@@ -3268,6 +3279,18 @@ void ViewImplementation::display_page_changed(RefPtr<WebContentPage> previous_paauto pending_webdriver_commands = move(m_pending_webdriver_commands);auto pending_webdriver_crash_commands = move(m_pending_webdriver_crash_commands);+ // NB: Restore commands that resume intercepted requests before any completion callback can reenter.+ // Their original page can still answer while a navigation replaces the displayed page.+ auto retain_commands_on_open_pages = [&](auto& commands) {+ commands.remove_all_matching([&](u64 command_id, PendingWebDriverCommand const& command) {+ if (!command.stays_on_page || !command.page->is_open())+ return false;+ m_pending_webdriver_commands.set(command_id, command);+ return true;+ });+ };+ retain_commands_on_open_pages(pending_webdriver_commands);+ retain_commands_on_open_pages(pending_webdriver_crash_commands);complete_webdriver_content_commands_after_process_replacement(pending_webdriver_commands);complete_webdriver_content_commands_after_process_replacement(pending_webdriver_crash_commands);}diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex c5fc8a68744..fe195e5e1ed 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -434,6 +434,7 @@ public:void run_webdriver_content_command(u64 command_id, Web::WebDriver::SessionBrowsingContext, String const& name, JsonValue payload, Vector<String> arguments);// https://w3c.github.io/webdriver-bidi/#commandsvoid run_webdriver_bidi_content_command(u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params);+ void run_webdriver_bidi_content_command(WebContentPage&, u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params);void run_webdriver_commands_waiting_for_a_document(Badge<CanonicalTraversable>);void did_complete_webdriver_content_command(WebContentPage&, u64 command_id, Web::WebDriver::Response);void did_set_webdriver_current_browsing_context(Badge<WebContentPage>, u64 command_id, Web::HTML::CrossProcessId navigable_id);@@ -986,6 +987,7 @@ protected:String name;Optional<Web::HTML::CrossProcessId> navigable_id;WebDriverProtocol protocol { WebDriverProtocol::Classic };+ bool stays_on_page { false };};HashMap<u64, PendingWebDriverCommand> m_pending_webdriver_commands;HashMap<u64, PendingWebDriverCommand> m_pending_webdriver_crash_commands;diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 22c019a7477..930ef4114c4 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -43,6 +43,7 @@#include <LibWebView/ViewImplementation.h>#include <LibWebView/WebContentClient.h>#include <LibWebView/WebContentTestClient.h>+#include <LibWebView/WebDriverBiDi.h>#include <LibWebView/WebUI.h>#include <LibWebView/WorkerProcessManager.h>@@ -278,6 +279,8 @@ WebContentPage& WebContentClient::open_page_for_new_top_level_traversable(Web::Pauto& page = open_page(page_id, traversable);traversable.active_document().set_host(page);+ if (auto* bidi = WebDriverBiDi::the())+ bidi->push_session_state_for_client(*this);return page;}diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 77f41847b2e..1e5f019daf9 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -643,8 +643,11 @@ void WebContentPage::close()}m_needs_beforeunload_check = true;m_history_recorded_url_for_current_load.clear();- if (m_client)+ if (m_client) {m_client->update_audio_capture_permission();+ if (auto* bidi = WebDriverBiDi::the())+ bidi->push_session_state_for_client(*m_client);+ }m_web_ui = nullptr;auto owed_replies = move(m_owed_replies);for (auto owed : owed_replies)diff --git a/Libraries/LibWebView/WebDriverBiDi.cpp b/Libraries/LibWebView/WebDriverBiDi.cppindex 94bd81bcce2..c3068dd03e5 100644--- a/Libraries/LibWebView/WebDriverBiDi.cpp+++ b/Libraries/LibWebView/WebDriverBiDi.cpp@@ -148,21 +148,58 @@ void WebDriverBiDi::ensure_session_is_active()push_session_state();}+static ErrorOr<CanonicalTraversable*, Web::WebDriver::Error> get_a_top_level_traversable(StringView);++void WebDriverBiDi::push_session_state_for_client(WebContentClient& client) const+{+ if (!m_session_state.is_active)+ return;++ HashTable<String> hosted_traversables;+ client.for_each_page([&](WebContentPage& page) {+ auto& traversable = page.traversable();+ if (page.displays_tab() || traversable.page_hosts_any(page)) {+ auto id = traversable.id();+ hosted_traversables.set(MUST(String::formatted("{}-{}", id.namespace_id, id.local_id)));+ }+ return IterationDecision::Continue;+ });+ client.async_set_webdriver_bidi_session_state(session_state_for_hosted_traversables(m_session_state, hosted_traversables));+}+void WebDriverBiDi::push_session_state(){m_session_state.is_active = true;+ // NB: A remote top-level navigable has a cross-process ID, but no local WebDriver window handle.+ Function<String(String const&)> context_id = [](String const& id) {+ auto navigable = get_a_top_level_traversable(id);+ if (navigable.is_error())+ return id;+ auto internal_id = navigable.value()->id();+ return MUST(String::formatted("{}-{}", internal_id.namespace_id, internal_id.local_id));+ };+ if (m_network)+ m_network->update_session_state(m_session_state, context_id);+ m_session_state.enabled_event_contexts = m_enabled_event_contexts;+ for (auto& [_, contexts] : m_session_state.enabled_event_contexts) {+ if (contexts.has_value()) {+ for (auto& id : *contexts)+ id = context_id(id);+ }+ }m_session_state.enabled_events.clear_with_capacity();for (auto const& event_name : m_enabled_events)m_session_state.enabled_events.append(event_name);WebContentClient::for_each_client([&](WebContentClient& client) {- client.async_set_webdriver_bidi_session_state(m_session_state);+ push_session_state_for_client(client);return IterationDecision::Continue;});}-void WebDriverBiDi::set_enabled_events(Vector<String> const& event_names)+void WebDriverBiDi::set_enabled_events(Vector<String> const& event_names, HashMap<String, Optional<Vector<String>>> event_contexts){+ m_enabled_event_contexts = move(event_contexts);m_enabled_events.clear();for (auto const& event_name : event_names)m_enabled_events.set(event_name);@@ -427,12 +464,14 @@ void WebDriverBiDi::remove_state_of_removed_navigables(){fail_navigations_of([](auto navigable_id) { return !navigable_exists(navigable_id); });+ m_blocked_network_requests.remove_all_matching([](auto const&, auto const& request) { return !request.page->is_open() || !navigable_exists(request.navigable_id); });m_destroyed_navigables.remove_all_matching([](auto navigable_id) { return !navigable_exists(navigable_id); });m_closing_traversable_infos.remove_all_matching([](auto navigable_id, auto const&) { return !navigable_exists(navigable_id); });}void WebDriverBiDi::top_level_traversable_did_crash(CanonicalTraversable const& traversable){+ m_blocked_network_requests.remove_all_matching([&](auto const&, auto const& request) { return CanonicalTraversable::traversable_containing(request.navigable_id) == &traversable; });fail_navigations_of([&](auto navigable_id) { return CanonicalTraversable::traversable_containing(navigable_id) == &traversable; });}@@ -523,8 +562,10 @@ void WebDriverBiDi::top_level_traversable_is_closing(CanonicalNavigable const& tvoid WebDriverBiDi::top_level_traversable_did_close(String const& window_handle){- if (m_network)+ if (m_network) {m_network->context_destroyed(window_handle);+ push_session_state();+ }auto os_window = os_window_of(window_handle);m_tab_windows.remove(window_handle);@@ -837,14 +878,11 @@ void WebDriverBiDi::did_receive_event(WebContentPage& page, Web::HTML::CrossProc"network.responseStarted"sv,"network.responseCompleted"sv,"network.fetchError"sv,+ "network.authRequired"sv,});if (!any_of(content_events, [&](auto event_name) { return event_name == name; }))return;- // NB: WebDriver buffers the log events that no subscription enables.- if (!is_event_enabled(name) && name != "log.entryAdded"sv)- return;-// NB: The navigable an event names is the navigable the process reported it for, which the browser process names// itself, so that a process cannot attribute an event to a navigable it does not host.if (!params.is_object())@@ -860,6 +898,23 @@ void WebDriverBiDi::did_receive_event(WebContentPage& page, Web::HTML::CrossProcset_context(params.as_object());}+ if (name.starts_with_bytes("network."sv)) {+ if (auto request = params.as_object().get_object("request"sv); request.has_value()) {+ if (auto id = request->get_string("request"sv); id.has_value()) {+ auto existing = m_blocked_network_requests.find(*id);+ if (existing != m_blocked_network_requests.end() && existing->value.page != &page)+ return;+ if (params.as_object().get_bool("isBlocked"sv).value_or(false))+ m_blocked_network_requests.set(*id, { page, navigable_id, m_next_network_interception_generation++ });+ else if (name.is_one_of("network.responseCompleted"sv, "network.fetchError"sv))+ m_blocked_network_requests.remove(*id);+ }+ }+ }+ // NB: Route bookkeeping also runs for events whose subscription changed while they were in flight.+ // WebDriver buffers the log events that no subscription enables.+ if (!is_event_enabled(name) && name != "log.entryAdded"sv)+ return;emit_event_for_navigable(name, move(params), *navigable);}@@ -1016,14 +1071,38 @@ void WebDriverBiDi::run_command(u64 command_id, String const& method, JsonValueif (method.starts_with_bytes("network."sv)) {if (!m_network)m_network = make<WebDriverBiDiNetwork>();+ if (method.is_one_of("network.continueRequest"sv, "network.continueResponse"sv, "network.provideResponse"sv, "network.continueWithAuth"sv, "network.failRequest"sv)) {+ auto validation = Web::WebDriver::Network::validate_interception_parameters(method, params);+ if (validation.is_error()) {+ on_complete(validation.release_error());+ return;+ }+ auto id = params.get_string("request"sv).release_value();+ if (auto blocked = m_blocked_network_requests.get(id); blocked.has_value() && blocked->page->routed_connection()) {+ auto content_command_id = m_next_content_command_id++;+ m_pending_content_commands.set(content_command_id, [id, generation = blocked->generation, on_complete = move(on_complete)](Web::WebDriver::Response response) mutable {+ if (!response.is_error()) {+ if (auto* bidi = WebDriverBiDi::the()) {+ if (auto current = bidi->m_blocked_network_requests.get(id); current.has_value() && current->generation == generation)+ bidi->m_blocked_network_requests.remove(id);+ }+ }+ on_complete(move(response));+ });+ blocked->page->view().run_webdriver_bidi_content_command(*blocked->page, content_command_id, blocked->navigable_id, method, params);+ return;+ }+ }auto result = m_network->run_command(method, params, [](String const& id) -> ErrorOr<void, Web::WebDriver::Error> {TRY(get_a_top_level_traversable(id));return {};});if (result.is_error())on_complete(result.release_error());- else+ else {+ push_session_state();on_complete(result.release_value());+ }return;}diff --git a/Libraries/LibWebView/WebDriverBiDi.h b/Libraries/LibWebView/WebDriverBiDi.hindex da0b208f3dc..9e0123c1f03 100644--- a/Libraries/LibWebView/WebDriverBiDi.h+++ b/Libraries/LibWebView/WebDriverBiDi.h@@ -46,10 +46,11 @@ public:void run_command(u64 command_id, String const& method, JsonValue params);void get_top_level_traversables(u64 command_id, Vector<String> const& navigable_ids);void run_subscribe_steps(u64 command_id, String const& event_name, Vector<String> const& top_level_traversable_ids);- void set_enabled_events(Vector<String> const& event_names);+ void set_enabled_events(Vector<String> const& event_names, HashMap<String, Optional<Vector<String>>> event_contexts);bool is_event_enabled(StringView event_name) const { return m_enabled_events.contains(event_name); }Web::WebDriver::BiDiSessionState const& session_state() const { return m_session_state; }+ void push_session_state_for_client(WebContentClient&) const;// Completes a command that a process hosting a navigable ran, if this object sent it.bool did_complete_content_command(u64 command_id, Web::WebDriver::Response&);@@ -160,9 +161,17 @@ private:WebDriverBrowserConnection& m_connection;HashTable<String> m_enabled_events;+ HashMap<String, Optional<Vector<String>>> m_enabled_event_contexts;Web::WebDriver::BiDiSessionState m_session_state;OwnPtr<WebDriverBiDiNetwork> m_network;+ struct BlockedNetworkRequest {+ RefPtr<WebContentPage> page;+ Web::HTML::CrossProcessId navigable_id;+ u64 generation;+ };+ u64 m_next_network_interception_generation { 0 };+ HashMap<String, BlockedNetworkRequest> m_blocked_network_requests;u64 m_next_content_command_id;HashMap<u64, CommandResult> m_pending_content_commands;diff --git a/Libraries/LibWebView/WebDriverBiDiNetwork.cpp b/Libraries/LibWebView/WebDriverBiDiNetwork.cppindex d6a83b18957..76dec3bb947 100644--- a/Libraries/LibWebView/WebDriverBiDiNetwork.cpp+++ b/Libraries/LibWebView/WebDriverBiDiNetwork.cpp@@ -11,6 +11,18 @@namespace WebView {+Web::WebDriver::BiDiSessionState session_state_for_hosted_traversables(Web::WebDriver::BiDiSessionState const& state, HashTable<String> const& hosted_traversables)+{+ auto filtered_state = state;+ filtered_state.network_navigable_headers.remove_all_matching([&](auto const& key, auto const&) {+ return !hosted_traversables.contains(key);+ });+ filtered_state.network_navigable_cache_behavior.remove_all_matching([&](auto const& key, auto const&) {+ return !hosted_traversables.contains(key);+ });+ return filtered_state;+}+using Web::WebDriver::as_js_uint;using Web::WebDriver::Error;using Web::WebDriver::ErrorCode;@@ -314,7 +326,7 @@ ErrorOr<JsonValue, Error> WebDriverBiDiNetwork::run_command(StringView method, J// "default"// Perform implementation-defined steps to enable any implementation-specific resource caches that// are usually enabled in the current remote end configuration.- // FIXME: Apply the cache behavior to Fetch and implementation-specific resource caches.+ // NB: The updated session state applies this to subsequent fetches.// 4. Return success with data null.return JsonValue {};}@@ -340,7 +352,7 @@ ErrorOr<JsonValue, Error> WebDriverBiDiNetwork::run_command(StringView method, J// Perform implementation-defined steps to enable any implementation-specific resource caches that// are usually enabled in the current remote end configuration for network requests originating// from any browsing context for which navigable is the top-level browsing context.- // FIXME: Apply the cache behavior to Fetch and implementation-specific resource caches.+ // NB: The updated session state applies this to subsequent fetches.// 3. If behavior is equal to default cache behavior:if (behavior == m_default_cache_behavior) {// 1. If navigable cache behavior map contains navigable, remove navigable cache behavior map[navigable].@@ -364,15 +376,37 @@ ErrorOr<JsonValue, Error> WebDriverBiDiNetwork::run_command(StringView method, J// 1. Let blocked requests be session's blocked request map.// 2. Let request id be command parameters["request"].// 3. If blocked requests does not contain request id then return error with error code no such request.- // NB: Nothing adds requests to the blocked request map until Fetch supports interception, so it is always- // empty. network.continueResponse and network.provideResponse perform this lookup in update the- // response.- // FIXME: Look up blocked requests once Fetch supports interception.+ // NB: The browser routes known blocked requests to the process that paused them before reaching this lookup.return Error::from_code(ErrorCode::NoSuchRequest, "Blocked request not found"sv);}return Error::from_code(ErrorCode::UnknownCommand, "Command is not supported"sv);}+void WebDriverBiDiNetwork::update_session_state(Web::WebDriver::BiDiSessionState& state, Function<String(String const&)> const& context_id) const+{+ state.network_intercepts.clear();+ for (auto const& [id, intercept] : m_intercept_map) {+ Vector<String> phases;+ for (auto const& phase : intercept.phases)+ phases.append(phase);+ auto contexts = intercept.browsing_contexts;+ if (contexts.has_value()) {+ for (auto& context : *contexts)+ context = context_id(context);+ }+ state.network_intercepts.append({ id, intercept.url_patterns, move(phases), move(contexts) });+ }+ state.network_default_headers = m_default_headers;+ state.network_user_context_headers = m_user_context_headers;+ state.network_navigable_headers.clear();+ for (auto const& [id, headers] : m_navigable_headers)+ state.network_navigable_headers.set(context_id(id), headers);+ state.network_default_cache_behavior = m_default_cache_behavior;+ state.network_navigable_cache_behavior.clear();+ for (auto const& [id, behavior] : m_navigable_cache_behavior_map)+ state.network_navigable_cache_behavior.set(context_id(id), behavior);+}+void WebDriverBiDiNetwork::context_destroyed(String const& id){// NB: Navigable headers and the navigable cache behavior map are weak maps keyed by top-level traversables. We keydiff --git a/Libraries/LibWebView/WebDriverBiDiNetwork.h b/Libraries/LibWebView/WebDriverBiDiNetwork.hindex 80adcbc40dd..743df4289b8 100644--- a/Libraries/LibWebView/WebDriverBiDiNetwork.h+++ b/Libraries/LibWebView/WebDriverBiDiNetwork.h@@ -9,10 +9,13 @@#include <AK/Function.h>#include <AK/HashMap.h>#include <AK/HashTable.h>-#include <LibWebCommon/WebDriver/Network.h>+#include <LibWebCommon/WebDriver/BiDi.h>+#include <LibWebView/Export.h>namespace WebView {+WEBVIEW_API Web::WebDriver::BiDiSessionState session_state_for_hosted_traversables(Web::WebDriver::BiDiSessionState const&, HashTable<String> const&);+// NB: The network state belongs to the browser side of a BiDi session, where context IDs can be resolved.class WebDriverBiDiNetwork {AK_ALLOC_WITH_KMALLOC;@@ -20,6 +23,7 @@ class WebDriverBiDiNetwork {public:using ValidateContext = Function<ErrorOr<void, Web::WebDriver::Error>(String const&)>;ErrorOr<JsonValue, Web::WebDriver::Error> run_command(StringView method, JsonObject const&, ValidateContext const&);+ void update_session_state(Web::WebDriver::BiDiSessionState&, Function<String(String const&)> const& context_id) const;void context_destroyed(String const&);private:@@ -29,7 +33,7 @@ private:HashTable<String> phases;Optional<Vector<String>> browsing_contexts;};- HashMap<String, Intercept> m_intercept_map;+ OrderedHashMap<String, Intercept> m_intercept_map;// https://w3c.github.io/webdriver-bidi/#network-collectorsstruct Collector {diff --git a/Libraries/LibWebView/WebDriverBrowserConnection.cpp b/Libraries/LibWebView/WebDriverBrowserConnection.cppindex 0de514cd661..d4a7bc8cb80 100644--- a/Libraries/LibWebView/WebDriverBrowserConnection.cpp+++ b/Libraries/LibWebView/WebDriverBrowserConnection.cpp@@ -325,9 +325,9 @@ void WebDriverBrowserConnection::bidi_run_subscribe_steps(u64 command_id, Stringm_webdriver_bidi->run_subscribe_steps(command_id, event_name, top_level_traversable_ids);}-void WebDriverBrowserConnection::set_bidi_enabled_events(Vector<String> event_names)+void WebDriverBrowserConnection::set_bidi_enabled_events(Vector<String> event_names, HashMap<String, Optional<Vector<String>>> event_contexts){- m_webdriver_bidi->set_enabled_events(event_names);+ m_webdriver_bidi->set_enabled_events(event_names, move(event_contexts));}}diff --git a/Libraries/LibWebView/WebDriverBrowserConnection.h b/Libraries/LibWebView/WebDriverBrowserConnection.hindex 65ebbee45e5..656d0d80964 100644--- a/Libraries/LibWebView/WebDriverBrowserConnection.h+++ b/Libraries/LibWebView/WebDriverBrowserConnection.h@@ -45,7 +45,7 @@ private:virtual void bidi_command(u64 command_id, String method, JsonValue params) override;virtual void bidi_get_top_level_traversables(u64 command_id, Vector<String> navigable_ids) override;virtual void bidi_run_subscribe_steps(u64 command_id, String event_name, Vector<String> top_level_traversable_ids) override;- virtual void set_bidi_enabled_events(Vector<String> event_names) override;+ virtual void set_bidi_enabled_events(Vector<String> event_names, HashMap<String, Optional<Vector<String>>> event_contexts) override;NonnullOwnPtr<WebDriverBiDi> m_webdriver_bidi;};diff --git a/Services/WebContent/WebDriverBiDi.cpp b/Services/WebContent/WebDriverBiDi.cppindex 8c15883c8e8..c2ae8c367b0 100644--- a/Services/WebContent/WebDriverBiDi.cpp+++ b/Services/WebContent/WebDriverBiDi.cpp@@ -15,6 +15,7 @@#include <LibWeb/WebDriver/BiDi/BiDi.h>#include <LibWeb/WebDriver/BiDi/BrowsingContext.h>#include <LibWeb/WebDriver/BiDi/Input.h>+#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebDriver/BiDi/Script.h>#include <LibWebCommon/WebDriver/Input.h>#include <WebContent/ConnectionFromClient.h>@@ -87,17 +88,21 @@ void run_webdriver_bidi_command(PageClient& page_client, u64 command_id, Web::HTpage_client->webdriver_command_complete(command_id, move(response));};- auto navigable = page_client.page().navigable_with_id(navigable_id);- if (!navigable) {- on_complete(no_such_frame());- return;- }if (!params_value.is_object()) {on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Command parameters must be an object"sv));return;}auto const& params = params_value.as_object();+ if (method.starts_with_bytes("network."sv))+ return on_complete(Web::WebDriver::BiDi::continue_network_request(method, params));++ auto navigable = page_client.page().navigable_with_id(navigable_id);+ if (!navigable) {+ on_complete(no_such_frame());+ return;+ }+if (method == "script.evaluate"sv)return Web::WebDriver::BiDi::evaluate(*navigable, params, move(on_complete));if (method == "script.callFunction"sv)diff --git a/Services/WebDriver/BiDiSession.cpp b/Services/WebDriver/BiDiSession.cppindex bd378688241..27ac0f68e7f 100644--- a/Services/WebDriver/BiDiSession.cpp+++ b/Services/WebDriver/BiDiSession.cpp@@ -690,19 +690,27 @@ HashTable<String> BiDiSession::set_of_top_level_traversables_for_which_an_event_void BiDiSession::update_enabled_events(){HashTable<String> enabled_events;+ HashMap<String, Optional<Vector<String>>> event_contexts;for (auto const& subscription : m_subscriptions) {- for (auto const& event_name : subscription.event_names)+ for (auto const& event_name : subscription.event_names) {enabled_events.set(event_name);+ auto& contexts = event_contexts.ensure(event_name, [] { return Optional<Vector<String>> { Vector<String> {} }; });+ if (subscription.is_global() || subscription.user_context_ids.contains("default"_string)) {+ contexts.clear();+ } else if (contexts.has_value()) {+ for (auto const& id : subscription.top_level_traversable_ids) {+ if (!contexts->contains_slow(id))+ contexts->append(id);+ }+ }+ }}-- if (sets_are_equal(enabled_events, m_enabled_events))- return;m_enabled_events = move(enabled_events);Vector<String> event_names;for (auto const& event_name : m_enabled_events)event_names.append(event_name);- m_session.set_bidi_enabled_events(move(event_names));+ m_session.set_bidi_enabled_events(move(event_names), move(event_contexts));}void BiDiSession::did_receive_event(String const& name, JsonValue params, Vector<String> const& top_level_traversable_ids, Vector<String> const& user_context_ids)diff --git a/Services/WebDriver/Session.cpp b/Services/WebDriver/Session.cppindex bd7a3c3458c..981907316a9 100644--- a/Services/WebDriver/Session.cpp+++ b/Services/WebDriver/Session.cpp@@ -922,10 +922,10 @@ NonnullRefPtr<Session::WebDriverPromise> Session::run_bidi_subscribe_steps(Strin});}-void Session::set_bidi_enabled_events(Vector<String> event_names)+void Session::set_bidi_enabled_events(Vector<String> event_names, HashMap<String, Optional<Vector<String>>> event_contexts){if (m_browser_connection)- m_browser_connection->async_set_bidi_enabled_events(move(event_names));+ m_browser_connection->async_set_bidi_enabled_events(move(event_names), move(event_contexts));}ErrorOr<void, Web::WebDriver::Error> Session::ensure_current_window_handle_is_valid() constdiff --git a/Services/WebDriver/Session.h b/Services/WebDriver/Session.hindex f0c36371b28..1d3e87dc961 100644--- a/Services/WebDriver/Session.h+++ b/Services/WebDriver/Session.h@@ -113,7 +113,7 @@ public:NonnullRefPtr<WebDriverPromise> perform_bidi_browser_command(StringView method, JsonValue params);NonnullRefPtr<WebDriverPromise> get_bidi_top_level_traversables(Vector<String> navigable_ids);NonnullRefPtr<WebDriverPromise> run_bidi_subscribe_steps(String const& event_name, Vector<String> top_level_traversable_ids);- void set_bidi_enabled_events(Vector<String> event_names);+ void set_bidi_enabled_events(Vector<String> event_names, HashMap<String, Optional<Vector<String>>> event_contexts);private:Session(NonnullRefPtr<Client> client, JsonObject const& capabilities, String session_id, Web::WebDriver::SessionFlags flags);diff --git a/Services/WebDriver/WebDriverBrowserClient.ipc b/Services/WebDriver/WebDriverBrowserClient.ipcindex d606b906d6e..8641ba7e367 100644--- a/Services/WebDriver/WebDriverBrowserClient.ipc+++ b/Services/WebDriver/WebDriverBrowserClient.ipc@@ -25,5 +25,5 @@ endpoint WebDriverBrowserClient {bidi_command(u64 command_id, String method, JsonValue params) =|bidi_get_top_level_traversables(u64 command_id, Vector<String> navigable_ids) =|bidi_run_subscribe_steps(u64 command_id, String event_name, Vector<String> top_level_traversable_ids) =|- set_bidi_enabled_events(Vector<String> event_names) =|+ set_bidi_enabled_events(Vector<String> event_names, HashMap<String, Optional<Vector<String>>> event_contexts) =|}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 26b40e1b9c2..2166256be24 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -26,6 +26,7 @@ set(TEST_SOURCESTestStorageAreaRegistry.cppTestStorageJar.cppTestTabPerformanceStats.cpp+ TestWebDriverBiDiNetwork.cppTestWebViewURL.cpp)diff --git a/Tests/LibWebView/TestWebDriverBiDiNetwork.cpp b/Tests/LibWebView/TestWebDriverBiDiNetwork.cppnew file mode 100644index 00000000000..8d201f6d9d3--- /dev/null+++ b/Tests/LibWebView/TestWebDriverBiDiNetwork.cpp@@ -0,0 +1,42 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibTest/TestCase.h>+#include <LibWebView/WebDriverBiDiNetwork.h>++TEST_CASE(scoped_network_state_only_contains_hosted_traversables)+{+ Web::WebDriver::BiDiSessionState state;+ state.is_active = true;+ state.network_default_headers.append({ "X-Default", "default" });+ state.network_user_context_headers.set("user"_string, { { "X-User", "user" } });+ state.network_navigable_headers.set("1-1"_string, { { "Authorization", "first-secret" } });+ state.network_navigable_headers.set("2-1"_string, { { "Authorization", "second-secret" } });+ state.network_navigable_headers.set("3-1"_string, { { "Authorization", "foreign-secret" } });+ state.network_navigable_cache_behavior.set("1-1"_string, "bypass"_string);+ state.network_navigable_cache_behavior.set("3-1"_string, "bypass"_string);++ HashTable<String> hosted;+ hosted.set("1-1"_string);+ hosted.set("2-1"_string);+ auto filtered = WebView::session_state_for_hosted_traversables(state, hosted);+ EXPECT(filtered.is_active);+ EXPECT_EQ(filtered.network_navigable_headers.size(), 2u);+ EXPECT(filtered.network_navigable_headers.contains("1-1"sv));+ EXPECT(filtered.network_navigable_headers.contains("2-1"sv));+ EXPECT(!filtered.network_navigable_headers.contains("3-1"sv));+ EXPECT_EQ(filtered.network_navigable_cache_behavior.size(), 1u);+ EXPECT(!filtered.network_navigable_cache_behavior.contains("3-1"sv));+ EXPECT_EQ(filtered.network_default_headers.size(), 1u);+ EXPECT_EQ(filtered.network_user_context_headers.size(), 1u);+ EXPECT_EQ(state.network_navigable_headers.size(), 3u);+ EXPECT_EQ(state.network_navigable_cache_behavior.size(), 2u);++ auto unhosted = WebView::session_state_for_hosted_traversables(state, {});+ EXPECT(unhosted.network_navigable_headers.is_empty());+ EXPECT(unhosted.network_navigable_cache_behavior.is_empty());+ EXPECT_EQ(unhosted.network_default_headers.size(), 1u);+}diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.pyindex e1ff3b2e7f7..8ee3de4ab78 100755--- a/Tests/LibWebView/test-webdriver-bidi.py+++ b/Tests/LibWebView/test-webdriver-bidi.py@@ -127,12 +127,91 @@ class ReloadServer(http.server.ThreadingHTTPServer):self.range_request_received: threading.Event = threading.Event()self.release_initial_download: threading.Event = threading.Event()self.initial_download_stopped: threading.Event = threading.Event()+ self.interception_lock = threading.Lock()+ self.interception_requests = []+ self.interception_received = threading.Event()+ self.release_interception = threading.Event()+ self.detached_final_received = threading.Event()+ self.interception_transport_closed = threading.Event()class ReloadHandler(http.server.BaseHTTPRequestHandler):+ def do_POST(self):+ self.do_GET()++ def do_PUT(self):+ self.do_GET()+def do_GET(self):server = self.serverassert isinstance(server, ReloadServer)+ if self.path == "/network-interception/fail-body":+ self.send_response(200)+ self.send_header("Content-Length", "1000000")+ self.end_headers()+ self.wfile.write(b"unfinished body")+ self.wfile.flush()+ self.connection.settimeout(30)+ try:+ if not self.connection.recv(1):+ server.interception_transport_closed.set()+ except (ConnectionResetError, BrokenPipeError):+ server.interception_transport_closed.set()+ return+ if 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.+ length = int(self.headers.get("Content-Length", "0").split(",", 1)[0])+ if self.command == "GET" and self.path.startswith("/network-interception/echo-final/"):+ length = 0+ body = self.rfile.read(length)+ record = {+ "path": self.path,+ "method": self.command,+ "body": body.decode(),+ "headers": list(self.headers.items()),+ }+ with server.interception_lock:+ server.interception_requests.append(record)+ if self.path == "/network-interception/detached-final":+ server.detached_final_received.set()+ if self.path in ["/network-interception/late-enable", "/network-interception/detached-redirect"]:+ server.interception_received.set()+ if not server.release_interception.wait(30):+ raise TimeoutError("The test did not release its intercepted response")+ if self.path.startswith("/network-interception/echo-redirect/"):+ self.send_response(303 if self.path.endswith("303") else 307)+ self.send_header("Location", self.path.replace("/echo-redirect/", "/echo-final/", 1))+ body = b""+ elif self.path.startswith("/network-interception/redirect/"):+ target = self.path.replace("/redirect/", "/final/", 1)+ self.send_response(307)+ self.send_header("Location", target)+ body = b""+ elif self.path == "/network-interception/detached-redirect":+ self.send_response(302)+ self.send_header("Location", "/network-interception/detached-final")+ body = b""+ elif self.path.startswith("/network-interception/auth/") and self.headers.get("Authorization") is None:+ self.send_response(401)+ self.send_header("WWW-Authenticate", 'Basic realm="bidi-selective-overrides"')+ if origin := self.headers.get("Origin"):+ self.send_header("Access-Control-Allow-Origin", origin)+ self.send_header("Access-Control-Allow-Credentials", "true")+ body = b"authentication required"+ else:+ self.send_response(200)+ with server.interception_lock:+ body = json.dumps(server.interception_requests).encode()+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ try:+ self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError):+ pass+ returnif self.path == "/network-download/split":body = server.segmented_download_bodyrange_header = self.headers.get("Range")@@ -225,6 +304,756 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):pass+def intercepted_event(bidi, method, url):+ while True:+ event = bidi.event(method)+ if event["request"]["url"] == url:+ assert event["isBlocked"], event+ return event+ assert not event["isBlocked"], event+++def send_fetch(bidi, context, url, options=None):+ return bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "expression": f"fetch({json.dumps(url)}, {json.dumps(options or {})}).then(response => response.text())",+ "awaitPromise": True,+ },+ )+++def fetch_records(bidi, command):+ result = bidi.response(command)+ assert result["type"] == "success" and result["result"]["type"] == "success", result+ return json.loads(result["result"]["result"]["value"])+++def check_network_late_interception(bidi, context, server, abort=False):+ url = f"http://127.0.0.1:{server.server_port}/network-interception/late-enable"+ server.interception_received.clear()+ server.release_interception.clear()+ with server.interception_lock:+ server.interception_requests.clear()+ if abort:+ pending = bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "expression": f"window.interceptionAbort = new AbortController(); fetch({json.dumps(url)}, "+ "{signal: interceptionAbort.signal}).then(() => 'fulfilled', error => error.name)",+ "awaitPromise": True,+ },+ )+ else:+ pending = send_fetch(bidi, context, url)+ assert server.interception_received.wait(30), "The unobserved request did not reach the server"+ subscription = bidi.command("session.subscribe", {"events": ["network.responseStarted"]})["subscription"]+ intercept = bidi.command(+ "network.addIntercept",+ {"phases": ["responseStarted"], "urlPatterns": [{"type": "string", "pattern": url}]},+ )["intercept"]+ try:+ # NB: State broadcasts and response delivery come from different IPC peers.+ bidi.evaluate(context, "0")+ server.release_interception.set()+ event = intercepted_event(bidi, "network.responseStarted", url)+ request_id = event["request"]["request"]+ if abort:+ bidi.evaluate(context, "interceptionAbort.abort(); 0")+ result = bidi.response(pending)+ assert result["type"] == "success" and result["result"]["result"]["value"] == "AbortError", result+ result = bidi.response(bidi.send("network.continueResponse", {"request": request_id}))+ assert result["type"] == "error" and result["error"] == "no such request", result+ else:+ # A known blocked request stays resumable when its event subscription is removed.+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+ subscription = None+ bidi.command("network.continueResponse", {"request": request_id})+ records = fetch_records(bidi, pending)+ assert [record["path"] for record in records] == ["/network-interception/late-enable"], records+ finally:+ server.release_interception.set()+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ if subscription is not None:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_override_retries(bidi, context, server, kinds):+ origin = f"http://127.0.0.1:{server.server_port}"+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent", "network.authRequired"]})[+ "subscription"+ ]++ def header_values(record, name):+ return [value for key, value in record["headers"] if key.lower() == name.lower()]++ def check_record(record, method, body, *, generated=True):+ assert record["method"] == method and record["body"] == body, record+ assert header_values(record, "Content-Length") == [str(len(body.encode()))], record+ for name in [+ "Referer",+ "Origin",+ "Sec-Fetch-Dest",+ "Sec-Fetch-Mode",+ "Sec-Fetch-Site",+ "Sec-Fetch-User",+ "User-Agent",+ "Content-Type",+ "Cache-Control",+ "Pragma",+ ]:+ assert len(header_values(record, name)) <= 1, (name, record)+ if generated:+ for name, value in [+ ("Referer", f"{origin}/interception-page"),+ ("Sec-Fetch-Dest", "empty"),+ ("Sec-Fetch-Mode", "cors"),+ ("Sec-Fetch-Site", "same-origin"),+ ]:+ assert header_values(record, name) == [value], (name, record)+ assert len(header_values(record, "User-Agent")) == 1, record+ if header_values(record, "Origin"):+ assert header_values(record, "Origin") == [origin], record++ try:+ for kind in kinds:+ with server.interception_lock:+ server.interception_requests.clear()+ start_url = f"{origin}/network-interception/start/{kind}"+ target_url = f"{origin}/network-interception/{'auth' if kind == 'auth' else 'redirect'}/{kind}"+ intercepts = [+ bidi.command(+ "network.addIntercept",+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": start_url}]},+ )["intercept"]+ ]+ if kind == "auth":+ intercepts.append(+ bidi.command(+ "network.addIntercept",+ {"phases": ["authRequired"], "urlPatterns": [{"type": "string", "pattern": target_url}]},+ )["intercept"]+ )+ pending = send_fetch(+ bidi, context, start_url, {"method": "POST", "body": "original-body", "cache": "no-store"}+ )+ event = intercepted_event(bidi, "network.beforeRequestSent", start_url)+ overrides = {"request": event["request"]["request"], "url": target_url}+ method, body = "POST", "original-body"+ if kind == "overrides":+ method, body = "PUT", "overridden payload"+ overrides.update(+ {+ "method": method,+ "body": {"type": "string", "value": body},+ "headers": [+ {+ "name": "Content-Type",+ "value": {"type": "string", "value": "application/x-bidi-override"},+ },+ {"name": "X-Client-Override", "value": {"type": "string", "value": "kept"}},+ ],+ "cookies": [{"name": "bidi_override", "value": {"type": "string", "value": "kept"}}],+ }+ )+ bidi.command("network.continueRequest", overrides)+ if kind == "auth":+ event = intercepted_event(bidi, "network.authRequired", target_url)+ bidi.command(+ "network.continueWithAuth",+ {+ "request": event["request"]["request"],+ "action": "provideCredentials",+ "credentials": {"type": "password", "username": "user", "password": "pass"},+ },+ )+ records = fetch_records(bidi, pending)+ assert len(records) == 2, records+ assert records[0]["path"] == urllib.parse.urlsplit(target_url).path, records+ expected_final = target_url if kind == "auth" else target_url.replace("/redirect/", "/final/", 1)+ assert records[-1]["path"] == urllib.parse.urlsplit(expected_final).path, records+ for index, record in enumerate(records):+ check_record(record, method, body, generated=kind != "overrides" or index != 0)+ if kind == "overrides":+ assert header_values(record, "X-Client-Override") == ["kept"], record+ assert header_values(record, "Content-Type") == ["application/x-bidi-override"], record+ assert header_values(record, "Cookie") == ["bidi_override=kept"], record+ if kind == "auth":+ assert header_values(records[-1], "Authorization") == ["Basic dXNlcjpwYXNz"], records+ for intercept in intercepts:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_echoed_headers(bidi, context, server, kinds):+ origin = f"http://127.0.0.1:{server.server_port}"+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent", "network.authRequired"]})[+ "subscription"+ ]++ subscribed = True++ def values(record, name):+ return [value for key, value in record["headers"] if key.lower() == name.lower()]++ try:+ for kind in kinds:+ if not subscribed:+ subscription = bidi.command(+ "session.subscribe", {"events": ["network.beforeRequestSent", "network.authRequired"]}+ )["subscription"]+ subscribed = True+ with server.interception_lock:+ server.interception_requests.clear()+ start_url = f"{origin}/network-interception/start/{kind}"+ auth = kind.endswith("auth")+ target_url = f"{origin}/network-interception/{'auth' if auth else 'echo-redirect'}/{kind}"+ intercepts = [+ bidi.command(+ "network.addIntercept",+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": start_url}]},+ )["intercept"]+ ]+ if auth:+ intercepts.append(+ bidi.command(+ "network.addIntercept",+ {"phases": ["authRequired"], "urlPatterns": [{"type": "string", "pattern": target_url}]},+ )["intercept"]+ )+ options: dict[str, object] = {"method": "POST", "body": "original-body"}+ if kind.endswith("range"):+ options["headers"] = {"Range": "bytes=0-9"}+ pending = send_fetch(bidi, context, start_url, options)+ event = intercepted_event(bidi, "network.beforeRequestSent", start_url)+ headers = list(event["request"]["headers"])+ expected = {+ "Referer": f"{origin}/interception-page",+ "Origin": origin,+ "Sec-Fetch-Dest": "empty",+ "Sec-Fetch-Mode": "cors",+ "Sec-Fetch-Site": "same-origin",+ "X-Client-Override": "kept",+ }+ if kind.endswith("range"):+ expected["Accept-Encoding"] = "identity"+ changed = {"X-Client-Override": "kept"}+ if kind.startswith("explicit"):+ changed.update(+ {+ "Referer": f"{origin}/explicit-referrer",+ "Origin": "null",+ "Sec-Fetch-Dest": "object",+ "Sec-Fetch-Mode": "no-cors",+ "Sec-Fetch-Site": "same-site",+ }+ )+ if kind == "explicit-range":+ changed["Accept-Encoding"] = "gzip"+ for name, value in changed.items():+ headers = [header for header in headers if header["name"].lower() != name.lower()]+ headers.append({"name": name, "value": {"type": "string", "value": value}})+ expected.update(changed)+ overrides = {"request": event["request"]["request"], "url": target_url, "headers": headers}+ body = "original-body"+ if kind == "echo-body":+ body = "replacement-body-is-longer"+ overrides["body"] = {"type": "string", "value": body}+ if kind == "explicit-unsubscribe":+ for intercept in intercepts:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ intercepts.clear()+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+ subscribed = False+ bidi.command("network.continueRequest", overrides)+ if auth:+ event = intercepted_event(bidi, "network.authRequired", target_url)+ bidi.command(+ "network.continueWithAuth",+ {+ "request": event["request"]["request"],+ "action": "provideCredentials",+ "credentials": {"type": "password", "username": "user", "password": "pass"},+ },+ )+ records = fetch_records(bidi, pending)+ assert len(records) == 2, records+ for index, record in enumerate(records):+ drops_body = index == 1 and kind.endswith("303")+ assert record["method"] == ("GET" if drops_body else "POST"), record+ assert record["body"] == ("" if drops_body else body), record+ assert values(record, "Content-Length") == ([] if drops_body else [str(len(body))]), record+ for name, value in expected.items():+ assert values(record, name) == [value], (name, record)+ assert len(values(record, "Content-Type")) == (0 if drops_body else 1), record+ assert records[0]["path"] == urllib.parse.urlsplit(target_url).path, records+ final_url = target_url if auth else target_url.replace("/echo-redirect/", "/echo-final/", 1)+ assert records[-1]["path"] == urllib.parse.urlsplit(final_url).path, records+ if auth:+ assert values(records[0], "Authorization") == [], records+ assert values(records[1], "Authorization") == ["Basic dXNlcjpwYXNz"], records+ for intercept in intercepts:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ finally:+ if sys.exc_info()[0] is None and subscribed:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_detached_interception(bidi, context, server):+ origin = f"http://127.0.0.1:{server.server_port}"+ url = f"{origin}/network-interception/detached-redirect"+ final_url = f"{origin}/network-interception/detached-final"+ server.interception_received.clear()+ server.release_interception.clear()+ server.detached_final_received.clear()+ with server.interception_lock:+ server.interception_requests.clear()+ bidi.evaluate(+ context,+ f"""new Promise(resolve => {{+ const frame = document.createElement('iframe');+ frame.id = 'interception-child';+ frame.onload = () => resolve(0);+ frame.src = {json.dumps(origin + "/interception-frame")};+ document.body.append(frame);+ }})""",+ awaitPromise=True,+ )+ tree = bidi.command("browsingContext.getTree", {"root": context})["contexts"][0]+ assert len(tree["children"]) == 1, tree+ assert tree["children"][0]["url"] == f"{origin}/interception-frame", tree+ child = tree["children"][0]["context"]+ bidi.evaluate(context, "window.detachedInterceptionMarker = true; 0")+ subscription = bidi.command(+ "session.subscribe",+ {+ "events": ["browsingContext.contextDestroyed", "network.beforeRequestSent", "network.responseStarted"],+ },+ )["subscription"]+ intercepts = []+ try:+ for phase, target in [("responseStarted", url), ("beforeRequestSent", final_url)]:+ intercepts.append(+ bidi.command(+ "network.addIntercept",+ {+ "phases": [phase],+ "urlPatterns": [{"type": "string", "pattern": target}],+ },+ )["intercept"]+ )+ bidi.evaluate(+ context,+ f"""document.getElementById('interception-child').contentWindow+ .fetch({json.dumps(url)}, {{keepalive: true}}).catch(() => {{}}); 0""",+ )+ assert server.interception_received.wait(30), "The child request did not reach the response gate"+ bidi.evaluate(context, "document.getElementById('interception-child').remove(); 0")+ destroyed = bidi.event("browsingContext.contextDestroyed")+ assert destroyed["context"] == child, destroyed+ bidi.evaluate(context, "internals.gc(); undefined")+ server.release_interception.set()+ # NB: Fetch callbacks for the removed document need not run. Observe native redirect progress instead.+ fetch_records(bidi, send_fetch(bidi, context, f"{origin}/network-interception/barrier"))+ followed_redirect = server.detached_final_received.is_set()+ # NB: Automatic crash recovery can restore the page URL while replacing its script state.+ marker = bidi.evaluate(context, "window.detachedInterceptionMarker")+ assert marker["result"].get("value") is True, marker+ for event in bidi.events:+ if event["method"] in ["network.beforeRequestSent", "network.responseStarted"]:+ assert not event["params"]["isBlocked"], event+ bidi.events[:] = [+ event+ for event in bidi.events+ if event["method"] not in ["network.beforeRequestSent", "network.responseStarted"]+ ]+ if followed_redirect:+ print("Detached keepalive transport followed the redirect after context destruction.")+ else:+ print("Detached transport did not follow the redirect; stale-navigable counterproof was not reached.")++ # NB: The remaining live parent still intercepts its own request; detachment must not disable interception.+ pending = send_fetch(bidi, context, final_url)+ event = intercepted_event(bidi, "network.beforeRequestSent", final_url)+ bidi.command("network.continueRequest", {"request": event["request"]["request"]})+ fetch_records(bidi, pending)+ assert bidi.evaluate(context, "document.readyState")["result"]["value"] == "complete"+ finally:+ server.release_interception.set()+ if sys.exc_info()[0] is None:+ for intercept in intercepts:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_authentication_gates(bidi, context, server, kinds, credentials=None):+ subscription = bidi.command("session.subscribe", {"events": ["network.authRequired"]})["subscription"]+ try:+ for kind in kinds:+ host = "localhost" if kind == "cors" else "127.0.0.1"+ url = f"http://{host}:{server.server_port}/network-interception/auth/gate-{kind}"+ intercept = bidi.command(+ "network.addIntercept",+ {+ "phases": ["authRequired"],+ "urlPatterns": [{"type": "string", "pattern": url}],+ },+ )["intercept"]+ with server.interception_lock:+ server.interception_requests.clear()+ fetch_options = {"credentials": "omit" if kind == "omit" else "include"}+ if kind != "default":+ fetch_options.update({"method": "POST", "body": "replayable-body"})+ options = json.dumps(fetch_options)+ if kind == "stream":+ options = "{method: 'POST', credentials: 'include', duplex: 'half', body: new ReadableStream({start(controller) {controller.enqueue(new Uint8Array([97])); controller.close();}})}"+ pending = bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "awaitPromise": True,+ "expression": f"fetch({json.dumps(url)}, {options}).then(async response => JSON.stringify({{status: response.status, body: await response.text()}}), error => JSON.stringify({{error: error.name}}))",+ },+ )+ if kind in ["cancel", "default"]:+ event = intercepted_event(bidi, "network.authRequired", url)+ params = {"request": event["request"]["request"], "action": kind}+ if credentials is not None:+ params["credentials"] = credentials+ bidi.command("network.continueWithAuth", params)+ else:+ # Observe an invalid block immediately, rather than waiting for the blocked fetch to time out.+ while pending not in bidi.responses:+ assert not any(+ event["method"] == "network.authRequired" and event["params"]["request"]["url"] == url+ for event in bidi.events+ ), bidi.events+ bidi.read_message()+ result = fetch_records(bidi, pending)+ if kind == "stream":+ assert result == {"error": "TypeError"}, result+ elif kind == "default":+ # The browser's existing interactive credential prompt is not implemented.+ assert result == {"error": "AbortError"}, result+ else:+ assert result == {"status": 401, "body": "authentication required"}, result+ bidi.evaluate(context, "0")+ assert not any(+ event["method"] == "network.authRequired" and event["params"]["request"]["url"] == url+ for event in bidi.events+ ), bidi.events+ with server.interception_lock:+ records = list(server.interception_requests)+ assert len(records) == 1, records+ assert not any(key.lower() == "authorization" for key, _ in records[0]["headers"]), records+ if kind != "stream":+ assert records[0]["body"] == ("" if kind == "default" else "replayable-body"), records+ bidi.command("network.removeIntercept", {"intercept": intercept})+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_continue_response_auth(bidi, context, server, credentials):+ kind = "credentials" if credentials else "default"+ url = f"http://127.0.0.1:{server.server_port}/network-interception/auth/continue-response-{kind}"+ subscription = bidi.command("session.subscribe", {"events": ["network.authRequired"]})["subscription"]+ intercept = bidi.command(+ "network.addIntercept",+ {+ "phases": ["authRequired"],+ "urlPatterns": [{"type": "string", "pattern": url}],+ },+ )["intercept"]+ try:+ with server.interception_lock:+ server.interception_requests.clear()+ options = {"method": "POST", "body": "continue-response-body"} if credentials else {}+ pending = bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "awaitPromise": True,+ "expression": f"fetch({json.dumps(url)}, {json.dumps(options)}).then(async response => JSON.stringify({{status: response.status, body: await response.text()}}), error => JSON.stringify({{error: error.name}}))",+ },+ )+ event = intercepted_event(bidi, "network.authRequired", url)+ params = {"request": event["request"]["request"]}+ if credentials:+ params["credentials"] = {"type": "password", "username": "user", "password": "pass"}+ bidi.command("network.continueResponse", params)+ while pending not in bidi.responses:+ assert not any(+ event["method"] == "network.authRequired" and event["params"]["request"]["url"] == url+ for event in bidi.events+ ), bidi.events+ bidi.read_message()+ result = fetch_records(bidi, pending)+ with server.interception_lock:+ records = list(server.interception_requests)+ if credentials:+ assert result["status"] == 200, result+ assert json.loads(result["body"]) == json.loads(json.dumps(records)), (result, records)+ assert len(records) == 2, records+ for record in records:+ assert record["method"] == "POST" and record["body"] == "continue-response-body", record+ lengths = [value for key, value in record["headers"] if key.lower() == "content-length"]+ assert lengths == [str(len("continue-response-body"))], record+ assert not any(key.lower() == "authorization" for key, _ in records[0]["headers"]), records+ authorization = [value for key, value in records[1]["headers"] if key.lower() == "authorization"]+ assert authorization == ["Basic dXNlcjpwYXNz"], records+ else:+ # Default authentication reaches the browser's existing unimplemented prompt fallback.+ assert result == {"error": "AbortError"}, result+ assert len(records) == 1 and records[0]["method"] == "GET", records+ bidi.evaluate(context, "0")+ assert not any(+ event["method"] == "network.authRequired" and event["params"]["request"]["url"] == url+ for event in bidi.events+ ), bidi.events+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_provide_response_auth(bidi, context, server, status):+ kind = "omitted" if status is None else str(status)+ url = f"http://127.0.0.1:{server.server_port}/network-interception/auth/provide-response-{kind}"+ subscription = bidi.command("session.subscribe", {"events": ["network.authRequired"]})["subscription"]+ intercept = bidi.command(+ "network.addIntercept",+ {"phases": ["authRequired"], "urlPatterns": [{"type": "string", "pattern": url}]},+ )["intercept"]+ try:+ with server.interception_lock:+ server.interception_requests.clear()+ pending = bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "awaitPromise": True,+ "expression": f"fetch({json.dumps(url)}).then(async response => JSON.stringify({{status: response.status, body: await response.text()}}), error => JSON.stringify({{error: error.name}}))",+ },+ )+ event = intercepted_event(bidi, "network.authRequired", url)+ params = {"request": event["request"]["request"], "body": {"type": "string", "value": "provided-auth-response"}}+ if status is not None:+ params["statusCode"] = status+ bidi.command("network.provideResponse", params)+ while pending not in bidi.responses:+ assert not any(+ event["method"] == "network.authRequired" and event["params"]["request"]["url"] == url+ for event in bidi.events+ ), bidi.events+ bidi.read_message()+ assert fetch_records(bidi, pending) == {+ "status": 401 if status is None else status,+ "body": "provided-auth-response",+ }+ with server.interception_lock:+ records = list(server.interception_requests)+ assert len(records) == 1 and records[0]["method"] == "GET", records+ assert not any(key.lower() == "authorization" for key, _ in records[0]["headers"]), records+ bidi.evaluate(context, "0")+ assert not any(+ event["method"] == "network.authRequired" and event["params"]["request"]["url"] == url+ for event in bidi.events+ ), bidi.events+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_failed_response_transport(bidi, context, server):+ url = f"http://127.0.0.1:{server.server_port}/network-interception/fail-body"+ server.interception_transport_closed.clear()+ subscription = bidi.command("session.subscribe", {"events": ["network.responseStarted"]})["subscription"]+ intercept = bidi.command(+ "network.addIntercept",+ {+ "phases": ["responseStarted"],+ "urlPatterns": [{"type": "string", "pattern": url}],+ },+ )["intercept"]+ try:+ pending = bidi.send(+ "script.evaluate",+ {+ "target": {"context": context},+ "awaitPromise": True,+ "expression": f"fetch({json.dumps(url)}).then(() => 'fulfilled', error => error.name)",+ },+ )+ event = intercepted_event(bidi, "network.responseStarted", url)+ bidi.command("network.failRequest", {"request": event["request"]["request"]})+ result = bidi.response(pending)+ assert result["type"] == "success" and result["result"]["result"]["value"] == "TypeError", result+ assert server.interception_transport_closed.wait(30), "Failed interception left the original transport open"+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_scoped_headers(bidi, context, server):+ other = bidi.command("browsingContext.create", {"type": "tab"})["context"]++ def set_headers(target, value):+ bidi.command(+ "network.setExtraHeaders",+ {+ "contexts": [target],+ "headers": [{"name": "X-Scoped-Secret", "value": {"type": "string", "value": value}}],+ },+ )++ def check_headers(target, host, expected):+ with server.interception_lock:+ server.interception_requests.clear()+ records = fetch_records(+ bidi, send_fetch(bidi, target, f"http://{host}:{server.server_port}/network-interception/scoped")+ )+ values = [value for key, value in records[-1]["headers"] if key.lower() == "x-scoped-secret"]+ assert values == [expected], records++ try:+ set_headers(context, "first-tab")+ # Set the second tab's scope before its new process is provisioned.+ set_headers(other, "second-tab")+ bidi.command(+ "browsingContext.navigate",+ {+ "context": other,+ "url": f"http://localhost:{server.server_port}/input-child",+ "wait": "complete",+ },+ )+ bidi.evaluate(+ other,+ "new Promise(resolve => { const frame = document.createElement('iframe'); "+ f"frame.src = 'http://127.0.0.1:{server.server_port}/input-child'; "+ "frame.onload = resolve; document.body.append(frame); })",+ awaitPromise=True,+ )+ tree = bidi.command("browsingContext.getTree", {"root": other})["contexts"][0]+ assert len(tree["children"]) == 1, tree+ child = tree["children"][0]["context"]+ check_headers(context, "127.0.0.1", "first-tab")+ check_headers(other, "localhost", "second-tab")+ check_headers(child, "127.0.0.1", "second-tab")+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("network.setExtraHeaders", {"contexts": [context], "headers": []})+ bidi.command("browsingContext.close", {"context": other})+++def check_network_intercepted_navigation(bidi, context, server):+ origin = f"http://127.0.0.1:{server.server_port}"+ url = f"http://localhost:{server.server_port}/intercepted-navigation"+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent", "browsingContext.load"]})[+ "subscription"+ ]+ intercept = bidi.command(+ "network.addIntercept",+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": url}]},+ )["intercept"]+ try:+ navigation_command = bidi.send("browsingContext.navigate", {"context": context, "url": url, "wait": "none"})+ event = intercepted_event(bidi, "network.beforeRequestSent", url)+ assert event["navigation"] is not None, event+ bidi.command(+ "network.provideResponse",+ {+ "request": event["request"]["request"],+ "statusCode": 200,+ "headers": [{"name": "Content-Type", "value": {"type": "string", "value": "text/html"}}],+ "body": {"type": "string", "value": "<!doctype html><title>Intercepted navigation</title><p>Provided"},+ },+ )+ navigation = bidi.response(navigation_command)+ assert navigation["type"] == "success", navigation+ assert navigation["result"]["navigation"] == event["navigation"], navigation+ loaded = bidi.event("browsingContext.load")+ assert loaded["context"] == context and loaded["url"] == url, loaded+ assert loaded["navigation"] == event["navigation"], loaded+ assert bidi.evaluate(context, "document.title")["result"]["value"] == "Intercepted navigation"+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+ bidi.command(+ "browsingContext.navigate",+ {"context": context, "url": f"{origin}/interception-page", "wait": "complete"},+ )+++def check_network_interception(bidi, context, server, case="all"):+ bidi.command(+ "browsingContext.navigate",+ {+ "context": context,+ "url": f"http://127.0.0.1:{server.server_port}/interception-page",+ "wait": "complete",+ },+ )+ # NB: This must run before any network subscription or interception creates state for the held request.+ if case in ["all", "late-enable"]:+ check_network_late_interception(bidi, context, server)+ if case in ["all", "late-abort"]:+ check_network_late_interception(bidi, context, server, abort=True)+ if case in ["all", "redirect", "auth", "overrides"]:+ check_network_override_retries(+ bidi, context, server, ["redirect", "auth", "overrides"] if case == "all" else [case]+ )+ echo_cases = [+ "echo-307",+ "echo-303",+ "echo-auth",+ "explicit-307",+ "explicit-303",+ "explicit-auth",+ "echo-body",+ "echo-range",+ "explicit-range",+ "explicit-unsubscribe",+ ]+ if case in ["all", "echo-headers", *echo_cases]:+ check_network_echoed_headers(bidi, context, server, echo_cases if case in ["all", "echo-headers"] else [case])+ if case in ["all", "detached"]:+ check_network_detached_interception(bidi, context, server)+ if case in ["all", "navigation"]:+ check_network_intercepted_navigation(bidi, context, server)+ if case in ["all", "scoped-headers"]:+ check_network_scoped_headers(bidi, context, server)+ if case in ["all", "fail-transport"]:+ check_network_failed_response_transport(bidi, context, server)+ for action in ["cancel", "default"]:+ if case in ["all", "auth-response-matrix", "auth-action-extras", f"auth-{action}-extra"]:+ for credentials in [{"type": "password", "username": "user", "password": "pass"}, {}]:+ check_network_authentication_gates(bidi, context, server, [action], credentials)+ for status, kind in [(None, "omitted"), (401, "401"), (200, "200")]:+ if case in ["all", "auth-response-matrix", "auth-provide-response", f"auth-provide-response-{kind}"]:+ check_network_provide_response_auth(bidi, context, server, status)+ if case in ["all", "auth-response-matrix", "auth-continue-response", "auth-continue-response-default"]:+ check_network_continue_response_auth(bidi, context, server, credentials=False)+ if case in ["all", "auth-response-matrix", "auth-continue-response", "auth-continue-response-credentials"]:+ check_network_continue_response_auth(bidi, context, server, credentials=True)+ if case in ["all", "auth-gates", "auth-omit", "auth-cors", "auth-stream", "auth-cancel", "auth-default"]:+ kinds = (+ ["omit", "cors", "stream", "cancel", "default"]+ if case in ["all", "auth-gates"]+ else [case.removeprefix("auth-")]+ )+ check_network_authentication_gates(bidi, context, server, kinds)++def check_network_download_events(bidi, context, server, downloads):if sys.platform == "win32":print("Skipping download event tests: Windows does not support the temporary download directory override.")@@ -911,6 +1740,7 @@ def cleanup_resources(server, webdriver, connection, bidi, session_id, *, primarattempt(lambda: webdriver.wait(timeout=5))attempt(server.release_response.set)+ attempt(server.release_interception.set)if session_id and connection:attempt(lambda: helpers.request(connection, "DELETE", f"/session/{session_id}"))if bidi:@@ -924,7 +1754,14 @@ def cleanup_resources(server, webdriver, connection, bidi, session_id, *, primarraise errors[0]-def run_test(webdriver_binary, *, input_cross_context_only=False, network_download_only=False):+def run_test(+ webdriver_binary,+ *,+ input_cross_context_only=False,+ network_download_only=False,+ network_interception_only=False,+ network_interception_case="all",+):with tempfile.TemporaryDirectory(prefix="ladybird-webdriver-bidi-") as profile:downloads = os.path.join(profile, "downloads")os.mkdir(downloads)@@ -973,6 +1810,12 @@ def run_test(webdriver_binary, *, input_cross_context_only=False, network_downlorejected.close()bidi = BiDiConnection(websocket_url)context = bidi.command("browsingContext.getTree", {})["contexts"][0]["context"]+ if network_interception_only:+ check_network_interception(bidi, context, server, network_interception_case)+ status, payload, _ = helpers.request(connection, "DELETE", f"/session/{session_id}")+ assert status == 200, payload+ session_id = None+ returnif network_download_only:check_network_download_events(bidi, context, server, downloads)status, payload, _ = helpers.request(connection, "DELETE", f"/session/{session_id}")@@ -986,6 +1829,7 @@ def run_test(webdriver_binary, *, input_cross_context_only=False, network_downloassert status == 200, payloadsession_id = Nonereturn+ check_network_interception(bidi, context, server, network_interception_case)check_network_download_events(bidi, context, server, downloads)check_screenshot_handles(bidi, context)check_input_handles(bidi, context)@@ -1177,9 +2021,56 @@ if __name__ == "__main__":parser.add_argument("webdriver_binary")parser.add_argument("--input-cross-context-only", action="store_true")parser.add_argument("--network-download-only", action="store_true")+ parser.add_argument("--network-interception-only", action="store_true")+ parser.add_argument(+ "--network-interception-case",+ choices=[+ "all",+ "late-enable",+ "late-abort",+ "redirect",+ "auth",+ "overrides",+ "detached",+ "navigation",+ "scoped-headers",+ "fail-transport",+ "auth-gates",+ "auth-omit",+ "auth-cors",+ "auth-stream",+ "auth-cancel",+ "auth-default",+ "echo-headers",+ "echo-307",+ "echo-303",+ "echo-auth",+ "explicit-307",+ "explicit-303",+ "explicit-auth",+ "echo-body",+ "echo-range",+ "explicit-range",+ "explicit-unsubscribe",+ "auth-response-matrix",+ "auth-action-extras",+ "auth-cancel-extra",+ "auth-default-extra",+ "auth-provide-response",+ "auth-provide-response-omitted",+ "auth-provide-response-401",+ "auth-provide-response-200",+ "auth-continue-response",+ "auth-continue-response-default",+ "auth-continue-response-credentials",+ ],+ default="all",+ )args = parser.parse_args()run_test(args.webdriver_binary,input_cross_context_only=args.input_cross_context_only,network_download_only=args.network_download_only,+ network_interception_only=args.network_interception_only,+ network_interception_case=args.network_interception_case,)