Truly independent web browser
LibWeb: Clone fetch request bodies from their source
Luke Wildeca7bc5c7d0f7
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 664ff7624bf..4942e41c733 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -1385,7 +1385,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// 3. If request’s service-workers mode is "all", then:if (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {// 1. Let requestForServiceWorker be a clone of request.- auto request_for_service_worker = request->clone(realm);+ auto request_for_service_worker = request->clone(realm, Infrastructure::Request::BodyCloning::FromSource);// 2. If requestForServiceWorker’s body is non-null, then:if (!request_for_service_worker->body().has<Empty>()) {@@ -1796,7 +1796,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// NOTE: Implementations are encouraged to avoid teeing request’s body’s stream when request’s body’s// 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(realm);+ http_request = request->clone(realm, Infrastructure::Request::BodyCloning::FromSource);// 2. Set httpFetchParams to a copy of fetchParams.auto new_http_fetch_params = Infrastructure::FetchParams::copy(fetch_params);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cppindex 589177a5bfa..94782996a45 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp@@ -83,6 +83,36 @@ GC::Ref<Body> Body::create(GC::Ref<Streams::ReadableStream> stream, FetchBody fereturn GC::Heap::the().allocate<Body>(stream, move(fetch_body));}+GC::Ref<Body> Body::create_from_source(JS::Realm& realm, FetchBody fetch_body)+{+ VERIFY(fetch_body.source().has_value());+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };++ auto stream = Streams::ReadableStream::create(realm);+ auto pull_algorithm = GC::create_function(GC::Heap::the(), [&realm, stream, source = *fetch_body.source(), offset = size_t { 0 }]() mutable {+ // A BYOB pull may consume only the current view's length.+ auto remaining = source.size() - offset;+ auto pull_size = remaining;+ if (auto byte_length = stream->current_byob_request_view_byte_length(); byte_length.has_value())+ pull_size = min(remaining, *byte_length);++ if (pull_size > 0) {+ if (auto result = stream->pull_from_bytes(source.bytes().slice(offset, pull_size)); result.is_error()) {+ if (stream->is_readable())+ stream->error(WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error()).release_value());+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());+ }+ offset += pull_size;+ }+ if (offset == source.size() && stream->is_readable())+ stream->close();+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());+ });+ stream->set_up_with_byte_reading_support(realm, pull_algorithm);++ return create(stream, move(fetch_body));+}+Body::Body(GC::Ref<Streams::ReadableStream> stream, FetchBody fetch_body): m_stream(stream), m_fetch_body(move(fetch_body))diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.hindex e9215d0cd07..10ac764c1e0 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h@@ -88,6 +88,8 @@ public:using ProcessEndOfBodyCallback = GC::Ref<GC::Function<void()>>;[[nodiscard]] static GC::Ref<Body> create(GC::Ref<Streams::ReadableStream>, FetchBody = {});+ // A body whose stream reads the source as it is pulled.+ [[nodiscard]] static GC::Ref<Body> create_from_source(JS::Realm&, FetchBody);[[nodiscard]] GC::Ref<Streams::ReadableStream> stream() const { return *m_stream; }void set_stream(GC::Ref<Streams::ReadableStream> value) { m_stream = value; }diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cppindex 1422d1e7b09..434357292b2 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp@@ -212,7 +212,7 @@ ByteString Request::byte_serialize_origin() const}// https://fetch.spec.whatwg.org/#concept-request-clone-GC::Ref<Request> Request::clone(JS::Realm& realm) const+GC::Ref<Request> Request::clone(JS::Realm& realm, BodyCloning body_cloning) const{// To clone a request request, run these steps:// 1. Let newRequest be a copy of request, except for its body.@@ -262,8 +262,18 @@ GC::Ref<Request> Request::clone(JS::Realm& realm) constnew_request->m_navigation_timing_allow_values_list = m_navigation_timing_allow_values_list;// 2. If request’s body is non-null, set newRequest’s body to the result of cloning request’s body.- if (auto const* body = m_body.get_pointer<GC::Ref<Body>>())- new_request->set_body((*body)->clone(realm));+ if (auto const* body = m_body.get_pointer<GC::Ref<Body>>()) {+ switch (body_cloning) {+ case BodyCloning::Tee:+ new_request->set_body((*body)->clone(realm));+ break;+ case BodyCloning::FromSource:+ // AD-HOC: The fetch algorithms never read both this clone's body and the request's (see the note on cloning+ // in HTTP-network-or-cache fetch), so the clone reads the source, and a body without one is shared.+ new_request->set_body((*body)->source().has_value() ? Body::create_from_source(realm, (*body)->fetch_body()) : *body);+ break;+ }+ }// 3. Return newRequest.return new_request;diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.hindex 28e2a73c766..96e9d133ca1 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h@@ -320,7 +320,11 @@ public:[[nodiscard]] String serialize_origin() const;[[nodiscard]] ByteString byte_serialize_origin() const;- [[nodiscard]] GC::Ref<Request> clone(JS::Realm&) const;+ enum class BodyCloning : u8 {+ Tee,+ FromSource,+ };+ [[nodiscard]] GC::Ref<Request> clone(JS::Realm&, BodyCloning) const;void add_range_header(u64 first, Optional<u64> const& last);void add_origin_header();diff --git a/Libraries/LibWeb/Fetch/Request.cpp b/Libraries/LibWeb/Fetch/Request.cppindex 9274ff93d07..64d56a974e7 100644--- a/Libraries/LibWeb/Fetch/Request.cpp+++ b/Libraries/LibWeb/Fetch/Request.cpp@@ -789,7 +789,7 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::clone(JS::Realm& realm) constreturn WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Request is unusable"_utf16 };// 2. Let clonedRequest be the result of cloning this’s request.- auto cloned_request = m_request->clone(realm);+ auto cloned_request = m_request->clone(realm, Infrastructure::Request::BodyCloning::Tee);// 3. Assert: this’s signal is non-null.VERIFY(m_signal);diff --git a/Libraries/LibWeb/ServiceWorker/Cache.cpp b/Libraries/LibWeb/ServiceWorker/Cache.cppindex 0510cd1d8c0..2862b858008 100644--- a/Libraries/LibWeb/ServiceWorker/Cache.cpp+++ b/Libraries/LibWeb/ServiceWorker/Cache.cpp@@ -825,7 +825,7 @@ GC::Ref<RequestResponseList> Cache::query_cache(JS::Realm& realm, GC::Ref<Fetch:}// 1. Let requestCopy be a copy of cachedRequest.- auto request_copy = cached_request->clone(realm);+ auto request_copy = cached_request->clone(realm, Fetch::Infrastructure::Request::BodyCloning::Tee);// 2. Let responseCopy be a copy of cachedResponse.auto response_copy = cached_response->clone(realm);@@ -849,7 +849,7 @@ WebIDL::ExceptionOr<bool> Cache::batch_cache_operations(JS::Realm& realm, GC::Reauto backup_cache = GC::Heap::the().allocate<RequestResponseList>();for (auto request_response : cache->elements()) {- auto backup_request = request_response->request->clone(realm);+ auto backup_request = request_response->request->clone(realm, Fetch::Infrastructure::Request::BodyCloning::Tee);auto backup_response = request_response->response->clone(realm);auto backup_request_response = GC::Heap::the().allocate<RequestResponse>(backup_request, backup_response);diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex e9aa7e10d23..1c734680b6a 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -44,10 +44,11 @@ ALLOWED_REALM_MENTIONS = {"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),"Fetch": (24,- 65,+ 67,"Fetch bodies, headers, requests, responses, and controllers still materialize JS values/streams; ""the body receiver's delivery and close tasks carry the realm its stream is enqueued and closed in; "- "BodyStreamPullSource materializes stream pulls and errors on the consumer side, in its stream's realm",+ "BodyStreamPullSource materializes stream pulls and errors on the consumer side, in its stream's realm; "+ "a request clone's body materializes the stream that reads its source",),"FileAPI": (4, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),"HTML": (diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-abort-cancels-the-request-body-stream.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-abort-cancels-the-request-body-stream.txtnew file mode 100644index 00000000000..79058bb83b7--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-abort-cancels-the-request-body-stream.txt@@ -0,0 +1,2 @@+cancel: AbortError+fetch: AbortErrordiff --git a/Tests/LibWeb/Text/input/Fetch/fetch-abort-cancels-the-request-body-stream.html b/Tests/LibWeb/Text/input/Fetch/fetch-abort-cancels-the-request-body-stream.htmlnew file mode 100644index 00000000000..2906798f62b--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/fetch-abort-cancels-the-request-body-stream.html@@ -0,0 +1,32 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ const url = await httpTestServer().createEcho("POST", "/fetch-abort-cancels-the-request-body-stream", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*" },+ body: "",+ });++ const controller = new AbortController();+ let pulls = 0;+ const stream = new ReadableStream({+ pull(streamController) {+ streamController.enqueue(new Uint8Array([1]));+ // The second pull comes once fetch reads the stream.+ if (++pulls === 2)+ queueMicrotask(() => controller.abort());+ },+ cancel(reason) {+ println(`cancel: ${reason.name}`);+ },+ });++ fetch(url, { method: "POST", body: stream, duplex: "half", signal: controller.signal })+ .then(+ () => println("fetch: resolved"),+ error => println(`fetch: ${error.name}`)+ )+ .finally(done);+ });+</script>