Truly independent web browser
test-web: Save downloads where the HTTP test server can report them
Luke Wildefae4dc207a19
diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.pyindex ce1d1490679..b0679f1c8cd 100755--- a/Tests/LibWeb/Fixtures/http-test-server.py+++ b/Tests/LibWeb/Fixtures/http-test-server.py@@ -40,6 +40,9 @@ Endpoints:server first sends a binary frame of that many bytes: a 1, zeros, and then a 2.- GET /reflect-websocket-cookie with an "Upgrade: websocket" header: As above, but first sends thehandshake's Cookie header (or an empty string) as a text frame.+ - GET /downloads/<name>: Reports the browser's download of <name> into the --downloads-directory: 404 while+ there is none, 202 while it is in progress, and the downloaded file once it has finished. A <name> longer+ than 188 bytes in UTF-8 gets a 400."""@@ -87,6 +90,22 @@ unblock_events: Dict[str, threading.Event] = {}# Per RFC 6455: appended to Sec-WebSocket-Key before hashing to compute the Sec-WebSocket-Accept value.WEBSOCKET_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"+# The browser saves a download as <name>.<id>.<uuid>.download until it finishes. That suffix takes at most 67 of the+# 255 bytes a filename may have, so a name of up to 188 bytes is never cut short.+MAXIMUM_REPORTED_DOWNLOAD_NAME_LENGTH = 188+++def name_of_download_in_progress(filename: str) -> Optional[str]:+ if not filename.endswith(".download"):+ return None+ parts = filename[: -len(".download")].rsplit(".", 2)+ if len(parts) != 3:+ return None+ name, download_id, uuid = parts+ if not (download_id.isascii() and download_id.isdigit()) or len(uuid) != 36:+ return None+ return name+class WPTContext:def __init__(self, wpt_directory):@@ -229,6 +248,7 @@ class TestHTTPSServerIPv6(TestHTTPSServer):class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):static_directory: strwpt_directory: str+ downloads_directory: Optional[str] = Noneaia_artifacts: dictaia_config: Optional[dict]@@ -368,6 +388,8 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):self.handle_echo()elif request_path.startswith("/recorded-request-headers/"):self._serve_recorded_request_headers()+ elif request_path.startswith("/downloads/"):+ self._serve_download()elif request_path.endswith(".py"):self._serve_wpt_python_script()elif request_path.startswith("/aia/"):@@ -512,6 +534,29 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):self.end_headers()self.wfile.write(json.dumps(headers).encode("utf-8"))+ def _serve_download(self):+ name = urllib.parse.unquote(self.path.partition("?")[0][len("/downloads/") :])+ directory = TestHTTPRequestHandler.downloads_directory+ body = b""+ status = 404+ if len(name.encode("utf-8")) > MAXIMUM_REPORTED_DOWNLOAD_NAME_LENGTH:+ status = 400+ elif directory is not None and name not in ("", ".", "..") and os.path.basename(name) == name:+ path = os.path.join(directory, name)+ if os.path.isfile(path):+ with open(path, "rb") as file:+ body = file.read()+ status = 200+ elif any(name_of_download_in_progress(entry) == name for entry in os.listdir(directory)):+ status = 202++ self.send_response(status)+ self.send_header("Access-Control-Allow-Origin", "*")+ self.send_header("Content-Type", "application/octet-stream")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+def handle_echo(self):method = self.command.upper()parsed_url = urllib.parse.urlparse(self.path)@@ -1018,11 +1063,12 @@ def start_mirror_server(server, server_class, address, ssl_context=None):return mirror-def start_server(port, static_directory, ca_cert_output=None, exit_when_stdin_closes=False):+def start_server(port, static_directory, ca_cert_output=None, exit_when_stdin_closes=False, downloads_directory=None):TestHTTPRequestHandler.static_directory = os.path.abspath(static_directory)TestHTTPRequestHandler.wpt_directory = os.path.join(TestHTTPRequestHandler.static_directory, "Text", "input", "wpt-import")+ TestHTTPRequestHandler.downloads_directory = downloads_directoryhttpd = TestHTTPServer(("127.0.0.1", port), TestHTTPRequestHandler)httpd.daemon_threads = Truehttpd.scheme = "http"@@ -1123,6 +1169,12 @@ if __name__ == "__main__":default=None,help="Path to write the AIA test root CA (PEM) to; enables the AIA broken-chain HTTPS servers",)+ parser.add_argument(+ "--downloads-directory",+ type=str,+ default=None,+ help="Directory the browser saves downloads to, as reported by GET /downloads/<name>",+ )args = parser.parse_args()start_server(@@ -1130,4 +1182,5 @@ if __name__ == "__main__":static_directory=args.directory,ca_cert_output=args.ca_cert_output,exit_when_stdin_closes=args.exit_when_stdin_closes,+ downloads_directory=args.downloads_directory,)diff --git a/Tests/LibWeb/test-web/Application.cpp b/Tests/LibWeb/test-web/Application.cppindex 768f32e42b8..b2dd00c1f03 100644--- a/Tests/LibWeb/test-web/Application.cpp+++ b/Tests/LibWeb/test-web/Application.cpp@@ -13,7 +13,9 @@#include <LibCore/File.h>#include <LibCore/StandardPaths.h>#include <LibCore/System.h>+#include <LibWebCommon/Loader/DownloadFilename.h>#include <LibWebView/TestSpellChecker.h>+#include <errno.h>namespace TestWeb {@@ -127,6 +129,13 @@ void Application::create_platform_options(WebView::BrowserOptions& browser_optio}}+ErrorOr<LexicalPath> Application::default_path_for_downloaded_file(ByteString const& file) const+{+ if (!downloads_directory.has_value())+ return Error::from_errno(ECANCELED);+ return LexicalPath::join(*downloads_directory, Web::sanitize_suggested_download_filename(file));+}+ErrorOr<void> Application::launch_test_fixtures(){Fixture::initialize_fixtures();diff --git a/Tests/LibWeb/test-web/Application.h b/Tests/LibWeb/test-web/Application.hindex 0a87bfa51b4..bedd6ce6c1b 100644--- a/Tests/LibWeb/test-web/Application.h+++ b/Tests/LibWeb/test-web/Application.h@@ -12,7 +12,6 @@#include <AK/String.h>#include <AK/Vector.h>#include <LibWebView/Application.h>-#include <errno.h>namespace TestWeb {@@ -31,7 +30,7 @@ public:// Tests cover elastic overscroll on every platform, whichever of them the browser enables it on.virtual bool platform_scrolls_elastically() const override { return true; }- virtual ErrorOr<LexicalPath> default_path_for_downloaded_file(ByteString const&) const override { return Error::from_errno(ECANCELED); }+ virtual ErrorOr<LexicalPath> default_path_for_downloaded_file(ByteString const&) const override;ErrorOr<void> launch_test_fixtures();@@ -42,6 +41,7 @@ public:ByteString test_root_path;ByteString results_directory { "test-dumps/results"sv };+ Optional<ByteString> downloads_directory;size_t test_concurrency { 1 };Vector<ByteString> test_globs;diff --git a/Tests/LibWeb/test-web/Fixture.cpp b/Tests/LibWeb/test-web/Fixture.cppindex 794626f71b4..d1f23e0b1b9 100644--- a/Tests/LibWeb/test-web/Fixture.cpp+++ b/Tests/LibWeb/test-web/Fixture.cpp@@ -9,6 +9,7 @@#include <AK/ByteBuffer.h>#include <AK/LexicalPath.h>+#include <LibCore/Directory.h>#include <LibCore/File.h>#include <LibCore/Process.h>#include <LibCore/StandardPaths.h>@@ -58,7 +59,10 @@ ErrorOr<void> HttpEchoServerFixture::setup(WebView::WebContentOptions& web_conte// Path where http-test-server.py writes the AIA test root CA. Must match the certificate trusted by// TestWeb::Application::create_platform_options.auto const ca_cert_path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), ByteString::formatted("ladybird-aia-test-ca-{}.pem", Core::System::getpid())).string();- auto const arguments = Vector { script_path.string(), "--directory", Application::the().test_root_path, "--ca-cert-output", ca_cert_path, "--exit-when-stdin-closes" };++ auto const downloads_directory = LexicalPath::join(Core::StandardPaths::tempfile_directory(), ByteString::formatted("ladybird-test-web-downloads-{}", Core::System::getpid())).string();++ auto const arguments = Vector { script_path.string(), "--directory", Application::the().test_root_path, "--ca-cert-output", ca_cert_path, "--downloads-directory", downloads_directory, "--exit-when-stdin-closes" };// FIXME: Pick a more reasonable log path that is more observableauto const log_path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), "http-test-server.log"sv).string();@@ -77,7 +81,16 @@ ErrorOr<void> HttpEchoServerFixture::setup(WebView::WebContentOptions& web_conteCore::FileAction::DupFd { stdout_fds[1], STDOUT_FILENO } }};- m_process = TRY(Core::Process::spawn(process_options));+ TRY(Core::Directory::create(downloads_directory, Core::Directory::CreateDirectories::Yes));+ Application::the().downloads_directory = downloads_directory;++ auto process = Core::Process::spawn(process_options);+ if (process.is_error()) {+ Application::the().downloads_directory = {};+ (void)FileSystem::remove(downloads_directory, FileSystem::RecursionMode::Allowed);+ return process.release_error();+ }+ m_process = process.release_value();TRY(Core::System::close(stdin_fds[0]));m_stdin_fd = stdin_fds[1];@@ -126,6 +139,8 @@ void HttpEchoServerFixture::teardown_impl()m_stdout_file = nullptr;auto const ca_cert_path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), ByteString::formatted("ladybird-aia-test-ca-{}.pem", Core::System::getpid())).string();(void)FileSystem::remove(ca_cert_path, FileSystem::RecursionMode::Disallowed);+ if (auto downloads_directory = exchange(Application::the().downloads_directory, {}); downloads_directory.has_value())+ (void)FileSystem::remove(*downloads_directory, FileSystem::RecursionMode::Allowed);}void Fixture::initialize_fixtures()