Skip to content

Truly independent web browser

LibWeb: Let body MIME sniffing report a failed body

Luke Wilde6a720af4fa51
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
index a789e3f5d22..a35d6e6d851 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
@@ -78,8 +78,12 @@ void FetchedDataReceiver::handle_network_data(JS::Realm& realm, Requests::Respon
return;
}
- if (state == NetworkState::Error)
+ if (state == NetworkState::Error) {
+ // A response that died mid-body must not satisfy a sniff waiter with partial bytes.
+ if (m_body)
+ m_body->set_sniff_bytes_failed();
return;
+ }
// 1. If one or more bytes have been transmitted from response’s message body, then:
auto bytes = data.bytes();
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 88c3130f7f8..6833347c455 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -2483,6 +2483,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
fetch_timing_info->update_final_timings(timing_info, cross_origin_isolated_capability);
fetched_data_receiver->handle_network_data(realm, Requests::ResponseData::from_bytes({}), FetchedDataReceiver::NetworkState::Complete);
} else {
+ fetched_data_receiver->handle_network_data(realm, Requests::ResponseData::from_bytes({}), FetchedDataReceiver::NetworkState::Error);
+
// 16.1.2.2. Otherwise, if stream is readable, error stream with a TypeError.
auto error = Utf16String::formatted("Load failed: {}", error_message.value_or("Unknown error"sv));
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
index 0fab37e5486..0425b2b47cd 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
@@ -60,7 +60,7 @@ void Body::visit_edges(Cell::Visitor& visitor)
void Body::append_sniff_bytes(ReadonlyBytes bytes)
{
- if (m_sniff_bytes_complete)
+ if (m_sniff_outcome.has_value())
return;
size_t space_remaining = MAX_SNIFF_BYTES - m_sniff_bytes.size();
@@ -78,36 +78,47 @@ void Body::append_sniff_bytes(ReadonlyBytes bytes)
void Body::set_sniff_bytes_complete()
{
- if (m_sniff_bytes_complete)
+ if (m_sniff_outcome.has_value())
return;
- m_sniff_bytes_complete = true;
+ m_sniff_outcome = SniffOutcome::Complete;
if (m_sniff_bytes_callback) {
auto callback = exchange(m_sniff_bytes_callback, nullptr);
- callback->function()(m_sniff_bytes);
+ callback->function()({ m_sniff_bytes, SniffOutcome::Complete });
}
}
-Optional<ReadonlyBytes> Body::sniff_bytes_if_available() const
+void Body::set_sniff_bytes_failed()
+{
+ if (m_sniff_outcome.has_value())
+ return;
+ m_sniff_outcome = SniffOutcome::Failed;
+ if (m_sniff_bytes_callback) {
+ auto callback = exchange(m_sniff_bytes_callback, nullptr);
+ callback->function()({ m_sniff_bytes, SniffOutcome::Failed });
+ }
+}
+
+Optional<Body::SniffBytes> Body::sniff_bytes_if_available() const
{
// Non-streaming body: source has bytes
if (m_source.has<ByteBuffer>()) {
auto const& buffer = m_source.get<ByteBuffer>();
- return buffer.bytes().slice(0, min(buffer.size(), MAX_SNIFF_BYTES));
+ return SniffBytes { buffer.bytes().slice(0, min(buffer.size(), MAX_SNIFF_BYTES)) };
}
if (m_source.has<Core::ImmutableBytes>()) {
auto bytes = m_source.get<Core::ImmutableBytes>().bytes();
- return bytes.slice(0, min(bytes.size(), MAX_SNIFF_BYTES));
+ return SniffBytes { bytes.slice(0, min(bytes.size(), MAX_SNIFF_BYTES)) };
}
if (m_source.has<GC::Ref<FileAPI::Blob>>()) {
auto raw = m_source.get<GC::Ref<FileAPI::Blob>>()->raw_bytes();
- return raw.slice(0, min(raw.size(), MAX_SNIFF_BYTES));
+ return SniffBytes { raw.slice(0, min(raw.size(), MAX_SNIFF_BYTES)) };
}
// Streaming body: bytes captured during fetch
- if (m_sniff_bytes_complete)
- return m_sniff_bytes;
+ if (m_sniff_outcome.has_value())
+ return SniffBytes { m_sniff_bytes, *m_sniff_outcome };
// Still waiting for bytes
return {};
@@ -115,8 +126,8 @@ Optional<ReadonlyBytes> Body::sniff_bytes_if_available() const
void Body::wait_for_sniff_bytes(SniffBytesCallback on_ready)
{
- if (auto bytes = sniff_bytes_if_available(); bytes.has_value()) {
- on_ready->function()(bytes.value());
+ if (auto sniff_bytes = sniff_bytes_if_available(); sniff_bytes.has_value()) {
+ on_ready->function()(sniff_bytes.value());
return;
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
index bd0b7f2a801..e02ca39d2e9 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
@@ -57,13 +57,23 @@ public:
// "until [...] 1445 or more bytes have been read" or end of resource is reached.
// For non-streaming bodies (ByteBuffer/Blob source), bytes are available immediately.
// For streaming bodies, bytes are captured during fetch and delivered via callback.
- using SniffBytesCallback = GC::Ref<GC::Function<void(ReadonlyBytes)>>;
- Optional<ReadonlyBytes> sniff_bytes_if_available() const;
+ enum class SniffOutcome : u8 {
+ Complete,
+ Failed,
+ };
+ struct SniffBytes {
+ ReadonlyBytes bytes;
+ SniffOutcome outcome { SniffOutcome::Complete };
+ };
+ using SniffBytesCallback = GC::Ref<GC::Function<void(SniffBytes)>>;
+ Optional<SniffBytes> sniff_bytes_if_available() const;
void wait_for_sniff_bytes(SniffBytesCallback on_ready);
- // Called by FetchedDataReceiver to provide sniff bytes during streaming fetch.
+ // Provides sniff bytes during a streaming fetch. An ending wakes a pending waiter once: Complete delivers the
+ // captured resource header, and Failed reports a response that died mid-body, whose partial bytes are not sniffable.
void append_sniff_bytes(ReadonlyBytes bytes);
void set_sniff_bytes_complete();
+ void set_sniff_bytes_failed();
[[nodiscard]] GC::Ref<Body> clone(JS::Realm&);
@@ -93,8 +103,8 @@ private:
// https://mimesniff.spec.whatwg.org/#reading-the-resource-header
// Non-standard: Captured "resource header" bytes for MIME type sniffing.
ByteBuffer m_sniff_bytes;
- bool m_sniff_bytes_complete { false };
- GC::Ptr<GC::Function<void(ReadonlyBytes)>> m_sniff_bytes_callback;
+ Optional<SniffOutcome> m_sniff_outcome;
+ GC::Ptr<GC::Function<void(SniffBytes)>> m_sniff_bytes_callback;
};
// https://fetch.spec.whatwg.org/#body-with-type
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 38034ee2be8..b78135d9898 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -3143,18 +3143,21 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
// Get sniff bytes for MIME type detection. For streaming responses where bytes
// haven't arrived yet, we must wait asynchronously.
- auto sniff_bytes = body ? body->sniff_bytes_if_available() : Optional<ReadonlyBytes> { ReadonlyBytes {} };
+ auto sniff_bytes = body ? body->sniff_bytes_if_available() : Optional<Fetch::Infrastructure::Body::SniffBytes> { Fetch::Infrastructure::Body::SniffBytes {} };
if (!sniff_bytes.has_value()) {
// Async path: bytes not yet available, wait for them
nav_params->response->resume_body_delivery_up_to(Fetch::Infrastructure::MAX_SNIFF_BYTES);
body->wait_for_sniff_bytes(GC::create_function(heap(),
- [output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url](ReadonlyBytes sniff_bytes) {
+ [output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url](Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {
// AD-HOC: The document may have been destroyed between when the fetch started and when the
- // bytes arrived.
- if (nav_params->navigable->active_browsing_context()) {
- load_document_or_handle_download(nav_params, sniff_bytes, url, source_allows_downloading, source_interface_origin, *output);
+ // bytes arrived. A response that failed mid-sniff must not be loaded as a document
+ // off its partial bytes either.
+ if (nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {
+ load_document_or_handle_download(nav_params, sniff_bytes.bytes, url, source_allows_downloading, source_interface_origin, *output);
} else {
stop_or_resume_response_body_delivery(navigation_params);
+ if (sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Failed)
+ output->save_extra_document_state = false;
}
output->navigation_params = navigation_params;
report_a_document_with_an_origin_of_its_own(*nav_params->navigable, output);
@@ -3165,7 +3168,12 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
}
// Sync path: bytes available immediately
- load_document_or_handle_download(nav_params, sniff_bytes.value(), url, source_allows_downloading, source_interface_origin, *output);
+ if (sniff_bytes->outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {
+ load_document_or_handle_download(nav_params, sniff_bytes->bytes, url, source_allows_downloading, source_interface_origin, *output);
+ } else {
+ stop_or_resume_response_body_delivery(navigation_params);
+ output->save_extra_document_state = false;
+ }
} else {
stop_or_resume_response_body_delivery(navigation_params);
}
diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
index 3e4fa896512..c35083201db 100644
--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
@@ -304,7 +304,7 @@ static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::R
return;
}
- body->set_sniff_bytes_complete();
+ body->set_sniff_bytes_failed();
if (stream->is_readable())
stream->error(JS::TypeError::create(realm, "Transferred navigation response failed"_utf16));
});
diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
index f9c813381a7..3621ba06230 100644
--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
@@ -62,8 +62,9 @@ void IncrementalDocumentParser::start()
// FIXME: The spec allows starting the parse after 500 ms or 1024 bytes, whichever comes first.
// We only honor the byte threshold.
auto parser = GC::Ref { *this };
- m_body->wait_for_sniff_bytes(GC::create_function(GC::Heap::the(), [parser](ReadonlyBytes sniff_bytes) {
- parser->initialize_parser(sniff_bytes);
+ m_body->wait_for_sniff_bytes(GC::create_function(GC::Heap::the(), [parser](Web::Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {
+ // A failed response initializes the parser too.
+ parser->initialize_parser(sniff_bytes.bytes);
}));
}
diff --git a/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt b/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt
new file mode 100644
index 00000000000..f2e51b012d1
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt
@@ -0,0 +1,2 @@
+iframe produced a document from the partial body: false
+iframe stayed on its initial document: true
diff --git a/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html b/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html
new file mode 100644
index 00000000000..b46ea7c90c6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html
@@ -0,0 +1,108 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A navigation response that dies mid-body must not satisfy the MIME-sniff wait with its
+ // partial bytes: no document may be created from the truncated body, and the navigation
+ // settles without one.
+
+ // Runs on a hostname of its own, in a process apart from the test page.
+ async function checkFailedNavigationSettles(urls) {
+ const output = [];
+ const println = line => output.push(line);
+
+ const countBodyReceivers = () =>
+ Object.values(JSON.parse(internals.dumpGCGraph())).filter(cell => cell.class_name === "FetchedDataReceiver")
+ .length;
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+
+ // A stale pointer on the stack can keep a cell alive through one conservative collection.
+ const waitForRelease = async initial => {
+ const deadline = performance.now() + 10000;
+ for (;;) {
+ await internals.gcAsync();
+ if (countBodyReceivers() === initial || performance.now() > deadline)
+ return;
+ await sleep(10);
+ }
+ };
+
+ await internals.gcAsync();
+ const initial = countBodyReceivers();
+
+ const frame = document.createElement("iframe");
+ let loaded = false;
+ frame.addEventListener("load", () => (loaded = true));
+ frame.src = urls.failing;
+ document.body.append(frame);
+
+ // The body is held after its first chunk, and ends short once it is let go.
+ const arrivalDeadline = performance.now() + 10000;
+ while (countBodyReceivers() === initial) {
+ if (performance.now() > arrivalDeadline) {
+ println("body of the failed navigation never arrived");
+ return output;
+ }
+ await sleep(10);
+ }
+ await fetch(urls.unblock);
+
+ // The navigation has settled once its body is released.
+ await waitForRelease(initial);
+ println(`iframe produced a document from the partial body: ${loaded}`);
+ const stayed = frame.contentDocument !== null && frame.contentDocument.querySelector("#partial") === null;
+ println(`iframe stayed on its initial document: ${stayed}`);
+ return output;
+ }
+
+ promiseTest(async () => {
+ const hostname = uniqueLocalhostHostname("mid-body-navigation-failure");
+ const server = httpTestServer();
+
+ const token = `mid-body-failure-${crypto.randomUUID()}`;
+ const failing = new URL(await server.createEcho("GET", `/mid-body-navigation-failure-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: {
+ "Cache-Control": "no-store",
+ "Content-Length": "100000",
+ "Content-Type": "text/html",
+ },
+ body: "<!DOCTYPE html><span id='partial'>partial</span>" + "x".repeat(967),
+ }));
+ failing.hostname = hostname;
+ failing.search = `?chunks=512,503&chunk_unblock_tokens=${token}`;
+ const unblock = new URL(`/unblock/${token}`, failing);
+
+ const urls = { failing: failing.href, unblock: unblock.href };
+ const checker = new URL(await server.createEcho("GET", `/mid-body-failure-checker-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><body><script>
+ (${checkFailedNavigationSettles.toString()})(${JSON.stringify(urls)}).then(
+ output => parent.postMessage({ output }, "*"),
+ error => parent.postMessage({ error: String(error) }, "*"));
+ <\/script>`,
+ }));
+ checker.hostname = hostname;
+
+ const frame = document.createElement("iframe");
+ const result = new Promise(resolve => {
+ window.addEventListener("message", function receive(event) {
+ if (event.source !== frame.contentWindow)
+ 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>