Skip to content

Truly independent web browser

LibWeb: Stop fetches without a fetch record when a document aborts

Luke Wilde3487273f44bd
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index bf8abbae5b7..1d3e2429913 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -6736,6 +6736,16 @@ void Document::abort()
if (auto window = this->window(); window && window->associated_document_if_any().ptr() == this) {
for (auto& fetch_record : relevant_settings_object().fetch_group())
cancel_fetch(fetch_record.fetch_controller());
+
+ for (auto& controller : HTML::relevant_agent(*this).fetch_controller_registry.controllers()) {
+ if (!controller->task_destination().is_for_document(*this))
+ continue;
+ // AD-HOC: A keepalive fetch without a fetch record, such as a violation report, outlives the document, as
+ // terminating a fetch group leaves its keepalive fetches running.
+ if (controller->is_keepalive())
+ continue;
+ cancel_fetch(controller.ptr());
+ }
}
if (canceled_fetch)
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 0be1ded8615..15731a01912 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -328,6 +328,7 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:
auto controller = Infrastructure::FetchController::create(controller_registry);
auto fetch_params = Infrastructure::FetchParams::create(controller, request, algorithms, timing_info, current_loader_config());
controller->set_task_destination(task_destination);
+ controller->set_keepalive(request.keepalive());
fetch_params->set_cross_origin_isolated_capability(cross_origin_isolated_capability);
fetch_params->set_has_response_body_transfer_lease(create_response_body_transfer_lease == CreateResponseBodyTransferLease::Yes);
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
index 9cc62652e9f..8a817173826 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
@@ -77,6 +77,9 @@ public:
[[nodiscard]] TaskDestination const& task_destination() const { return m_task_destination; }
void set_task_destination(TaskDestination task_destination) { m_task_destination = move(task_destination); }
+ [[nodiscard]] bool is_keepalive() const { return m_is_keepalive; }
+ void set_keepalive(bool is_keepalive) { m_is_keepalive = is_keepalive; }
+
// AD-HOC: Whether this fetch's response has arrived: as headers from the network, or at main fetch. From then on,
// its body delivery is queued as event-loop tasks, and its response processing captures its task
// destination as it was then — so re-targeting the fetch no longer reaches either.
@@ -169,6 +172,7 @@ private:
// task destination (default null)
// Null, a global object, or a parallel queue.
TaskDestination m_task_destination;
+ bool m_is_keepalive { false };
bool m_response_arrived { false };
// NB: Assumes one waiting consumer for a pending preloaded response.
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp
index 5aa01cf7bdc..895b08f8d8c 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/Atomic.h>
+#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>
namespace Web::Fetch::Infrastructure {
@@ -36,4 +37,13 @@ GC::Ptr<FetchController> FetchControllerRegistry::find(FetchControllerToken toke
return m_controllers.get(token.m_serial).value_or(nullptr);
}
+Vector<GC::Root<FetchController>> FetchControllerRegistry::controllers() const
+{
+ Vector<GC::Root<FetchController>> controllers;
+ controllers.ensure_capacity(m_controllers.size());
+ for (auto const& entry : m_controllers)
+ controllers.unchecked_append(GC::make_root(*entry.value));
+ return controllers;
+}
+
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h
index 4b410d343f0..84a566a3a65 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h
@@ -9,8 +9,10 @@
#include <AK/Badge.h>
#include <AK/HashMap.h>
#include <AK/Noncopyable.h>
+#include <AK/Vector.h>
#include <AK/Weakable.h>
#include <LibGC/Ptr.h>
+#include <LibGC/Root.h>
#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Infrastructure/FetchControllerToken.h>
#include <LibWeb/Forward.h>
@@ -30,6 +32,8 @@ public:
[[nodiscard]] GC::Ptr<FetchController> find(FetchControllerToken) const;
+ [[nodiscard]] Vector<GC::Root<FetchController>> controllers() const;
+
private:
u64 m_id { 0 };
HashMap<u64, GC::RawPtr<FetchController>> m_controllers;
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/Task.cpp b/Libraries/LibWeb/Fetch/Infrastructure/Task.cpp
index f76a842c7a6..d56bbd426fc 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/Task.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/Task.cpp
@@ -38,6 +38,14 @@ void TaskDestination::visit_edges(GC::Cell::Visitor& visitor) const
visitor.visit(document_override);
}
+bool TaskDestination::is_for_document(DOM::Document const& document) const
+{
+ if (document_override)
+ return document_override.ptr() == &document;
+ auto const* global_object = get_pointer<GC::Ref<JS::Object>>();
+ return global_object && global_object->ptr() == &HTML::relevant_global_object(document);
+}
+
// https://fetch.spec.whatwg.org/#queue-a-fetch-task
HTML::TaskID queue_fetch_task(TaskDestination task_destination, GC::Ref<GC::Function<void()>> algorithm)
{
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/Task.h b/Libraries/LibWeb/Fetch/Infrastructure/Task.h
index 4737b104108..aaf4e1062d6 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/Task.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/Task.h
@@ -23,6 +23,9 @@ struct WEB_API TaskDestination : public Variant<Empty, GC::Ref<JS::Object>, Nonn
void visit_edges(GC::Cell::Visitor&) const;
+ // Whether tasks queued on this destination go to document or to its relevant global object.
+ [[nodiscard]] bool is_for_document(DOM::Document const&) const;
+
GC::Ptr<DOM::Document> document_override;
};
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index f2b2089c189..5b7a1564bc8 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -31,6 +31,7 @@ set(TEST_SOURCES
TestFetchBodyStream.cpp
TestFetchByteChannel.cpp
TestFetchControllerRegistry.cpp
+ TestFetchTaskDestination.cpp
TestFetchEngineMessages.cpp
TestFetchExecutor.cpp
TestFetchResponse.cpp
@@ -99,6 +100,7 @@ target_link_libraries(TestFetchBodyDeliveryGate PRIVATE LibCore LibThreading)
target_link_libraries(TestFetchBodyStream PRIVATE LibCore LibGC LibJS)
target_link_libraries(TestFetchByteChannel PRIVATE LibThreading)
target_link_libraries(TestFetchControllerRegistry PRIVATE LibGC)
+target_link_libraries(TestFetchTaskDestination PRIVATE LibCore LibGC LibJS LibURL)
target_link_libraries(TestFetchResponse PRIVATE LibGC LibHTTP LibJS LibRequests LibURL)
target_link_libraries(TestFetchURL PRIVATE LibURL)
target_link_libraries(TestImageData PRIVATE LibGC LibJS)
diff --git a/Tests/LibWeb/TestFetchTaskDestination.cpp b/Tests/LibWeb/TestFetchTaskDestination.cpp
new file mode 100644
index 00000000000..aebd09f8cef
--- /dev/null
+++ b/Tests/LibWeb/TestFetchTaskDestination.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "FetchTestDocument.h"
+#include <LibCore/EventLoop.h>
+#include <LibTest/TestCase.h>
+#include <LibWeb/Fetch/Infrastructure/Task.h>
+#include <LibWeb/HTML/EventLoop/Task.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Window.h>
+
+using Web::Fetch::Infrastructure::TaskDestination;
+
+TEST_CASE(a_document_override_takes_precedence_over_a_shared_global)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ auto document = create_test_document();
+ auto& window = *document->window();
+ auto other_document = Web::DOM::Document::create(document->page(), window);
+ auto& global = Web::HTML::relevant_global_object(*document);
+
+ TaskDestination for_the_global { GC::Ref { global } };
+ EXPECT(for_the_global.is_for_document(*document));
+ EXPECT(for_the_global.is_for_document(*other_document));
+
+ TaskDestination for_the_other_document { GC::Ref { global } };
+ for_the_other_document.document_override = other_document;
+ EXPECT(for_the_other_document.is_for_document(*other_document));
+ EXPECT(!for_the_other_document.is_for_document(*document));
+
+ TaskDestination for_the_document { GC::Ref { global } };
+ for_the_document.document_override = document;
+ EXPECT(for_the_document.is_for_document(*document));
+ EXPECT(!for_the_document.is_for_document(*other_document));
+}
+
+TEST_CASE(a_parallel_queue_is_for_no_document)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ auto document = create_test_document();
+
+ TaskDestination parallel_queue { Web::HTML::ParallelQueue::create() };
+ EXPECT(!parallel_queue.is_for_document(*document));
+}
diff --git a/Tests/LibWeb/Text/expected/Fetch/download-outlives-its-document.txt b/Tests/LibWeb/Text/expected/Fetch/download-outlives-its-document.txt
new file mode 100644
index 00000000000..21fc0a83b03
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/download-outlives-its-document.txt
@@ -0,0 +1 @@
+after its document went away, the download finished with all 65536 bytes
diff --git a/Tests/LibWeb/Text/expected/Fetch/object-data-fetch-stops-with-its-document.txt b/Tests/LibWeb/Text/expected/Fetch/object-data-fetch-stops-with-its-document.txt
new file mode 100644
index 00000000000..7cd199bfd37
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/object-data-fetch-stops-with-its-document.txt
@@ -0,0 +1,2 @@
+object data held before its headers, after its document went away: released
+object data held mid-body, after its document went away: released
diff --git a/Tests/LibWeb/Text/expected/Fetch/violation-report-outlives-its-document.txt b/Tests/LibWeb/Text/expected/Fetch/violation-report-outlives-its-document.txt
new file mode 100644
index 00000000000..207a5e2fb80
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/violation-report-outlives-its-document.txt
@@ -0,0 +1,2 @@
+report still running after its document went away: true
+report finished once its response arrived
diff --git a/Tests/LibWeb/Text/expected/ServiceWorker/service-worker-register-stopped.txt b/Tests/LibWeb/Text/expected/ServiceWorker/service-worker-register-stopped.txt
new file mode 100644
index 00000000000..e1e7bb1e6e3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ServiceWorker/service-worker-register-stopped.txt
@@ -0,0 +1,7 @@
+classic, stopped before the script's headers: TypeError
+classic, stopped while the script's body arrives: TypeError
+module, stopped before the script's headers: TypeError
+module, stopped while the script's body arrives: TypeError
+module, stopped while it imports a module: TypeError
+classic, served as plain text: SecurityError
+classic, after them: InternalError
diff --git a/Tests/LibWeb/Text/input/Fetch/download-outlives-its-document.html b/Tests/LibWeb/Text/input/Fetch/download-outlives-its-document.html
new file mode 100644
index 00000000000..1992befe7b8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/download-outlives-its-document.html
@@ -0,0 +1,79 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Resolves with the server's answer once it has the status, or with null after twenty seconds.
+ async function waitForDownloadStatus(url, status) {
+ const deadline = performance.now() + 20000;
+ while (performance.now() < deadline) {
+ const response = await fetch(url).catch(() => null);
+ if (response?.status === status)
+ return response;
+ await new Promise(resolve => setTimeout(resolve, 20));
+ }
+ return null;
+ }
+
+ // A download that the UI process has taken over outlives the document that started it.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const id = uniqueID();
+ const filename = `download-outlives-its-document-${id}.bin`;
+ const token = `download-outlives-its-document-${id}`;
+
+ const bytes = new Uint8Array(64 * 1024);
+ let binary = "";
+ for (let i = 0; i < bytes.length; ++i) {
+ bytes[i] = i % 251;
+ binary += String.fromCharCode(bytes[i]);
+ }
+
+ const download = new URL(await server.createEcho("GET", `/download-${id}`, {
+ status: 200,
+ headers: {
+ "Cache-Control": "no-store",
+ "Content-Type": "application/octet-stream",
+ "Content-Disposition": `attachment; filename="${filename}"`,
+ "Content-Length": String(bytes.length),
+ },
+ body: btoa(binary),
+ body_encoding: "base64",
+ }));
+ download.search = `?chunks=1024&chunk_unblock_tokens=${token}`;
+
+ const page = await server.createEcho("GET", `/download-page-${id}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>addEventListener("load", () => location.href = "${download.href}");<\/script>`,
+ });
+
+ const frame = document.createElement("iframe");
+ frame.src = page;
+ document.body.append(frame);
+
+ const downloadURL = `${server.baseURL}/downloads/${filename}`;
+ try {
+ // The server holds the rest of the body until the frame's document has gone away.
+ if (!(await waitForDownloadStatus(downloadURL, 202))) {
+ println("the download did not start");
+ return;
+ }
+
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ frame.src = "about:blank";
+ });
+ frame.remove();
+ } finally {
+ await fetch(`${server.baseURL}/unblock/${token}`);
+ }
+
+ const finished = await waitForDownloadStatus(downloadURL, 200);
+ if (!finished) {
+ println("after its document went away, the download did not finish");
+ return;
+ }
+ const saved = new Uint8Array(await finished.arrayBuffer());
+ const intact = saved.length === bytes.length && saved.every((byte, index) => byte === bytes[index]);
+ println(`after its document went away, the download finished with ${intact ? "all" : "different"} ${saved.length} bytes`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/object-data-fetch-stops-with-its-document.html b/Tests/LibWeb/Text/input/Fetch/object-data-fetch-stops-with-its-document.html
new file mode 100644
index 00000000000..6bccaf7d27e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/object-data-fetch-stops-with-its-document.html
@@ -0,0 +1,161 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Runs on a hostname of its own, in a process apart from the test page.
+ async function checkObjectDataFetchesStopWithTheirDocument(cases) {
+ const output = [];
+ const println = line => output.push(line);
+
+ const countCells = className => {
+ let count = 0;
+ for (const cell of Object.values(JSON.parse(internals.dumpGCGraph()))) {
+ if (cell.class_name === className)
+ ++count;
+ }
+ return count;
+ };
+
+ const waitUntil = async condition => {
+ while (!(await condition()))
+ await new Promise(resolve => setTimeout(resolve, 10));
+ };
+
+ // The test's requests to the server go through the parent page, and add no cells to this process.
+ let questionCount = 0;
+ const askParent = question =>
+ new Promise(resolve => {
+ const id = ++questionCount;
+ addEventListener("message", function receive(event) {
+ if (event.data?.answered !== id)
+ return;
+ removeEventListener("message", receive);
+ resolve();
+ });
+ parent.postMessage({ question: { ...question, id } }, "*");
+ });
+ const waitForRequestAtServer = url => askParent({ waitForRequest: url });
+ const unblock = url => askParent({ unblock: url });
+
+ // One collection may not free a cell that nothing holds.
+ const waitForPumps = async count => {
+ const deadline = performance.now() + 20000;
+ let pumps;
+ do {
+ await internals.gcAsync();
+ pumps = countCells("NetworkBodyPump");
+ if (pumps === count)
+ return "released";
+ await new Promise(resolve => setTimeout(resolve, 10));
+ } while (performance.now() < deadline);
+ return `left ${pumps - count} pumps`;
+ };
+
+ await internals.gcAsync();
+ const initialPumps = countCells("NetworkBodyPump");
+ const initialPullSources = countCells("BodyStreamPullSource");
+
+ for (const held of cases) {
+ const frame = document.createElement("iframe");
+ frame.src = held.page;
+ document.body.append(frame);
+
+ // The server has the object's request, and holds its response.
+ await waitForRequestAtServer(held.recorded);
+ await waitUntil(() => countCells("NetworkBodyPump") > initialPumps);
+ if (held.midBody)
+ await waitUntil(() => countCells("BodyStreamPullSource") > initialPullSources);
+
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ frame.src = "about:blank";
+ });
+ println(`object data held ${held.name}, after its document went away: ${await waitForPumps(initialPumps)}`);
+ frame.remove();
+ await unblock(held.unblock);
+ }
+
+ return output;
+ }
+
+ promiseTest(async () => {
+ const hostname = uniqueLocalhostHostname("object-data-fetch");
+ const server = httpTestServer();
+ const onHostname = url => {
+ const result = new URL(url);
+ result.hostname = hostname;
+ return result;
+ };
+
+ const cases = [];
+ for (const midBody of [false, true]) {
+ const token = `object-data-${crypto.randomUUID()}`;
+ const data = onHostname(await server.createEcho("GET", `/object-data-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "application/octet-stream" },
+ body: "x".repeat(64 * 1024),
+ ...(midBody ? {} : { wait_for_unblock: token }),
+ }));
+ const recorded = new URL(server.recordedRequestHeadersURL(data.href));
+ recorded.hostname = hostname;
+ if (midBody) {
+ data.search = `?chunks=1500&chunk_unblock_tokens=${token}`;
+ recorded.search = data.search;
+ }
+ const page = onHostname(await server.createEcho("GET", `/object-data-page-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><object data="${data.href}"></object>`,
+ }));
+ cases.push({
+ name: midBody ? "mid-body" : "before its headers",
+ midBody,
+ page: page.href,
+ recorded: recorded.href,
+ unblock: new URL(`/unblock/${token}`, data).href,
+ });
+ }
+
+ const checker = onHostname(await server.createEcho("GET", `/object-data-checker-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><body><script>
+ (${checkObjectDataFetchesStopWithTheirDocument.toString()})(${JSON.stringify(cases)}).then(
+ output => parent.postMessage({ output }, "*"),
+ error => parent.postMessage({ error: String(error) }, "*"));
+ <\/script>`,
+ }));
+
+ const frame = document.createElement("iframe");
+ window.addEventListener("message", async event => {
+ const question = event.data?.question;
+ if (event.source !== frame.contentWindow || !question)
+ return;
+ if (question.waitForRequest) {
+ while ((await fetch(question.waitForRequest).catch(() => null))?.ok !== true)
+ await new Promise(resolve => setTimeout(resolve, 10));
+ } else {
+ await fetch(question.unblock);
+ }
+ frame.contentWindow.postMessage({ answered: question.id }, "*");
+ });
+ const result = new Promise(resolve => {
+ window.addEventListener("message", function receive(event) {
+ if (event.source !== frame.contentWindow || event.data?.question)
+ return;
+ window.removeEventListener("message", receive);
+ resolve(event.data);
+ });
+ });
+ frame.src = checker;
+ document.body.append(frame);
+ try {
+ const { output, error } = await result;
+ if (error)
+ throw new Error(error);
+ for (const line of output)
+ println(line);
+ } finally {
+ frame.remove();
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/violation-report-outlives-its-document.html b/Tests/LibWeb/Text/input/Fetch/violation-report-outlives-its-document.html
new file mode 100644
index 00000000000..147c3e13643
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/violation-report-outlives-its-document.html
@@ -0,0 +1,148 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Runs on a hostname of its own, in a process apart from the test page.
+ async function checkViolationReportOutlivesItsDocument(urls) {
+ const output = [];
+ const println = line => output.push(line);
+
+ const countPumps = () => {
+ let count = 0;
+ for (const cell of Object.values(JSON.parse(internals.dumpGCGraph()))) {
+ if (cell.class_name === "NetworkBodyPump")
+ ++count;
+ }
+ return count;
+ };
+
+ const waitUntil = async condition => {
+ while (!(await condition()))
+ await new Promise(resolve => setTimeout(resolve, 10));
+ };
+
+ // The test's requests to the server go through the parent page, and add no cells to this process.
+ let questionCount = 0;
+ const askParent = question =>
+ new Promise(resolve => {
+ const id = ++questionCount;
+ addEventListener("message", function receive(event) {
+ if (event.data?.answered !== id)
+ return;
+ removeEventListener("message", receive);
+ resolve();
+ });
+ parent.postMessage({ question: { ...question, id } }, "*");
+ });
+ const waitForRequestAtServer = url => askParent({ waitForRequest: url });
+ const unblock = url => askParent({ unblock: url });
+
+ // One collection may not free a cell that nothing holds.
+ const collectGarbage = async () => {
+ for (let round = 0; round < 5; ++round)
+ await internals.gcAsync();
+ };
+
+ await collectGarbage();
+ const initialPumps = countPumps();
+
+ const frame = document.createElement("iframe");
+ frame.src = urls.page;
+ document.body.append(frame);
+
+ // The server has the report's request, and holds its response.
+ await waitForRequestAtServer(urls.recorded);
+ await waitUntil(() => countPumps() > initialPumps);
+
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ frame.src = "about:blank";
+ });
+ await collectGarbage();
+ println(`report still running after its document went away: ${countPumps() > initialPumps}`);
+
+ await unblock(urls.unblock);
+ await waitUntil(async () => {
+ await internals.gcAsync();
+ return countPumps() === initialPumps;
+ });
+ println("report finished once its response arrived");
+ frame.remove();
+
+ return output;
+ }
+
+ promiseTest(async () => {
+ const hostname = uniqueLocalhostHostname("violation-report");
+ const server = httpTestServer();
+ const onHostname = url => {
+ const result = new URL(url);
+ result.hostname = hostname;
+ return result;
+ };
+
+ const token = `violation-report-${crypto.randomUUID()}`;
+ const report = onHostname(await server.createEcho("POST", `/violation-report-${crypto.randomUUID()}`, {
+ status: 204,
+ headers: { "Cache-Control": "no-store" },
+ wait_for_unblock: token,
+ }));
+ const recorded = onHostname(server.recordedRequestHeadersURL(report.href));
+ const page = onHostname(await server.createEcho("GET", `/violation-report-page-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: {
+ "Cache-Control": "no-store",
+ "Content-Type": "text/html",
+ "Content-Security-Policy": `img-src 'none'; report-uri ${report.href}`,
+ },
+ body: `<!DOCTYPE html><img src="blocked.png">`,
+ }));
+ const urls = {
+ page: page.href,
+ recorded: recorded.href,
+ unblock: new URL(`/unblock/${token}`, report).href,
+ };
+
+ const checker = onHostname(await server.createEcho("GET", `/violation-report-checker-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><body><script>
+ (${checkViolationReportOutlivesItsDocument.toString()})(${JSON.stringify(urls)}).then(
+ output => parent.postMessage({ output }, "*"),
+ error => parent.postMessage({ error: String(error) }, "*"));
+ <\/script>`,
+ }));
+
+ const frame = document.createElement("iframe");
+ window.addEventListener("message", async event => {
+ const question = event.data?.question;
+ if (event.source !== frame.contentWindow || !question)
+ return;
+ if (question.waitForRequest) {
+ while ((await fetch(question.waitForRequest).catch(() => null))?.ok !== true)
+ await new Promise(resolve => setTimeout(resolve, 10));
+ } else {
+ await fetch(question.unblock);
+ }
+ frame.contentWindow.postMessage({ answered: question.id }, "*");
+ });
+ const result = new Promise(resolve => {
+ window.addEventListener("message", function receive(event) {
+ if (event.source !== frame.contentWindow || event.data?.question)
+ return;
+ window.removeEventListener("message", receive);
+ resolve(event.data);
+ });
+ });
+ frame.src = checker;
+ document.body.append(frame);
+ try {
+ const { output, error } = await result;
+ if (error)
+ throw new Error(error);
+ for (const line of output)
+ println(line);
+ } finally {
+ frame.remove();
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ServiceWorker/service-worker-register-stopped.html b/Tests/LibWeb/Text/input/ServiceWorker/service-worker-register-stopped.html
new file mode 100644
index 00000000000..d14b8382d1d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ServiceWorker/service-worker-register-stopped.html
@@ -0,0 +1,83 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Stopping the document whose registration is fetching its script settles the registration and finishes its job,
+ // whether the script's headers or body are still to come, so the next registration for the scope still runs.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const runId = uniqueID();
+ const directory = `/service-worker-register-stopped-${runId}`;
+
+ const javascript = { "Content-Type": "text/javascript", "Cache-Control": "no-store" };
+ const script = async (name, options) => server.createEcho("GET", `${directory}/${name}`, { status: 200, headers: javascript, body: "", ...options });
+ const heldUntil = token => ({ wait_for_unblock: token });
+ const bodyHeldUntil = token => `?chunks=1&chunk_unblock_tokens=${token}`;
+ const unblock = token => fetch(`${server.baseURL}/unblock/${token}`);
+
+ const frameUrl = await server.createEcho("GET", `${directory}/frame.html`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>
+ addEventListener("message", async event => {
+ if (event.data === "stop") {
+ stop();
+ return;
+ }
+ try {
+ await navigator.serviceWorker.register(event.data.url, { type: event.data.type });
+ parent.postMessage("resolved", "*");
+ } catch (error) {
+ parent.postMessage(error.name, "*");
+ }
+ });
+ <\/script>`,
+ });
+ const frame = document.createElement("iframe");
+ document.body.appendChild(frame);
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ frame.src = frameUrl;
+ });
+
+ const register = (url, type) => {
+ const settled = new Promise(resolve => addEventListener("message", event => resolve(event.data), { once: true }));
+ frame.contentWindow.postMessage({ url, type }, "*");
+ return settled;
+ };
+ const stopFrame = () => frame.contentWindow.postMessage("stop", "*");
+
+ for (const type of ["classic", "module"]) {
+ const headersToken = `${runId}-${type}-headers`;
+ const headersHeld = await script(`${type}-headers-held.js`, heldUntil(headersToken));
+ let settled = register(headersHeld, type);
+ await server.waitForRequest(headersHeld);
+ stopFrame();
+ println(`${type}, stopped before the script's headers: ${await settled}`);
+ await unblock(headersToken);
+
+ const bodyToken = `${runId}-${type}-body`;
+ const bodyHeld = (await script(`${type}-body-held.js`, { body: "// held" })) + bodyHeldUntil(bodyToken);
+ settled = register(bodyHeld, type);
+ await server.waitForRequest(bodyHeld);
+ await timeout(200);
+ stopFrame();
+ println(`${type}, stopped while the script's body arrives: ${await settled}`);
+ await unblock(bodyToken);
+ }
+
+ const dependencyToken = `${runId}-dependency`;
+ const dependency = await script("dependency-held.js", heldUntil(dependencyToken));
+ const importer = await script("importer.js", { body: `import ${JSON.stringify(dependency)};` });
+ let settled = register(importer, "module");
+ await server.waitForRequest(dependency);
+ stopFrame();
+ println(`module, stopped while it imports a module: ${await settled}`);
+ await unblock(dependencyToken);
+
+ const plainText = await script("plain-text.js", { headers: { "Content-Type": "text/plain", "Cache-Control": "no-store" } });
+ println(`classic, served as plain text: ${await register(plainText, "classic")}`);
+
+ const valid = await script("valid.js", {});
+ println(`classic, after them: ${await register(valid, "classic")}`);
+ });
+</script>
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
index 8e4d9faa1bd..4c2cb02a9d6 100755
--- a/Tests/LibWebView/test-webdriver-bidi.py
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -343,6 +343,19 @@ def intercepted_event(bidi, method, url):
assert not event["isBlocked"], event
+def take_blocked_requests(bidi, context, url):
+ # An object element can fetch its data once for each time it determines what it represents.
+ bidi.evaluate(context, "0")
+ events = [
+ event
+ for event in bidi.events
+ if event["method"] == "network.beforeRequestSent" and event["params"]["request"]["url"] == url
+ ]
+ for event in events:
+ bidi.events.remove(event)
+ return [event["params"]["request"]["request"] for event in events if event["params"]["isBlocked"]]
+
+
def send_fetch(bidi, context, url, options=None):
return bidi.send(
"script.evaluate",
@@ -932,6 +945,36 @@ def check_network_failed_response_transport(bidi, context, server):
bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+def check_network_document_abort_releases_blocked_object(bidi, context, server):
+ url = f"http://127.0.0.1:{server.server_port}/network-interception/object-data"
+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent"]})["subscription"]
+ intercept = bidi.command(
+ "network.addIntercept",
+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": url}]},
+ )["intercept"]
+ try:
+ # An <object>'s fetch has no fetch record, and its document's abort still stops it, blocked or not.
+ markup = f'<object data="{url}"></object>'
+ bidi.evaluate(
+ context,
+ "window.objectFrame = document.createElement('iframe'); "
+ f"objectFrame.srcdoc = {json.dumps(markup)}; document.body.append(objectFrame); 0",
+ )
+ event = intercepted_event(bidi, "network.beforeRequestSent", url)
+ bidi.evaluate(context, "objectFrame.contentWindow.location = 'about:blank'; 0")
+ deadline = time.monotonic() + 10
+ while bidi.evaluate(context, "objectFrame.contentDocument.URL")["result"].get("value") != "about:blank":
+ assert time.monotonic() < deadline, "The object's frame did not navigate away"
+ for request_id in [event["request"]["request"], *take_blocked_requests(bidi, context, url)]:
+ result = bidi.response(bidi.send("network.continueRequest", {"request": request_id}))
+ assert result["type"] == "error" and result["error"] == "no such request", result
+ finally:
+ if sys.exc_info()[0] is None:
+ bidi.command("network.removeIntercept", {"intercept": intercept})
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+ bidi.evaluate(context, "objectFrame.remove(); 0")
+
+
def check_network_provided_body_at_response_started(bidi, context, server):
url = f"http://127.0.0.1:{server.server_port}/network-interception/fail-body"
provided = "provided body"
@@ -1110,6 +1153,8 @@ def check_network_interception(bidi, context, server, case="all"):
check_network_failed_response_transport(bidi, context, server)
if case in ["all", "provided-body-at-response-started"]:
check_network_provided_body_at_response_started(bidi, context, server)
+ if case in ["all", "document-abort-object"]:
+ check_network_document_abort_releases_blocked_object(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"}, {}]:
@@ -2202,6 +2247,7 @@ if __name__ == "__main__":
"scoped-headers",
"fail-transport",
"provided-body-at-response-started",
+ "document-abort-object",
"auth-gates",
"auth-omit",
"auth-cors",