Truly independent web browser
LibWeb: Stop the transport of a response the fetch discards
Luke Wildea9ea8bf43bb3
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cppindex 31346dc20bf..7b651b970ed 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp@@ -226,6 +226,19 @@ void FetchedDataReceiver::enqueue_into_stream(JS::Realm& realm, ReadonlyBytes by}}+void FetchedDataReceiver::abandon_cache_entry()+{+ if (!m_http_cache || !m_fetch_params || !m_response)+ return;++ auto request = m_fetch_params->request();+ m_http_cache->abandon_entry(request->current_url(), request->method(), request->header_list(), m_response->header_list());++ m_http_cache.clear();+ m_cache_buffer.clear();+ m_cache_body.clear();+}+void FetchedDataReceiver::close_stream(JS::Realm& realm){if (m_http_cache && m_fetch_params) {diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.hindex eb220151bc2..9a7a078b8d0 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h+++ b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h@@ -38,6 +38,9 @@ public:void handle_network_data(JS::Realm&, Requests::ResponseData, NetworkState);void set_cached_response_body(Core::ImmutableBytes);+ // Drops the response's pending memory-cache entry, for a body that will not finish arriving.+ void abandon_cache_entry();+private:FetchedDataReceiver(GC::Ptr<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, RefPtr<HTTP::MemoryCache>);diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 6833347c455..7ce64c60d0c 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -185,6 +185,13 @@ static void store_response_in_cache(HTTP::MemoryCache& http_cache, Infrastructurhttp_cache.create_entry(request.current_url(), request.method(), request.header_list(), request.request_time(), response.status(), response.status_message(), response.header_list(), response.javascript_bytecode_cache(), response.javascript_bytecode_cache_vary_key());}+// Ends the delivery of a response's body that the fetch will not read.+static void stop_discarded_response_body(Infrastructure::FetchController& controller, Infrastructure::Response const& response)+{+ response.release_request_transfer_lease();+ controller.stop_body_transport();+}+// https://fetch.spec.whatwg.org/#concept-fetchGC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure::Request& request, Infrastructure::FetchAlgorithms const& algorithms, UseParallelQueue use_parallel_queue, CreateResponseBodyTransferLease create_response_body_transfer_lease){@@ -731,6 +738,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// - should internalResponse to request be blocked due to nosniff|| Infrastructure::should_response_to_request_be_blocked_due_to_nosniff(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked)) {// then set response and internalResponse to a network error.+ stop_discarded_response_body(*fetch_params.controller(), *internal_response);response = internal_response = Infrastructure::Response::network_error("Response was blocked"_string);}@@ -744,6 +752,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam&& internal_response->status() == 206&& internal_response->range_requested()&& !request->header_list()->contains("Range"sv)) {+ stop_discarded_response_body(*fetch_params.controller(), *internal_response);response = internal_response = Infrastructure::Response::network_error("Response has status 206 and 'range-requested' flag set, but request has no 'Range' header"_string);}@@ -1510,6 +1519,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// a service worker for that matter, it is applied here.if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS&& !cors_check(request, *response)) {+ stop_discarded_response_body(*fetch_params.controller(), *response);returned_pending_response->resolve(Infrastructure::Response::network_error("Request with 'cors' response tainting failed CORS check"_string));return;}@@ -1530,6 +1540,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParamauto client_embedder_policy = request->client() ? request->client()->policy_container()->embedder_policy : HTML::EmbedderPolicy {};if ((request->response_tainting() == Infrastructure::Request::ResponseTainting::Opaque || response->type() == Infrastructure::Response::Type::Opaque)&& cross_origin_resource_policy_check(request->origin().get<URL::Origin>(), client_embedder_policy, *internal_response) == Infrastructure::RequestOrResponseBlocking::Blocked) {+ stop_discarded_response_body(*fetch_params.controller(), *internal_response);returned_pending_response->resolve(Infrastructure::Response::network_error("Response was blocked by cross-origin resource policy check"_string));return;}@@ -1618,9 +1629,7 @@ GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm& realm, Infrastructure::F// AD-HOC: Navigation responses have a RequestServer transfer lease so they can move through the UI process.// This response will be discarded in favor of either a network error or the redirect response, so// release its lease and stop the request if it is still active.- internal_response->release_request_transfer_lease();- if (auto const& request_server_request = internal_response->request_server_request(); request_server_request.has_value() && request_server_request->request)- request_server_request->request->stop();+ stop_discarded_response_body(*fetch_params.controller(), *internal_response);// 5. If locationURL is failure, then return a network error.if (location_url_or_error.is_error())@@ -2155,6 +2164,9 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru&& include_credentials == HTTP::Cookie::IncludeCredentials::Yes&& request->traversable_for_user_prompts().has<GC::Ptr<HTML::Navigable>>()&& 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)@@ -2503,6 +2515,11 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(fetched_data_receiver->set_network_request(network_request);if (network_request && fetch_params.has_response_body_transfer_lease())network_request->set_body_delivery_paused(true);+ if (network_request) {+ network_request->on_teardown = [fetched_data_receiver = GC::Root { fetched_data_receiver }] {+ fetched_data_receiver->abandon_cache_entry();+ };+ }fetch_params.controller()->set_pending_request(network_request);// To transmit request’s body body, run these steps:@@ -2618,9 +2635,12 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::auto preflight_response = http_network_or_cache_fetch(realm, fetch_params);- preflight_response->when_loaded([&request, returned_pending_response](GC::Ref<Infrastructure::Response> response) {+ preflight_response->when_loaded([&request, returned_pending_response, preflight_controller = fetch_params->controller()](GC::Ref<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");+ // NB: Only the preflight response's headers are read.+ preflight_controller->stop_body_transport();+// 7. If a CORS check for request and response returns success and response’s status is an ok status, then:// NOTE: The CORS check is done on request rather than preflight to ensure the correct credentials mode is used.if (cors_check(request, response) && Infrastructure::is_ok_status(response->status())) {diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex cfb19997d66..68149e4f7ba 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -181,6 +181,11 @@ void FetchController::stop_request(){end_rendering_pending_operation(this);VERIFY(m_state != State::Ongoing);+ stop_body_transport();+}++void FetchController::stop_body_transport()+{if (m_pending_request) {m_pending_request->stop();m_pending_request = nullptr;diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.hindex cdae1d5617e..ba964fd88db 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h@@ -77,6 +77,8 @@ public:void stop_fetch();void stop_request();+ // Stops the delivery of the current response's body without ending the fetch.+ void stop_body_transport();void set_stop_steps(GC::Ref<GC::Function<void()>> stop_steps) { m_stop_steps = stop_steps; }u64 next_fetch_task_id() { return m_next_fetch_task_id++; }diff --git a/Tests/LibWeb/Text/expected/Cache/http-memory-cache-discarded-response.txt b/Tests/LibWeb/Text/expected/Cache/http-memory-cache-discarded-response.txtnew file mode 100644index 00000000000..fc7a70d0cbc--- /dev/null+++ b/Tests/LibWeb/Text/expected/Cache/http-memory-cache-discarded-response.txt@@ -0,0 +1,3 @@+script load was blocked+stored response arrived whole: true+next fetch served from the cache: truediff --git a/Tests/LibWeb/Text/input/Cache/http-memory-cache-discarded-response.html b/Tests/LibWeb/Text/input/Cache/http-memory-cache-discarded-response.htmlnew file mode 100644index 00000000000..2b1832ea487--- /dev/null+++ b/Tests/LibWeb/Text/input/Cache/http-memory-cache-discarded-response.html@@ -0,0 +1,51 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A response the fetch discards leaves no memory-cache entry behind, pending or complete. A later response for the+ // same request is the one the cache stores.+ //+ // The Accept marker rides each fetch (CORS-safelisted, and the response has no Vary). The server records the last+ // marker it saw, which tells a hit from a miss.+ asyncTest(async done => {+ const server = httpTestServer();+ const delay = ms => new Promise(resolve => setTimeout(resolve, ms));+ const lastSeenMarker = async url => {+ const response = await fetch(server.recordedRequestHeadersURL(url));+ return (await response.json())["Accept"][0];+ };++ const token = `discarded-${crypto.randomUUID()}`;+ const url = await server.createEcho("GET", `/cache-discarded-${crypto.randomUUID()}`, {+ status: 200,+ headers: {+ "Access-Control-Allow-Origin": "*",+ "Cache-Control": "max-age=2",+ "Content-Type": "application/octet-stream",+ "X-Content-Type-Options": "nosniff",+ },+ body: "abcdefghij" + "K".repeat(54),+ });+ // The body is held after its first chunk while the script load discards the response.+ const heldUrl = `${url}?chunks=10,54&chunk_unblock_tokens=${token}`;++ // A nosniff response that is not JavaScript is blocked for a script.+ const script = document.createElement("script");+ const blocked = new Promise(resolve => script.addEventListener("error", resolve, { once: true }));+ script.src = heldUrl;+ document.body.append(script);+ await blocked;+ println("script load was blocked");+ await fetch(new URL(`/unblock/${token}`, url));++ // Wait past the discarded response's freshness: an entry it left behind is expired by then.+ await delay(3000);++ const stored = await fetch(heldUrl, { headers: { Accept: "stored" } });+ println(`stored response arrived whole: ${(await stored.arrayBuffer()).byteLength === 64}`);++ await fetch(heldUrl, { headers: { Accept: "check" } });+ println(`next fetch served from the cache: ${(await lastSeenMarker(url)) === "stored"}`);++ done();+ });+</script>