Skip to content

Truly independent web browser

LibWeb: Error the response body when a `fetch()` call is aborted

Tim Ledbetter9aeee263ee3d
diff --git a/Libraries/LibWeb/Fetch/FetchMethod.cpp b/Libraries/LibWeb/Fetch/FetchMethod.cpp
index 243e7d5dd28..4f026bc4dc3 100644
--- a/Libraries/LibWeb/Fetch/FetchMethod.cpp
+++ b/Libraries/LibWeb/Fetch/FetchMethod.cpp
@@ -30,6 +30,21 @@
namespace Web::Fetch {
+struct ResponseObjectHolder final : public JS::Cell {
+ GC_CELL(ResponseObjectHolder, JS::Cell);
+ GC_DECLARE_ALLOCATOR(ResponseObjectHolder);
+
+ virtual void visit_edges(JS::Cell::Visitor& visitor) override
+ {
+ Base::visit_edges(visitor);
+ visitor.visit(response_object);
+ }
+
+ GC::Ptr<Response> response_object;
+};
+
+GC_DEFINE_ALLOCATOR(ResponseObjectHolder);
+
// https://fetch.spec.whatwg.org/#deserialize-a-serialized-abort-reason
static JS::Value deserialize_serialized_abort_reason(JS::Realm& realm, Infrastructure::FetchController const& controller)
{
@@ -88,7 +103,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
(void)global_object;
// 7. Let responseObject be null.
- GC::Ptr<Response> response_object;
+ auto response_object_holder = GC::Heap::the().allocate<ResponseObjectHolder>();
// 8. Let relevantRealm be this’s relevant Realm.
// NOTE: This assumes that the running execution context is for the fetch() function call.
@@ -107,7 +122,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
// 12. Set controller to the result of calling fetch given request and processResponse given response being these
// steps:
- auto process_response = [locally_aborted, promise_capability, request, response_object, controller_holder, &relevant_realm](GC::Ref<Infrastructure::Response> response) mutable {
+ auto process_response = [locally_aborted, promise_capability, request, response_object_holder, controller_holder, &relevant_realm](GC::Ref<Infrastructure::Response> response) {
// 1. If locallyAborted is true, then abort these steps.
if (locally_aborted->value())
return;
@@ -122,7 +137,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
auto deserialized_error = deserialize_serialized_abort_reason(relevant_realm, *controller_holder->controller());
// 2. Abort the fetch() call with p, request, responseObject, and deserializedError.
- abort_fetch(*promise_capability, request, response_object, deserialized_error);
+ abort_fetch(*promise_capability, request, response_object_holder->response_object, deserialized_error);
// 3. Abort these steps.
return;
@@ -137,13 +152,13 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
// 4. Set responseObject to the result of creating a Response object, given response, "immutable", and
// relevantRealm.
- response_object = Response::create(response, Headers::Guard::Immutable);
+ response_object_holder->response_object = Response::create(response, Headers::Guard::Immutable);
// 5. Resolve p with responseObject.
auto response_value = Bindings::wrap(
Bindings::host_defined_wrapper_world(relevant_realm),
relevant_realm,
- GC::Ref { *response_object });
+ GC::Ref { *response_object_holder->response_object });
WebIDL::resolve_promise(relevant_realm, promise_capability, response_value);
};
controller_holder->set_controller(Fetching::fetch(
@@ -160,7 +175,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
})));
// 11. Add the following abort steps to requestObject’s signal:
- (void)request_object->signal()->add_abort_algorithm([locally_aborted, request, controller_holder, promise_capability, request_object, response_object, &relevant_realm] {
+ (void)request_object->signal()->add_abort_algorithm([locally_aborted, request, controller_holder, promise_capability, request_object, response_object_holder, &relevant_realm] {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Request object signal's abort algorithm called");
// 1. Set locallyAborted to true.
@@ -176,7 +191,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
HTML::TemporaryExecutionContext execution_context { relevant_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
// 4. Abort the fetch() call with p, request, responseObject, and requestObject’s signal’s abort reason.
- abort_fetch(*promise_capability, request, response_object, request_object->signal()->reason());
+ abort_fetch(*promise_capability, request, response_object_holder->response_object, request_object->signal()->reason());
});
// 13. Return p.
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 730a28c798d..13bda26fd39 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -983,7 +983,9 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
auto identity_transform_algorithm = GC::create_function(GC::Heap::the(), [&realm, transform_stream](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {
- MUST(Streams::transform_stream_default_controller_enqueue(realm, *transform_stream->controller(), chunk));
+ if (auto result = Streams::transform_stream_default_controller_enqueue(realm, *transform_stream->controller(), chunk); result.is_error())
+ return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());
+
return WebIDL::create_resolved_promise(realm, JS::js_undefined());
});
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index e79c5d36206..42fdf0eb104 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -46,6 +46,7 @@ Text/input/wpt-import/video-rvfc/
; fetching a file only works from an HTTP server.
Text/input/wpt-import/fetch/api/basic/text-utf8.any.html
+Text/input/wpt-import/fetch/api/abort/general.any.html
Crash/HTML/media-element-load-with-pending-source-buffer-append.html
Text/input/HTML/HTMLMediaElement-failed-range-response-after-metadata.html
Text/input/HTML/HTMLMediaElement-preload-metadata-suspends-download.html
diff --git a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/abort/general.any.txt b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/abort/general.any.txt
new file mode 100644
index 00000000000..33ce26803f8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/abort/general.any.txt
@@ -0,0 +1,67 @@
+Harness status: OK
+
+Found 61 tests
+
+54 Pass
+7 Fail
+Pass Aborting rejects with AbortError
+Pass Aborting rejects with abort reason
+Pass Aborting rejects with abort reason when aborted after fetch() called
+Pass Aborting rejects with AbortError - no-cors
+Pass TypeError from request constructor takes priority - RequestInit's window is not null
+Pass TypeError from request constructor takes priority - Input URL is not valid
+Pass TypeError from request constructor takes priority - Input URL has credentials
+Pass TypeError from request constructor takes priority - RequestInit's mode is navigate
+Pass TypeError from request constructor takes priority - RequestInit's referrer is invalid
+Pass TypeError from request constructor takes priority - RequestInit's method is invalid
+Pass TypeError from request constructor takes priority - RequestInit's method is forbidden
+Pass TypeError from request constructor takes priority - RequestInit's mode is no-cors and method is not simple
+Pass TypeError from request constructor takes priority - RequestInit's cache mode is only-if-cached and mode is not same-origin
+Pass TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode cors
+Pass TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode no-cors
+Pass TypeError from request constructor takes priority - Bad referrerPolicy init parameter value
+Pass TypeError from request constructor takes priority - Bad mode init parameter value
+Pass TypeError from request constructor takes priority - Bad credentials init parameter value
+Pass TypeError from request constructor takes priority - Bad cache init parameter value
+Pass TypeError from request constructor takes priority - Bad redirect init parameter value
+Pass Request objects have a signal property
+Pass Signal on request object
+Pass Signal on request object should also have abort reason
+Pass Signal on request object created from request object
+Pass Signal on request object created from request object, with signal on second request
+Pass Signal on request object created from request object, with signal on second request overriding another
+Pass Signal retained after unrelated properties are overridden by fetch
+Pass Signal removed by setting to null
+Pass Already aborted signal rejects immediately
+Pass Request is still 'used' if signal is aborted before fetching
+Fail response.arrayBuffer() rejects if already aborted
+Pass response.arrayBuffer() rejects with abort reason if already aborted
+Fail response.blob() rejects if already aborted
+Pass response.blob() rejects with abort reason if already aborted
+Fail response.bytes() rejects if already aborted
+Pass response.bytes() rejects with abort reason if already aborted
+Fail response.formData() rejects if already aborted
+Pass response.formData() rejects with abort reason if already aborted
+Fail response.json() rejects if already aborted
+Pass response.json() rejects with abort reason if already aborted
+Fail response.text() rejects if already aborted
+Pass response.text() rejects with abort reason if already aborted
+Fail Call text() twice on aborted response
+Pass Already aborted signal does not make request
+Pass Already aborted signal can be used for many fetches
+Pass Signal can be used to abort other fetches, even if another fetch succeeded before aborting
+Pass Underlying connection is closed when aborting after receiving response
+Pass Underlying connection is closed when aborting after receiving response - no-cors
+Pass Fetch aborted & connection closed when aborted after calling response.arrayBuffer()
+Pass Fetch aborted & connection closed when aborted after calling response.blob()
+Pass Fetch aborted & connection closed when aborted after calling response.bytes()
+Pass Fetch aborted & connection closed when aborted after calling response.formData()
+Pass Fetch aborted & connection closed when aborted after calling response.json()
+Pass Fetch aborted & connection closed when aborted after calling response.text()
+Pass Stream errors once aborted. Underlying connection closed.
+Pass Stream errors once aborted with abort reason. Underlying connection closed.
+Pass Stream errors once aborted, after reading. Underlying connection closed.
+Pass Stream will not error if body is empty. It's closed with an empty queue before it errors.
+Pass Readable stream synchronously cancels with AbortError if aborted before reading
+Pass Signal state is cloned
+Pass Clone aborts with original controller
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/abort/general.any.html b/Tests/LibWeb/Text/input/wpt-import/fetch/api/abort/general.any.html
new file mode 100644
index 00000000000..05e39555ed3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/abort/general.any.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<meta charset=utf-8>
+<meta name="timeout" content="long">
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../../resources/testharness.js"></script>
+<script src="../../../resources/testharnessreport.js"></script>
+<script src="../../../common/utils.js"></script>
+<script src="../../../common/get-host-info.sub.js"></script>
+<script src="../request/request-error.js"></script>
+<div id=log></div>
+<script src="../../../fetch/api/abort/general.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/abort/general.any.js b/Tests/LibWeb/Text/input/wpt-import/fetch/api/abort/general.any.js
new file mode 100644
index 00000000000..5d085cd2de2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/abort/general.any.js
@@ -0,0 +1,623 @@
+// META: timeout=long
+// META: global=window,worker
+// META: script=/common/utils.js
+// META: script=/common/get-host-info.sub.js
+// META: script=../request/request-error.js
+
+const BODY_METHODS = ['arrayBuffer', 'blob', 'bytes', 'formData', 'json', 'text'];
+
+const error1 = new Error('error1');
+error1.name = 'error1';
+
+// This is used to close connections that weren't correctly closed during the tests,
+// otherwise you can end up running out of HTTP connections.
+let requestAbortKeys = [];
+
+function abortRequests() {
+ const keys = requestAbortKeys;
+ requestAbortKeys = [];
+ return Promise.all(
+ keys.map(key => fetch(`../resources/stash-put.py?key=${key}&value=close`))
+ );
+}
+
+const hostInfo = get_host_info();
+const urlHostname = hostInfo.REMOTE_HOST;
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const fetchPromise = fetch('../resources/data.json', { signal });
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Aborting rejects with AbortError");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort(error1);
+
+ const fetchPromise = fetch('../resources/data.json', { signal });
+
+ await promise_rejects_exactly(t, error1, fetchPromise, 'fetch() should reject with abort reason');
+}, "Aborting rejects with abort reason");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const fetchPromise = fetch('../resources/data.json', { signal });
+ controller.abort(error1);
+
+ await promise_rejects_exactly(t, error1, fetchPromise, 'fetch() should reject with abort reason when aborted after fetch() called');
+}, "Aborting rejects with abort reason when aborted after fetch() called");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const url = new URL('../resources/data.json', location);
+ url.hostname = urlHostname;
+
+ const fetchPromise = fetch(url, {
+ signal,
+ mode: 'no-cors'
+ });
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Aborting rejects with AbortError - no-cors");
+
+// Test that errors thrown from the request constructor take priority over abort errors.
+// badRequestArgTests is from response-error.js
+for (const { args, testName } of badRequestArgTests) {
+ promise_test(async t => {
+ try {
+ // If this doesn't throw, we'll effectively skip the test.
+ // It'll fail properly in ../request/request-error.html
+ new Request(...args);
+ }
+ catch (err) {
+ const controller = new AbortController();
+ controller.abort();
+
+ // Add signal to 2nd arg
+ args[1] = args[1] || {};
+ args[1].signal = controller.signal;
+ await promise_rejects_js(t, TypeError, fetch(...args));
+ }
+ }, `TypeError from request constructor takes priority - ${testName}`);
+}
+
+test(() => {
+ const request = new Request('');
+ assert_true(Boolean(request.signal), "Signal member is present & truthy");
+ assert_equals(request.signal.constructor, AbortSignal);
+}, "Request objects have a signal property");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json', { signal });
+
+ assert_true(Boolean(request.signal), "Signal member is present & truthy");
+ assert_equals(request.signal.constructor, AbortSignal);
+ assert_not_equals(request.signal, signal, 'Request has a new signal, not a reference');
+ assert_true(request.signal.aborted, `Request's signal has aborted`);
+
+ const fetchPromise = fetch(request);
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Signal on request object");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort(error1);
+
+ const request = new Request('../resources/data.json', { signal });
+
+ assert_not_equals(request.signal, signal, 'Request has a new signal, not a reference');
+ assert_true(request.signal.aborted, `Request's signal has aborted`);
+ assert_equals(request.signal.reason, error1, `Request's signal's abort reason is error1`);
+
+ const fetchPromise = fetch(request);
+
+ await promise_rejects_exactly(t, error1, fetchPromise, "fetch() should reject with abort reason");
+}, "Signal on request object should also have abort reason");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json', { signal });
+ const requestFromRequest = new Request(request);
+
+ const fetchPromise = fetch(requestFromRequest);
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Signal on request object created from request object");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json');
+ const requestFromRequest = new Request(request, { signal });
+
+ const fetchPromise = fetch(requestFromRequest);
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Signal on request object created from request object, with signal on second request");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json', { signal: new AbortController().signal });
+ const requestFromRequest = new Request(request, { signal });
+
+ const fetchPromise = fetch(requestFromRequest);
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Signal on request object created from request object, with signal on second request overriding another");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json', { signal });
+
+ const fetchPromise = fetch(request, {method: 'POST'});
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+}, "Signal retained after unrelated properties are overridden by fetch");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json', { signal });
+
+ const data = await fetch(request, { signal: null }).then(r => r.json());
+ assert_equals(data.key, 'value', 'Fetch fully completes');
+}, "Signal removed by setting to null");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const log = [];
+
+ await Promise.all([
+ fetch('../resources/data.json', { signal }).then(
+ () => assert_unreached("Fetch must not resolve"),
+ () => log.push('fetch-reject')
+ ),
+ Promise.resolve().then(() => log.push('next-microtask'))
+ ]);
+
+ assert_array_equals(log, ['fetch-reject', 'next-microtask']);
+}, "Already aborted signal rejects immediately");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('../resources/data.json', {
+ signal,
+ method: 'POST',
+ body: 'foo',
+ headers: { 'Content-Type': 'text/plain' }
+ });
+
+ await fetch(request).catch(() => {});
+
+ assert_true(request.bodyUsed, "Body has been used");
+}, "Request is still 'used' if signal is aborted before fetching");
+
+for (const bodyMethod of BODY_METHODS) {
+ promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const log = [];
+ const response = await fetch('../resources/data.json', { signal });
+
+ controller.abort();
+
+ const bodyPromise = response[bodyMethod]();
+
+ await Promise.all([
+ bodyPromise.catch(() => log.push(`${bodyMethod}-reject`)),
+ Promise.resolve().then(() => log.push('next-microtask'))
+ ]);
+
+ await promise_rejects_dom(t, "AbortError", bodyPromise);
+
+ assert_array_equals(log, [`${bodyMethod}-reject`, 'next-microtask']);
+ }, `response.${bodyMethod}() rejects if already aborted`);
+
+ promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const response = await fetch('../resources/data.json', { signal });
+
+ controller.abort(error1);
+
+ const bodyPromise = response[bodyMethod]();
+
+ await promise_rejects_exactly(t, error1, bodyPromise,
+ `${bodyMethod}() should reject with abort reason`);
+ }, `response.${bodyMethod}() rejects with abort reason if already aborted`);
+}
+
+promise_test(async (t) => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const res = await fetch('../resources/data.json', { signal });
+ controller.abort();
+
+ await promise_rejects_dom(t, 'AbortError', res.text());
+ await promise_rejects_dom(t, 'AbortError', res.text());
+}, 'Call text() twice on aborted response');
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+ controller.abort();
+
+ await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }).catch(() => {});
+
+ // I'm hoping this will give the browser enough time to (incorrectly) make the request
+ // above, if it intends to.
+ await fetch('../resources/data.json').then(r => r.json());
+
+ const response = await fetch(`../resources/stash-take.py?key=${stateKey}`);
+ const data = await response.json();
+
+ assert_equals(data, null, "Request hasn't been made to the server");
+}, "Already aborted signal does not make request");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const fetches = [];
+
+ for (let i = 0; i < 3; i++) {
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ fetches.push(
+ fetch(`../resources/infinite-slow-response.py?${i}&abortKey=${abortKey}`, { signal })
+ );
+ }
+
+ for (const fetchPromise of fetches) {
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+ }
+}, "Already aborted signal can be used for many fetches");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ await fetch('../resources/data.json', { signal }).then(r => r.json());
+
+ controller.abort();
+
+ const fetches = [];
+
+ for (let i = 0; i < 3; i++) {
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ fetches.push(
+ fetch(`../resources/infinite-slow-response.py?${i}&abortKey=${abortKey}`, { signal })
+ );
+ }
+
+ for (const fetchPromise of fetches) {
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+ }
+}, "Signal can be used to abort other fetches, even if another fetch succeeded before aborting");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });
+
+ const beforeAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());
+ assert_equals(beforeAbortResult, "open", "Connection is open");
+
+ controller.abort();
+
+ // The connection won't close immediately, but it should close at some point:
+ const start = Date.now();
+
+ while (true) {
+ // Stop spinning if 10 seconds have passed
+ if (Date.now() - start > 10000) throw Error('Timed out');
+
+ const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());
+ if (afterAbortResult == 'closed') break;
+ }
+}, "Underlying connection is closed when aborting after receiving response");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ const url = new URL(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, location);
+ url.hostname = urlHostname;
+
+ await fetch(url, {
+ signal,
+ mode: 'no-cors'
+ });
+
+ const stashTakeURL = new URL(`../resources/stash-take.py?key=${stateKey}`, location);
+ stashTakeURL.hostname = urlHostname;
+
+ const beforeAbortResult = await fetch(stashTakeURL).then(r => r.json());
+ assert_equals(beforeAbortResult, "open", "Connection is open");
+
+ controller.abort();
+
+ // The connection won't close immediately, but it should close at some point:
+ const start = Date.now();
+
+ while (true) {
+ // Stop spinning if 10 seconds have passed
+ if (Date.now() - start > 10000) throw Error('Timed out');
+
+ const afterAbortResult = await fetch(stashTakeURL).then(r => r.json());
+ if (afterAbortResult == 'closed') break;
+ }
+}, "Underlying connection is closed when aborting after receiving response - no-cors");
+
+for (const bodyMethod of BODY_METHODS) {
+ promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });
+
+ const beforeAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());
+ assert_equals(beforeAbortResult, "open", "Connection is open");
+
+ const bodyPromise = response[bodyMethod]();
+
+ controller.abort();
+
+ await promise_rejects_dom(t, "AbortError", bodyPromise);
+
+ const start = Date.now();
+
+ while (true) {
+ // Stop spinning if 10 seconds have passed
+ if (Date.now() - start > 10000) throw Error('Timed out');
+
+ const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());
+ if (afterAbortResult == 'closed') break;
+ }
+ }, `Fetch aborted & connection closed when aborted after calling response.${bodyMethod}()`);
+}
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });
+ const reader = response.body.getReader();
+
+ controller.abort();
+
+ await promise_rejects_dom(t, "AbortError", reader.read());
+ await promise_rejects_dom(t, "AbortError", reader.closed);
+
+ // The connection won't close immediately, but it should close at some point:
+ const start = Date.now();
+
+ while (true) {
+ // Stop spinning if 10 seconds have passed
+ if (Date.now() - start > 10000) throw Error('Timed out');
+
+ const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());
+ if (afterAbortResult == 'closed') break;
+ }
+}, "Stream errors once aborted. Underlying connection closed.");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });
+ const reader = response.body.getReader();
+
+ controller.abort(error1);
+
+ await promise_rejects_exactly(t, error1, reader.read());
+ await promise_rejects_exactly(t, error1, reader.closed);
+
+ // The connection won't close immediately, but it should close at some point:
+ const start = Date.now();
+
+ await t.step_wait(async () => {
+ const response = await fetch(`../resources/stash-take.py?key=${stateKey}`);
+ const json = await response.json();
+ return json == 'closed';
+ }, "underlying connection should close");
+}, "Stream errors once aborted with abort reason. Underlying connection closed.");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const stateKey = token();
+ const abortKey = token();
+ requestAbortKeys.push(abortKey);
+
+ const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal });
+ const reader = response.body.getReader();
+
+ await reader.read();
+
+ controller.abort();
+
+ await promise_rejects_dom(t, "AbortError", reader.read());
+ await promise_rejects_dom(t, "AbortError", reader.closed);
+
+ // The connection won't close immediately, but it should close at some point:
+ const start = Date.now();
+
+ while (true) {
+ // Stop spinning if 10 seconds have passed
+ if (Date.now() - start > 10000) throw Error('Timed out');
+
+ const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json());
+ if (afterAbortResult == 'closed') break;
+ }
+}, "Stream errors once aborted, after reading. Underlying connection closed.");
+
+promise_test(async t => {
+ await abortRequests();
+
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const response = await fetch(`../resources/empty.txt`, { signal });
+
+ // Read whole response to ensure close signal has sent.
+ await response.clone().text();
+
+ const reader = response.body.getReader();
+
+ controller.abort();
+
+ const item = await reader.read();
+
+ assert_true(item.done, "Stream is done");
+}, "Stream will not error if body is empty. It's closed with an empty queue before it errors.");
+
+promise_test(async t => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ let cancelReason;
+
+ const body = new ReadableStream({
+ pull(controller) {
+ controller.enqueue(new Uint8Array([42]));
+ },
+ cancel(reason) {
+ cancelReason = reason;
+ }
+ });
+
+ const fetchPromise = fetch('../resources/empty.txt', {
+ body, signal,
+ method: 'POST',
+ duplex: 'half',
+ headers: {
+ 'Content-Type': 'text/plain'
+ }
+ });
+
+ assert_true(!!cancelReason, 'Cancel called sync');
+ assert_equals(cancelReason.constructor, DOMException);
+ assert_equals(cancelReason.name, 'AbortError');
+
+ await promise_rejects_dom(t, "AbortError", fetchPromise);
+
+ const fetchErr = await fetchPromise.catch(e => e);
+
+ assert_equals(cancelReason, fetchErr, "Fetch rejects with same error instance");
+}, "Readable stream synchronously cancels with AbortError if aborted before reading");
+
+test(() => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ controller.abort();
+
+ const request = new Request('.', { signal });
+ const requestSignal = request.signal;
+
+ const clonedRequest = request.clone();
+
+ assert_equals(requestSignal, request.signal, "Original request signal the same after cloning");
+ assert_true(request.signal.aborted, "Original request signal aborted");
+ assert_not_equals(clonedRequest.signal, request.signal, "Cloned request has different signal");
+ assert_true(clonedRequest.signal.aborted, "Cloned request signal aborted");
+}, "Signal state is cloned");
+
+test(() => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const request = new Request('.', { signal });
+ const clonedRequest = request.clone();
+
+ const log = [];
+
+ request.signal.addEventListener('abort', () => log.push('original-aborted'));
+ clonedRequest.signal.addEventListener('abort', () => log.push('clone-aborted'));
+
+ controller.abort();
+
+ assert_array_equals(log, ['original-aborted', 'clone-aborted'], "Abort events fired in correct order");
+ assert_true(request.signal.aborted, 'Signal aborted');
+ assert_true(clonedRequest.signal.aborted, 'Signal aborted');
+}, "Clone aborts with original controller");
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/request/request-error.js b/Tests/LibWeb/Text/input/wpt-import/fetch/api/request/request-error.js
new file mode 100644
index 00000000000..cf77313f5bc
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/request/request-error.js
@@ -0,0 +1,57 @@
+const badRequestArgTests = [
+ {
+ args: ["", { "window": "http://test.url" }],
+ testName: "RequestInit's window is not null"
+ },
+ {
+ args: ["http://:not a valid URL"],
+ testName: "Input URL is not valid"
+ },
+ {
+ args: ["http://user:[email protected]"],
+ testName: "Input URL has credentials"
+ },
+ {
+ args: ["", { "mode": "navigate" }],
+ testName: "RequestInit's mode is navigate"
+ },
+ {
+ args: ["", { "referrer": "http://:not a valid URL" }],
+ testName: "RequestInit's referrer is invalid"
+ },
+ {
+ args: ["", { "method": "IN VALID" }],
+ testName: "RequestInit's method is invalid"
+ },
+ {
+ args: ["", { "method": "TRACE" }],
+ testName: "RequestInit's method is forbidden"
+ },
+ {
+ args: ["", { "mode": "no-cors", "method": "PUT" }],
+ testName: "RequestInit's mode is no-cors and method is not simple"
+ },
+ {
+ args: ["", { "mode": "cors", "cache": "only-if-cached" }],
+ testName: "RequestInit's cache mode is only-if-cached and mode is not same-origin"
+ },
+ {
+ args: ["test", { "cache": "only-if-cached", "mode": "cors" }],
+ testName: "Request with cache mode: only-if-cached and fetch mode cors"
+ },
+ {
+ args: ["test", { "cache": "only-if-cached", "mode": "no-cors" }],
+ testName: "Request with cache mode: only-if-cached and fetch mode no-cors"
+ }
+];
+
+badRequestArgTests.push(
+ ...["referrerPolicy", "mode", "credentials", "cache", "redirect"].map(optionProp => {
+ const options = {};
+ options[optionProp] = "BAD";
+ return {
+ args: ["", options],
+ testName: `Bad ${optionProp} init parameter value`
+ };
+ })
+);
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/data.json b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/data.json
new file mode 100644
index 00000000000..76519fa8cc2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/data.json
@@ -0,0 +1 @@
+{"key": "value"}
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/empty.txt b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/empty.txt
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/infinite-slow-response.py b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/infinite-slow-response.py
new file mode 100644
index 00000000000..a26cd8064c8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/infinite-slow-response.py
@@ -0,0 +1,35 @@
+import time
+
+
+def url_dir(request):
+ return u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/'
+
+
+def stash_write(request, key, value):
+ """Write to the stash, overwriting any previous value"""
+ request.server.stash.take(key, url_dir(request))
+ request.server.stash.put(key, value, url_dir(request))
+
+
+def main(request, response):
+ stateKey = request.GET.first(b"stateKey", b"")
+ abortKey = request.GET.first(b"abortKey", b"")
+
+ if stateKey:
+ stash_write(request, stateKey, 'open')
+
+ response.headers.set(b"Content-type", b"text/plain")
+ response.write_status_headers()
+
+ # Writing an initial 2k so browsers realise it's there. *shrug*
+ response.writer.write(b"." * 2048)
+
+ while True:
+ if not response.writer.write(b"."):
+ break
+ if abortKey and request.server.stash.take(abortKey, url_dir(request)):
+ break
+ time.sleep(0.01)
+
+ if stateKey:
+ stash_write(request, stateKey, 'closed')
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/stash-put.py b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/stash-put.py
new file mode 100644
index 00000000000..91c198abb7d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/stash-put.py
@@ -0,0 +1,41 @@
+from wptserve.utils import isomorphic_decode
+
+def should_be_treated_as_same_origin_request(request):
+ """Tells whether request should be treated as same-origin request."""
+ # In both of the following cases, allow to proceed with handling to simulate
+ # 'no-cors' mode: response is sent, but browser will make it opaque.
+ if request.GET.first(b'mode') == b'no-cors':
+ return True
+
+ # We can't rely on the Origin header field of a fetch request, as it is only
+ # present for 'cors' mode or methods other than 'GET'/'HEAD' (i.e. present for
+ # 'POST'). See https://fetch.spec.whatwg.org/#http-origin
+ assert 'frame_origin ' in request.GET
+ frame_origin = request.GET.first(b'frame_origin').decode('utf-8')
+ host_origin = request.url_parts.scheme + '://' + request.url_parts.netloc
+ return frame_origin == host_origin
+
+def main(request, response):
+ if request.method == u'OPTIONS':
+ # CORS preflight
+ response.headers.set(b'Access-Control-Allow-Origin', b'*')
+ response.headers.set(b'Access-Control-Allow-Methods', b'*')
+ response.headers.set(b'Access-Control-Allow-Headers', b'*')
+ return 'done'
+
+ if b'disallow_cross_origin' not in request.GET:
+ response.headers.set(b'Access-Control-Allow-Origin', b'*')
+ elif not should_be_treated_as_same_origin_request(request):
+ # As simple requests will not trigger preflight, we have to manually block
+ # cors requests before making any changes to storage.
+ # https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
+ # https://fetch.spec.whatwg.org/#cors-preflight-fetch
+ return 'not stashing for cors request'
+
+ url_dir = u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/'
+ key = request.GET.first(b'key')
+ value = request.GET.first(b'value')
+ # value here must be a text string. It will be json.dump()'ed in stash-take.py.
+ request.server.stash.put(key, isomorphic_decode(value), url_dir)
+
+ return 'done'
diff --git a/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/stash-take.py b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/stash-take.py
new file mode 100644
index 00000000000..e6db80dd86d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/fetch/api/resources/stash-take.py
@@ -0,0 +1,9 @@
+from wptserve.handlers import json_handler
+
+
+@json_handler
+def main(request, response):
+ dir = u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/'
+ key = request.GET.first(b"key")
+ response.headers.set(b'Access-Control-Allow-Origin', b'*')
+ return request.server.stash.take(key, dir)