Skip to content

Truly independent web browser

LibWebView: Add web compatibility reports

Jelle Raaijmakersaf9d94ab4e8e
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 121d45b3d5d..3633093ce91 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -69,6 +69,7 @@ set(SOURCES
Utilities.cpp
VideoDecoderServerControlClient.cpp
ViewImplementation.cpp
+ WebCompatReport.cpp
WebContentClient.cpp
WebContentPage.cpp
WebContentTestClient.cpp
diff --git a/Libraries/LibWebView/ReportSubmission.cpp b/Libraries/LibWebView/ReportSubmission.cpp
index a3778d8643c..78c6a4a6850 100644
--- a/Libraries/LibWebView/ReportSubmission.cpp
+++ b/Libraries/LibWebView/ReportSubmission.cpp
@@ -169,6 +169,19 @@ static Optional<int> retry_after_ms(HTTP::HeaderList const& headers)
// It can outlive whatever started it.
ReportSubmission::ReportSubmission() = default;
+// A submission of a payload prepared in advance sends that payload, so a retry of it keeps its submission ID.
+NonnullRefPtr<ReportSubmission> ReportSubmission::create(Payload payload)
+{
+ auto submission = adopt_ref(*new ReportSubmission);
+ submission->m_payload = move(payload);
+ return submission;
+}
+
+ErrorOr<ReportSubmission::Payload, String> ReportSubmission::prepare()
+{
+ VERIFY_NOT_REACHED();
+}
+
ReportSubmission::~ReportSubmission()
{
m_proof_cancelled.store(true);
diff --git a/Libraries/LibWebView/ReportSubmission.h b/Libraries/LibWebView/ReportSubmission.h
index 308d65dfac6..8dc34b6f2cf 100644
--- a/Libraries/LibWebView/ReportSubmission.h
+++ b/Libraries/LibWebView/ReportSubmission.h
@@ -74,6 +74,7 @@ public:
};
static ByteString build_manifest(Contents const&, ReadonlySpan<Attachment>);
+ static NonnullRefPtr<ReportSubmission> create(Payload);
virtual ~ReportSubmission();
@@ -89,7 +90,7 @@ public:
protected:
ReportSubmission();
- virtual ErrorOr<Payload, String> prepare() = 0;
+ virtual ErrorOr<Payload, String> prepare();
virtual void did_send() { }
private:
diff --git a/Libraries/LibWebView/WebCompatReport.cpp b/Libraries/LibWebView/WebCompatReport.cpp
new file mode 100644
index 00000000000..af54326a486
--- /dev/null
+++ b/Libraries/LibWebView/WebCompatReport.cpp
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Math.h>
+#include <AK/StringBuilder.h>
+#include <AK/WeakPtr.h>
+#include <LibCore/ImmutableBytes.h>
+#include <LibCore/Promise.h>
+#include <LibWebCommon/Loader/UserAgent.h>
+#include <LibWebCommon/WebView/PageInfo.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/BuildInformation.h>
+#include <LibWebView/ViewImplementation.h>
+#include <LibWebView/WebCompatReport.h>
+
+namespace WebView {
+
+static constexpr auto diagnostics_reference = "diagnostics"sv;
+static constexpr auto diagnostics_name = "webcompat-diagnostics.txt"sv;
+static constexpr auto screenshot_reference = "screenshot"sv;
+static constexpr auto screenshot_name = "screenshot.png"sv;
+
+static constexpr auto browser_version = BROWSER_VERSION ""sv;
+static constexpr auto platform = OS_STRING ""sv;
+static constexpr auto architecture = CPU_STRING ""sv;
+
+#ifdef NDEBUG
+static constexpr auto build_configuration = "release"sv;
+#else
+static constexpr auto build_configuration = "debug"sv;
+#endif
+
+static String to_string(StringView text)
+{
+ return String::from_utf8_with_replacement_character(text);
+}
+
+static String format_viewport_size(Gfx::IntSize size)
+{
+ return MUST(String::formatted("{}x{}", size.width(), size.height()));
+}
+
+static String format_zoom_level(double zoom_level)
+{
+ return MUST(String::formatted("{}%", round_to<int>(zoom_level * 100)));
+}
+
+WebCompatReport::Page WebCompatReport::describe_page(ViewImplementation const& view)
+{
+ // The viewport in CSS pixels, as the page sees it.
+ auto device_size = view.viewport_size();
+ auto scale = view.device_pixel_ratio() * view.zoom_level();
+ Gfx::IntSize viewport_size {
+ round_to<int>(static_cast<double>(device_size.width().value()) / scale),
+ round_to<int>(static_cast<double>(device_size.height().value()) / scale),
+ };
+
+ return {
+ .url = view.url(),
+ .user_agent = Application::the().user_agent_string(),
+ .viewport_size = viewport_size,
+ .device_pixel_ratio = view.device_pixel_ratio(),
+ .zoom_level = view.zoom_level(),
+ };
+}
+
+// The dumps of how the page was laid out and painted, taken together so they describe the same moment. Each one starts
+// with what it is: the layout tree with its viewport, the stacking context tree with "SC for", and the display list with
+// its visual context tree.
+NonnullRefPtr<Core::Promise<String>> WebCompatReport::request_page_dumps(ViewImplementation& view)
+{
+ return view.request_internal_page_info(PageInfoType::LayoutTree | PageInfoType::StackingContextTree | PageInfoType::DisplayList);
+}
+
+Optional<String> WebCompatReport::validate(StringView description)
+{
+ if (description.trim_whitespace().is_empty())
+ return "Describe what is wrong with this website."_string;
+ if (description.length() > maximum_description_bytes)
+ return "This description is too long to include in a report."_string;
+ return {};
+}
+
+WebCompatReport::WebCompatReport(Page page)
+ : m_page(move(page))
+{
+}
+
+WebCompatReport::~WebCompatReport() = default;
+
+Vector<ReportDetail> WebCompatReport::details() const
+{
+ Vector<ReportDetail> details;
+ details.append({ "Website"_string, m_page.url.serialize(), false });
+ details.append({ "User agent"_string, m_page.user_agent, true });
+ details.append({ "Viewport size"_string, format_viewport_size(m_page.viewport_size), false });
+ details.append({ "Device pixel ratio"_string, MUST(String::formatted("{}", m_page.device_pixel_ratio)), false });
+ details.append({ "Zoom level"_string, format_zoom_level(m_page.zoom_level), false });
+ details.append({ "Ladybird version"_string, to_string(browser_version), true });
+ details.append({ "Platform"_string, to_string(platform), false });
+ details.append({ "Architecture"_string, to_string(architecture), false });
+ details.append({ "Git commit"_string, to_string(LADYBIRD_COMMIT), true });
+ return details;
+}
+
+// Dumps that exceed the limit are cut at a character boundary, and say so.
+void WebCompatReport::set_page_dumps(String dumps)
+{
+ auto bytes = dumps.bytes();
+ if (bytes.size() <= maximum_page_dumps_bytes) {
+ m_page_dumps = move(dumps);
+ return;
+ }
+
+ auto length = maximum_page_dumps_bytes;
+ while (length > 0 && (bytes[length] & 0xC0) == 0x80)
+ --length;
+ m_page_dumps = MUST(String::formatted("{}\n(Truncated)\n", StringView { bytes.slice(0, length) }));
+}
+
+ByteString WebCompatReport::diagnostics(IncludePageDumps include_page_dumps) const
+{
+ StringBuilder builder;
+ builder.append("Ladybird web compatibility report, format 1\n"sv);
+ builder.appendff("Version: {}\nPlatform: {}\nArchitecture: {}\n", browser_version, platform, architecture);
+ builder.appendff("Build configuration: {}\n", build_configuration);
+ append_build_information_for_process(builder, ProcessType::Browser);
+ builder.appendff("URL: {}\n", m_page.url.serialize());
+ builder.appendff("User agent: {}\n", m_page.user_agent);
+ builder.appendff("Viewport size: {}\n", format_viewport_size(m_page.viewport_size));
+ builder.appendff("Device pixel ratio: {}\n", m_page.device_pixel_ratio);
+ builder.appendff("Zoom level: {}\n", format_zoom_level(m_page.zoom_level));
+
+ if (include_page_dumps == IncludePageDumps::Yes && m_page_dumps.has_value())
+ builder.appendff("\n{}", *m_page_dumps);
+
+ return builder.to_byte_string();
+}
+
+Optional<String> WebCompatReport::send(String const& description, Optional<ByteBuffer> screenshot_png,
+ IncludePageDumps include_page_dumps)
+{
+ VERIFY(!m_submission);
+
+ if (auto error = validate(description); error.has_value())
+ return error;
+ if (screenshot_png.has_value() && screenshot_png->size() > maximum_screenshot_bytes)
+ return "This screenshot is too large to include in a report."_string;
+
+ auto diagnostics_text = diagnostics(include_page_dumps);
+ Vector<ReportSubmission::Attachment> attachments;
+ attachments.append({
+ .id = diagnostics_reference,
+ .name = diagnostics_name,
+ .media_type = "text/plain"sv,
+ .content = MUST(Core::ImmutableBytes::copy(diagnostics_text.bytes())),
+ });
+ if (screenshot_png.has_value()) {
+ attachments.append({
+ .id = screenshot_reference,
+ .name = screenshot_name,
+ .media_type = "image/png"sv,
+ .content = Core::ImmutableBytes::adopt(screenshot_png.release_value()),
+ });
+ }
+
+ auto url = m_page.url.serialize();
+ auto viewport_size = format_viewport_size(m_page.viewport_size);
+
+ ReportSubmission::Contents contents;
+ contents.kind = "web_compat"sv;
+ contents.client_version = browser_version;
+ contents.build = build_configuration;
+ contents.add_text("description"sv, "multiline"sv, description);
+ contents.add_text("url"sv, "text"sv, url);
+ contents.add_text("user_agent"sv, "text"sv, m_page.user_agent);
+ contents.add_text("viewport_size"sv, "text"sv, viewport_size);
+ contents.add("device_pixel_ratio"sv, "number"sv, m_page.device_pixel_ratio);
+ contents.add("zoom_level"sv, "number"sv, m_page.zoom_level);
+ contents.add_text("platform"sv, "text"sv, platform);
+ contents.add_text("architecture"sv, "text"sv, architecture);
+ contents.add_text("git_commit"sv, "text"sv, LADYBIRD_COMMIT);
+ contents.add_text("build_configuration"sv, "text"sv, build_configuration);
+
+ auto manifest = ReportSubmission::build_manifest(contents, attachments);
+ m_payload = ReportSubmission::Payload { move(manifest), move(attachments) };
+ start_submission();
+ return {};
+}
+
+void WebCompatReport::retry()
+{
+ VERIFY(m_payload.has_value());
+ VERIFY(!m_submission);
+ start_submission();
+}
+
+void WebCompatReport::cancel_sending()
+{
+ if (auto submission = move(m_submission))
+ submission->cancel();
+}
+
+// A report on its way keeps being sent if this report is destroyed, which then only stops hearing about it.
+void WebCompatReport::start_submission()
+{
+ auto submission = ReportSubmission::create(*m_payload);
+
+ submission->on_progress = [weak_this = make_weak_ptr()](auto stage) {
+ if (auto* self = weak_this.ptr(); self && self->on_progress)
+ self->on_progress(stage);
+ };
+ submission->on_retry = [weak_this = make_weak_ptr()](String reason, u32 retry_number, u32 maximum_retries, u32 delay_seconds) {
+ if (auto* self = weak_this.ptr(); self && self->on_retry)
+ self->on_retry(move(reason), retry_number, maximum_retries, delay_seconds);
+ };
+ submission->on_sent = [weak_this = make_weak_ptr()] {
+ if (auto* self = weak_this.ptr()) {
+ self->m_submission = nullptr;
+ if (self->on_sent)
+ self->on_sent();
+ }
+ };
+ submission->on_failed = [weak_this = make_weak_ptr()](auto failure, String reason) {
+ if (auto* self = weak_this.ptr()) {
+ self->m_submission = nullptr;
+ if (self->on_failed)
+ self->on_failed(failure, move(reason));
+ }
+ };
+
+ m_submission = submission;
+ submission->start();
+}
+
+}
diff --git a/Libraries/LibWebView/WebCompatReport.h b/Libraries/LibWebView/WebCompatReport.h
new file mode 100644
index 00000000000..5153481d9ce
--- /dev/null
+++ b/Libraries/LibWebView/WebCompatReport.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteBuffer.h>
+#include <AK/ByteString.h>
+#include <AK/Function.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/RefPtr.h>
+#include <AK/String.h>
+#include <AK/Vector.h>
+#include <AK/Weakable.h>
+#include <LibCore/Forward.h>
+#include <LibGfx/Size.h>
+#include <LibURL/URL.h>
+#include <LibWebView/Forward.h>
+#include <LibWebView/ReportDetail.h>
+#include <LibWebView/ReportSubmission.h>
+
+namespace WebView {
+
+class WEBVIEW_API WebCompatReport : public Weakable<WebCompatReport> {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ static constexpr size_t maximum_description_bytes = 16384;
+ static constexpr size_t maximum_page_dumps_bytes = 8 * MiB;
+ static constexpr size_t maximum_screenshot_bytes = 8 * MiB;
+ static constexpr size_t maximum_screenshot_pixels = 8'000'000;
+
+ struct Page {
+ URL::URL url;
+ String user_agent;
+ Gfx::IntSize viewport_size;
+ double device_pixel_ratio { 1 };
+ double zoom_level { 1 };
+ };
+
+ enum class IncludePageDumps : bool {
+ No,
+ Yes,
+ };
+
+ static Page describe_page(ViewImplementation const&);
+ static NonnullRefPtr<Core::Promise<String>> request_page_dumps(ViewImplementation&);
+ static Optional<String> validate(StringView description);
+
+ explicit WebCompatReport(Page);
+ ~WebCompatReport();
+
+ Page const& page() const { return m_page; }
+ Vector<ReportDetail> details() const;
+
+ void set_page_dumps(String);
+ bool has_page_dumps() const { return m_page_dumps.has_value(); }
+
+ ByteString diagnostics(IncludePageDumps) const;
+
+ Optional<String> send(String const& description, Optional<ByteBuffer> screenshot_png, IncludePageDumps);
+ void retry();
+ bool is_sending() const { return m_submission; }
+ void cancel_sending();
+
+ Function<void(ReportSubmission::Stage)> on_progress;
+ Function<void(String reason, u32 retry_number, u32 maximum_retries, u32 delay_seconds)> on_retry;
+ Function<void()> on_sent;
+ Function<void(ReportSubmission::Failure, String reason)> on_failed;
+
+private:
+ void start_submission();
+
+ Page m_page;
+ Optional<String> m_page_dumps;
+ Optional<ReportSubmission::Payload> m_payload;
+ RefPtr<ReportSubmission> m_submission;
+};
+
+}
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index ca8959399e5..64fd527dcff 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -245,6 +245,13 @@ if (NOT WIN32)
target_compile_definitions(TestCrashReportSubmission PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")
endif()
+ add_executable(TestWebCompatReport TestWebCompatReport.cpp)
+ add_dependencies(TestWebCompatReport ${ladybird_helper_processes})
+ target_link_libraries(TestWebCompatReport PRIVATE AK LibCore LibCrypto LibFileSystem LibIPC LibMain LibURL LibWebView)
+ if (APPLE)
+ target_compile_definitions(TestWebCompatReport PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")
+ endif()
+
add_executable(TestRequestServerClientSessions TestRequestServerClientSessions.cpp)
add_dependencies(TestRequestServerClientSessions ${ladybird_helper_processes})
target_link_libraries(TestRequestServerClientSessions PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)
@@ -430,6 +437,8 @@ if (BUILD_TESTING AND NOT WIN32)
set_tests_properties(TestImageDecoderIsolation PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
add_test(NAME TestCrashReportSubmission COMMAND $<TARGET_FILE:TestCrashReportSubmission>)
set_tests_properties(TestCrashReportSubmission PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
+ add_test(NAME TestWebCompatReport COMMAND $<TARGET_FILE:TestWebCompatReport>)
+ set_tests_properties(TestWebCompatReport PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
add_test(NAME TestRequestServerClientSessions COMMAND $<TARGET_FILE:TestRequestServerClientSessions>)
set_tests_properties(TestRequestServerClientSessions PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
add_test(NAME TestTabPerformanceMonitor COMMAND $<TARGET_FILE:TestTabPerformanceMonitor>)
diff --git a/Tests/LibWebView/ReportServer.h b/Tests/LibWebView/ReportServer.h
new file mode 100644
index 00000000000..dde60e8ecef
--- /dev/null
+++ b/Tests/LibWebView/ReportServer.h
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteBuffer.h>
+#include <AK/ByteString.h>
+#include <AK/HashMap.h>
+#include <AK/Hex.h>
+#include <AK/JsonArray.h>
+#include <AK/JsonObject.h>
+#include <AK/JsonValue.h>
+#include <AK/NonnullOwnPtr.h>
+#include <AK/Vector.h>
+#include <LibCore/Socket.h>
+#include <LibCore/TCPServer.h>
+#include <LibCrypto/Hash/SHA2.h>
+#include <LibWebView/Application.h>
+
+namespace ReportServerTest {
+
+class TestApplication : public WebView::Application {
+ WEB_VIEW_APPLICATION(TestApplication)
+
+public:
+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)
+ : WebView::Application(move(ladybird_binary_path))
+ {
+ }
+
+ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions&) override
+ {
+ browser_options.headless_mode = WebView::HeadlessMode::Test;
+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;
+ }
+
+ virtual bool should_coordinate_browser_process() const override { return false; }
+};
+
+struct ReceivedRequest {
+ ByteString path;
+ HashMap<ByteString, ByteString> headers;
+ ByteString body;
+};
+
+struct Response {
+ u32 status { 200 };
+ ByteString body;
+ ByteString extra_headers;
+};
+
+inline Response challenge(StringView token)
+{
+ return { 200, ByteString::formatted(R"({{"algorithm":"sha256-seed-nonce-le-v1","token":"{}","expected_work":1}})", token), {} };
+}
+
+// A report server on the loopback interface that answers each request with the next of the responses it was given. A
+// request that comes in once they have run out is left waiting.
+class ReportServer {
+public:
+ ReportServer()
+ {
+ m_server = MUST(Core::TCPServer::try_create());
+ MUST(m_server->listen(IPv4Address { 127, 0, 0, 1 }, 0));
+ m_server->on_ready_to_accept = [this] {
+ auto socket = MUST(m_server->accept());
+ MUST(socket->set_blocking(false));
+ m_connections.append(make<Connection>(move(socket)));
+ auto& connection = *m_connections.last();
+ connection.socket->on_ready_to_read = [this, &connection] { read_from(connection); };
+ };
+ }
+
+ ByteString endpoint() const { return ByteString::formatted("http://127.0.0.1:{}", *m_server->local_port()); }
+
+ void respond_with(Response response) { m_responses.append(move(response)); }
+ bool has_answered_everything() const { return m_responses.is_empty(); }
+
+ Vector<ReceivedRequest> requests;
+
+private:
+ struct Connection {
+ AK_ALLOC_WITH_KMALLOC;
+
+ NonnullOwnPtr<Core::TCPSocket> socket;
+ ByteBuffer data {};
+ bool sent_continue { false };
+ };
+
+ void read_from(Connection& connection)
+ {
+ auto buffer = MUST(ByteBuffer::create_uninitialized(64 * KiB));
+ auto received = connection.socket->read_some(buffer);
+ if (received.is_error() || received.value().is_empty()) {
+ connection.socket->on_ready_to_read = nullptr;
+ return;
+ }
+ connection.data.append(received.value());
+
+ auto data = StringView { connection.data.bytes() };
+ auto header_end = data.find("\r\n\r\n"sv);
+ if (!header_end.has_value())
+ return;
+
+ ReceivedRequest request;
+ auto lines = data.substring_view(0, *header_end).split_view("\r\n"sv);
+ request.path = lines[0].split_view(' ')[1];
+ for (size_t i = 1; i < lines.size(); ++i) {
+ auto separator = lines[i].find(':').value();
+ request.headers.set(ByteString { lines[i].substring_view(0, separator) }.to_lowercase(),
+ lines[i].substring_view(separator + 1).trim_whitespace());
+ }
+
+ auto content_length = request.headers.get("content-length"sv).value_or("0"sv).to_number<size_t>().value();
+ auto body = data.substring_view(*header_end + 4);
+ if (body.length() < content_length) {
+ if (request.headers.get("expect"sv) == "100-continue"sv && !connection.sent_continue) {
+ connection.sent_continue = true;
+ MUST(connection.socket->write_until_depleted("HTTP/1.1 100 Continue\r\n\r\n"sv.bytes()));
+ }
+ return;
+ }
+ request.body = body.substring_view(0, content_length);
+ requests.append(move(request));
+
+ connection.socket->on_ready_to_read = nullptr;
+ if (m_responses.is_empty())
+ return;
+ auto response = m_responses.take_first();
+ MUST(connection.socket->set_blocking(true));
+ auto response_text = ByteString::formatted(
+ "HTTP/1.1 {} Status\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{}\r\n{}",
+ response.status, response.body.length(), response.extra_headers, response.body);
+ MUST(connection.socket->write_until_depleted(response_text.bytes()));
+ connection.socket->close();
+ }
+
+ RefPtr<Core::TCPServer> m_server;
+ Vector<NonnullOwnPtr<Connection>> m_connections;
+ Vector<Response> m_responses;
+};
+
+inline ByteString sha256_hex(StringView text)
+{
+ return encode_hex(Crypto::Hash::SHA256::hash(text.bytes()).bytes());
+}
+
+// The content of the multipart part with the given name.
+inline StringView multipart_part(StringView body, StringView name)
+{
+ auto disposition = ByteString::formatted("Content-Disposition: form-data; name=\"{}\"", name);
+ auto start = body.find(disposition).value();
+ auto content_start = body.find("\r\n\r\n"sv, start).value() + 4;
+ auto content_end = body.find("\r\n--"sv, content_start).value();
+ return body.substring_view(content_start, content_end - content_start);
+}
+
+inline Optional<JsonValue> manifest_field(JsonObject const& manifest, StringView key)
+{
+ Optional<JsonValue> value;
+ manifest.get_array("fields"sv)->for_each([&](JsonValue const& field) {
+ if (field.as_object().get_string("key"sv) == key)
+ value = field.as_object().get_object("value"sv)->get("value"sv).value();
+ });
+ return value;
+}
+
+}
diff --git a/Tests/LibWebView/TestCrashReportSubmission.cpp b/Tests/LibWebView/TestCrashReportSubmission.cpp
index 86c5ec5d2c9..88aab97a815 100644
--- a/Tests/LibWebView/TestCrashReportSubmission.cpp
+++ b/Tests/LibWebView/TestCrashReportSubmission.cpp
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Hex.h>
+#include "ReportServer.h"
#include <AK/JsonArray.h>
#include <AK/JsonObject.h>
#include <AK/JsonValue.h>
@@ -15,34 +15,14 @@
#include <LibCore/Environment.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
-#include <LibCore/Socket.h>
#include <LibCore/StandardPaths.h>
-#include <LibCore/TCPServer.h>
-#include <LibCrypto/Hash/SHA2.h>
#include <LibFileSystem/FileSystem.h>
#include <LibMain/Main.h>
-#include <LibWebView/Application.h>
#include <LibWebView/CrashReportReview.h>
-namespace {
-
-class TestApplication : public WebView::Application {
- WEB_VIEW_APPLICATION(TestApplication)
-
-public:
- explicit TestApplication(Optional<ByteString> ladybird_binary_path)
- : WebView::Application(move(ladybird_binary_path))
- {
- }
-
- virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions&) override
- {
- browser_options.headless_mode = WebView::HeadlessMode::Test;
- browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;
- }
+using namespace ReportServerTest;
- virtual bool should_coordinate_browser_process() const override { return false; }
-};
+namespace {
constexpr auto report_text = "Ladybird crash report, format 1\n"
"Process: WebContent\n"
@@ -54,131 +34,6 @@ constexpr auto report_text = "Ladybird crash report, format 1\n"
"Native stack (binary build ID, object address):\n"
"#0 abcdef 0x1234 Web::Page::crash()\n"sv;
-struct ReceivedRequest {
- ByteString path;
- HashMap<ByteString, ByteString> headers;
- ByteString body;
-};
-
-struct Response {
- u32 status { 200 };
- ByteString body;
- ByteString extra_headers;
-};
-
-Response challenge(StringView token)
-{
- return { 200, ByteString::formatted(R"({{"algorithm":"sha256-seed-nonce-le-v1","token":"{}","expected_work":1}})", token), {} };
-}
-
-// A report server on the loopback interface that answers each request with the next of the responses it was given.
-class ReportServer {
-public:
- ReportServer()
- {
- m_server = MUST(Core::TCPServer::try_create());
- MUST(m_server->listen(IPv4Address { 127, 0, 0, 1 }, 0));
- m_server->on_ready_to_accept = [this] {
- auto socket = MUST(m_server->accept());
- MUST(socket->set_blocking(false));
- m_connections.append(make<Connection>(move(socket)));
- auto& connection = *m_connections.last();
- connection.socket->on_ready_to_read = [this, &connection] { read_from(connection); };
- };
- }
-
- ByteString endpoint() const { return ByteString::formatted("http://127.0.0.1:{}", *m_server->local_port()); }
-
- void respond_with(Response response) { m_responses.append(move(response)); }
- bool has_answered_everything() const { return m_responses.is_empty(); }
-
- Vector<ReceivedRequest> requests;
-
-private:
- struct Connection {
- AK_ALLOC_WITH_KMALLOC;
-
- NonnullOwnPtr<Core::TCPSocket> socket;
- ByteBuffer data {};
- bool sent_continue { false };
- };
-
- void read_from(Connection& connection)
- {
- auto buffer = MUST(ByteBuffer::create_uninitialized(64 * KiB));
- auto received = connection.socket->read_some(buffer);
- if (received.is_error() || received.value().is_empty()) {
- connection.socket->on_ready_to_read = nullptr;
- return;
- }
- connection.data.append(received.value());
-
- auto data = StringView { connection.data.bytes() };
- auto header_end = data.find("\r\n\r\n"sv);
- if (!header_end.has_value())
- return;
-
- ReceivedRequest request;
- auto lines = data.substring_view(0, *header_end).split_view("\r\n"sv);
- request.path = lines[0].split_view(' ')[1];
- for (size_t i = 1; i < lines.size(); ++i) {
- auto separator = lines[i].find(':').value();
- request.headers.set(ByteString { lines[i].substring_view(0, separator) }.to_lowercase(),
- lines[i].substring_view(separator + 1).trim_whitespace());
- }
-
- auto content_length = request.headers.get("content-length"sv).value_or("0"sv).to_number<size_t>().value();
- auto body = data.substring_view(*header_end + 4);
- if (body.length() < content_length) {
- if (request.headers.get("expect"sv) == "100-continue"sv && !connection.sent_continue) {
- connection.sent_continue = true;
- MUST(connection.socket->write_until_depleted("HTTP/1.1 100 Continue\r\n\r\n"sv.bytes()));
- }
- return;
- }
- request.body = body.substring_view(0, content_length);
- requests.append(move(request));
-
- connection.socket->on_ready_to_read = nullptr;
- auto response = m_responses.take_first();
- MUST(connection.socket->set_blocking(true));
- auto response_text = ByteString::formatted(
- "HTTP/1.1 {} Status\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{}\r\n{}",
- response.status, response.body.length(), response.extra_headers, response.body);
- MUST(connection.socket->write_until_depleted(response_text.bytes()));
- connection.socket->close();
- }
-
- RefPtr<Core::TCPServer> m_server;
- Vector<NonnullOwnPtr<Connection>> m_connections;
- Vector<Response> m_responses;
-};
-
-ByteString sha256_hex(StringView text)
-{
- return encode_hex(Crypto::Hash::SHA256::hash(text.bytes()).bytes());
-}
-
-// The content of the multipart part with the given name.
-StringView multipart_part(StringView body, StringView name)
-{
- auto disposition = ByteString::formatted("Content-Disposition: form-data; name=\"{}\"", name);
- auto start = body.find(disposition).value();
- auto content_start = body.find("\r\n\r\n"sv, start).value() + 4;
- auto content_end = body.find("\r\n--"sv, content_start).value();
- return body.substring_view(content_start, content_end - content_start);
-}
-
-Optional<JsonValue> manifest_field(JsonObject const& manifest, StringView key)
-{
- Optional<JsonValue> value;
- manifest.get_array("fields"sv)->for_each([&](JsonValue const& field) {
- if (field.as_object().get_string("key"sv) == key)
- value = field.as_object().get_object("value"sv)->get("value"sv).value();
- });
- return value;
-}
-
struct Outcome {
bool sent { false };
Optional<WebView::ReportSubmission::Failure> failure;
diff --git a/Tests/LibWebView/TestWebCompatReport.cpp b/Tests/LibWebView/TestWebCompatReport.cpp
new file mode 100644
index 00000000000..4fb4e4540ab
--- /dev/null
+++ b/Tests/LibWebView/TestWebCompatReport.cpp
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "ReportServer.h"
+#include <AK/JsonArray.h>
+#include <AK/JsonObject.h>
+#include <AK/JsonValue.h>
+#include <AK/LexicalPath.h>
+#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
+#include <LibCore/Directory.h>
+#include <LibCore/Environment.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/StandardPaths.h>
+#include <LibCore/Timer.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibMain/Main.h>
+#include <LibURL/Parser.h>
+#include <LibWebView/WebCompatReport.h>
+
+using namespace ReportServerTest;
+using WebView::ReportSubmission;
+using WebView::WebCompatReport;
+
+namespace {
+
+constexpr auto page_dumps = "Layout tree:\nViewport <#document>\n\nDisplay list:\nFillRect\n"sv;
+constexpr auto screenshot_png = "\x89PNG\r\n\x1a\nnot really a PNG"sv;
+
+struct Outcome {
+ bool sent { false };
+ Optional<ReportSubmission::Failure> failure;
+ String reason;
+
+ bool is_finished() const { return sent || failure.has_value(); }
+};
+
+void track(WebCompatReport& report, Outcome& outcome)
+{
+ outcome = {};
+ report.on_sent = [&outcome] { outcome.sent = true; };
+ report.on_failed = [&outcome](auto failure, String const& reason) {
+ outcome.failure = failure;
+ outcome.reason = reason;
+ };
+}
+
+WebCompatReport::Page test_page()
+{
+ return {
+ .url = URL::Parser::basic_parse("https://example.com/broken?query"sv).release_value(),
+ .user_agent = "Mozilla/5.0 Ladybird/1.0"_string,
+ .viewport_size = { 1280, 720 },
+ .device_pixel_ratio = 2,
+ .zoom_level = 1.1,
+ };
+}
+
+void verify_validation()
+{
+ VERIFY(WebCompatReport::validate(""sv) == "Describe what is wrong with this website."sv);
+ VERIFY(WebCompatReport::validate(" \n "sv) == "Describe what is wrong with this website."sv);
+ VERIFY(!WebCompatReport::validate("The menu does not open"sv).has_value());
+
+ auto long_description = ByteString::repeated('a', WebCompatReport::maximum_description_bytes + 1);
+ VERIFY(WebCompatReport::validate(long_description) == "This description is too long to include in a report."sv);
+
+ WebCompatReport report { test_page() };
+ VERIFY(report.send(""_string, {}, WebCompatReport::IncludePageDumps::No) == "Describe what is wrong with this website."sv);
+ VERIFY(!report.is_sending());
+}
+
+void verify_diagnostics()
+{
+ WebCompatReport report { test_page() };
+ VERIFY(!report.has_page_dumps());
+
+ auto diagnostics = report.diagnostics(WebCompatReport::IncludePageDumps::Yes);
+ VERIFY(diagnostics.starts_with("Ladybird web compatibility report, format 1\n"sv));
+ VERIFY(diagnostics.contains("\nURL: https://example.com/broken?query\n"sv));
+ VERIFY(diagnostics.contains("\nUser agent: Mozilla/5.0 Ladybird/1.0\n"sv));
+ VERIFY(diagnostics.contains("\nViewport size: 1280x720\n"sv));
+ VERIFY(diagnostics.contains("\nDevice pixel ratio: 2\n"sv));
+ VERIFY(diagnostics.contains("\nZoom level: 110%\n"sv));
+ VERIFY(diagnostics.contains("\nGit commit: "sv));
+
+ report.set_page_dumps(String::from_utf8_without_validation(page_dumps.bytes()));
+ VERIFY(report.has_page_dumps());
+ VERIFY(report.diagnostics(WebCompatReport::IncludePageDumps::Yes).ends_with(ByteString::formatted("\n\n{}", page_dumps)));
+ VERIFY(report.diagnostics(WebCompatReport::IncludePageDumps::No) == diagnostics);
+
+ // Dumps over the limit are cut where a character starts, and say so.
+ StringBuilder builder;
+ builder.append(ByteString::repeated('a', WebCompatReport::maximum_page_dumps_bytes - 1));
+ builder.append("é and more"sv);
+ report.set_page_dumps(MUST(builder.to_string()));
+ auto truncated = report.diagnostics(WebCompatReport::IncludePageDumps::Yes);
+ VERIFY(truncated.ends_with("a\n(Truncated)\n"sv));
+ VERIFY(!truncated.contains("é"sv));
+
+ auto details = report.details();
+ VERIFY(details[0].label == "Website"sv);
+ VERIFY(details[0].value == "https://example.com/broken?query"sv);
+ VERIFY(details[1].label == "User agent"sv);
+ VERIFY(details[1].is_code);
+}
+
+}
+
+ErrorOr<int> ladybird_main(Main::Arguments arguments)
+{
+ auto test_directory = ByteString::formatted("{}/Ladybird-TestWebCompatReport-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid());
+ TRY(Core::Directory::create(test_directory, Core::Directory::CreateDirectories::Yes));
+ auto cleanup_test_directory = ScopeGuard([&] {
+ MUST(FileSystem::remove(test_directory, FileSystem::RecursionMode::Allowed));
+ });
+ MUST(Core::Environment::set("XDG_CONFIG_HOME"sv, LexicalPath::join(test_directory, "config"sv).string(), Core::Environment::Overwrite::Yes));
+
+#if defined(LADYBIRD_BINARY_PATH)
+ auto app = TRY(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));
+#else
+ auto app = TRY(TestApplication::create(arguments, OptionalNone {}));
+#endif
+
+ verify_validation();
+ verify_diagnostics();
+
+ ReportServer server;
+ MUST(Core::Environment::set("LADYBIRD_REPORTS_ENDPOINT"sv, server.endpoint(), Core::Environment::Overwrite::Yes));
+
+ // A report with a screenshot and the page's dumps carries both, next to the fields that tell pages apart.
+ WebCompatReport report { test_page() };
+ report.set_page_dumps(String::from_utf8_without_validation(page_dumps.bytes()));
+ Outcome outcome;
+ track(report, outcome);
+ server.respond_with(challenge("first"sv));
+ server.respond_with({ 200, R"({"receipt":"receipt-1"})", {} });
+
+ VERIFY(!report.send("The menu does not open"_string, MUST(ByteBuffer::copy(screenshot_png.bytes())),
+ WebCompatReport::IncludePageDumps::Yes)
+ .has_value());
+ VERIFY(report.is_sending());
+ Core::EventLoop::current().spin_until([&] { return outcome.is_finished(); });
+ VERIFY(outcome.sent);
+ VERIFY(server.has_answered_everything());
+ VERIFY(server.requests.size() == 2);
+
+ auto const& upload = server.requests[1];
+ VERIFY(upload.path == "/api/v1/reports"sv);
+ auto manifest_text = multipart_part(upload.body, "manifest"sv);
+ auto diagnostics = multipart_part(upload.body, "diagnostics"sv);
+ VERIFY(diagnostics == report.diagnostics(WebCompatReport::IncludePageDumps::Yes));
+ VERIFY(diagnostics.ends_with(page_dumps));
+ VERIFY(multipart_part(upload.body, "screenshot"sv) == screenshot_png);
+ VERIFY(upload.body.contains("Content-Disposition: form-data; name=\"screenshot\"; filename=\"screenshot.png\"\r\nContent-Type: image/png\r\n"sv));
+
+ auto manifest = JsonValue::from_string(manifest_text).release_value().as_object();
+ VERIFY(manifest.get_string("kind"sv) == "web_compat"sv);
+ VERIFY(manifest.get_string("client_version"sv) == "1.0"sv);
+ VERIFY(manifest_field(manifest, "description"sv)->as_string() == "The menu does not open"sv);
+ VERIFY(manifest_field(manifest, "url"sv)->as_string() == "https://example.com/broken?query"sv);
+ VERIFY(manifest_field(manifest, "user_agent"sv)->as_string() == "Mozilla/5.0 Ladybird/1.0"sv);
+ VERIFY(manifest_field(manifest, "viewport_size"sv)->as_string() == "1280x720"sv);
+ VERIFY(manifest_field(manifest, "device_pixel_ratio"sv)->get_double_with_precision_loss() == 2.);
+ VERIFY(manifest_field(manifest, "zoom_level"sv)->get_double_with_precision_loss() == 1.1);
+ VERIFY(manifest_field(manifest, "platform"sv).has_value());
+ VERIFY(manifest_field(manifest, "git_commit"sv).has_value());
+
+ auto attachments = manifest.get_array("attachments"sv).value();
+ VERIFY(attachments.size() == 2);
+ auto const& described_diagnostics = attachments.at(0).as_object();
+ VERIFY(described_diagnostics.get_string("id"sv) == "diagnostics"sv);
+ VERIFY(described_diagnostics.get_string("name"sv) == "webcompat-diagnostics.txt"sv);
+ VERIFY(described_diagnostics.get_string("media_type"sv) == "text/plain"sv);
+ VERIFY(described_diagnostics.get_string("sha256"sv)->bytes_as_string_view() == sha256_hex(diagnostics));
+ auto const& described_screenshot = attachments.at(1).as_object();
+ VERIFY(described_screenshot.get_string("id"sv) == "screenshot"sv);
+ VERIFY(described_screenshot.get_string("media_type"sv) == "image/png"sv);
+ VERIFY(described_screenshot.get_integer<size_t>("size"sv) == screenshot_png.length());
+ VERIFY(described_screenshot.get_string("sha256"sv)->bytes_as_string_view() == sha256_hex(screenshot_png));
+
+ // Without a screenshot or dumps, only the diagnostics go along. Trying again after a failure sends the same
+ // manifest, submission ID included.
+ server.requests.clear();
+ WebCompatReport plain_report { test_page() };
+ plain_report.set_page_dumps(String::from_utf8_without_validation(page_dumps.bytes()));
+ track(plain_report, outcome);
+ server.respond_with({ 400, "{}", {} });
+ VERIFY(!plain_report.send("Text overlaps"_string, {}, WebCompatReport::IncludePageDumps::No).has_value());
+ Core::EventLoop::current().spin_until([&] { return outcome.is_finished(); });
+ VERIFY(outcome.failure == ReportSubmission::Failure::Sending);
+ VERIFY(outcome.reason == "Report server returned 400 while requesting a challenge."sv);
+ VERIFY(!plain_report.is_sending());
+
+ track(plain_report, outcome);
+ server.respond_with(challenge("second"sv));
+ server.respond_with({ 200, R"({"receipt":"receipt-2"})", {} });
+ plain_report.retry();
+ Core::EventLoop::current().spin_until([&] { return outcome.is_finished(); });
+ VERIFY(outcome.sent);
+ VERIFY(server.requests.size() == 3);
+ VERIFY(server.requests[0].body == server.requests[1].body);
+
+ auto const& plain_upload = server.requests[2];
+ VERIFY(!plain_upload.body.contains("name=\"screenshot\""sv));
+ VERIFY(!multipart_part(plain_upload.body, "diagnostics"sv).contains("Layout tree:"sv));
+ manifest = JsonValue::from_string(multipart_part(plain_upload.body, "manifest"sv)).release_value().as_object();
+ VERIFY(manifest.get_array("attachments"sv)->size() == 1);
+
+ // A canceled report stops sending and hears nothing more, not even about the request it was waiting on.
+ server.requests.clear();
+ WebCompatReport canceled_report { test_page() };
+ track(canceled_report, outcome);
+ VERIFY(!canceled_report.send("Nothing happens"_string, {}, WebCompatReport::IncludePageDumps::No).has_value());
+ Core::EventLoop::current().spin_until([&] { return server.requests.size() == 1; });
+ canceled_report.cancel_sending();
+ VERIFY(!canceled_report.is_sending());
+
+ auto has_waited = false;
+ auto wait = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(200), [&] { has_waited = true; });
+ wait->start();
+ Core::EventLoop::current().spin_until([&] { return has_waited; });
+ VERIFY(!outcome.is_finished());
+ VERIFY(server.requests.size() == 1);
+
+ outln("PASS: Web compatibility reports reach the report server in the format it expects");
+ return 0;
+}