Truly independent web browser
LibWeb+LibWebView+WebContent: Serve the WPT tree over HTTPS in test-web
Shannon Booth77e111212fba
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 531afe61119..f686dc53ee1 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -116,6 +116,7 @@namespace Web::Internals {static u16 s_echo_server_port { 0 };+static u16 s_https_echo_server_port { 0 };static Web::WheelDeltaPrecision wheel_delta_precision_from(bool precise){@@ -1528,6 +1529,16 @@ void Internals::set_echo_server_port(u16 const port)s_echo_server_port = port;}+u16 Internals::get_https_echo_server_port()+{+ return s_https_echo_server_port;+}++void Internals::set_https_echo_server_port(u16 const port)+{+ s_https_echo_server_port = port;+}+WebIDL::ExceptionOr<void> Internals::set_hsts_policy(Utf16String const& domain, u64 max_age, bool include_sub_domains){auto domain_utf8 = TRY_OR_THROW_OOM(vm(), domain.utf16_view().to_utf8());diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 34aaade3992..fa5984795ce 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -184,6 +184,8 @@ public:static u16 get_echo_server_port();static void set_echo_server_port(u16 port);+ static u16 get_https_echo_server_port();+ static void set_https_echo_server_port(u16 port);WebIDL::ExceptionOr<void> set_hsts_policy(Utf16String const& domain, u64 max_age, bool include_sub_domains);WebIDL::ExceptionOr<void> ingest_hsts_header(Utf16String const& url, Utf16String const& header_value);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex 215e99be344..a06fda1e23a 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -182,6 +182,7 @@ interface Internals {DOMString getComputedAriaLevel(Element element);undefined setAccessibilityFocusTarget(Element element);unsigned short getEchoServerPort();+ unsigned short getHttpsEchoServerPort();undefined setHSTSPolicy(DOMString domain, unsigned long long maxAge, boolean includeSubDomains);undefined ingestHSTSHeader(USVString url, DOMString headerValue);diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex c8ac20ba801..b5218376db6 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -344,6 +344,11 @@ ErrorOr<NonnullRefPtr<WebView::WebContentClient>> launch_web_content_process(IsParguments.append(ByteString::number(maybe_echo_server_port.value()));}+ if (auto const maybe_https_echo_server_port = web_content_options.https_echo_server_port; maybe_https_echo_server_port.has_value()) {+ arguments.append("--https-echo-server-port"sv);+ arguments.append(ByteString::number(maybe_https_echo_server_port.value()));+ }+if (web_content_options.default_time_zone.has_value()) {arguments.append("--default-time-zone");arguments.append(web_content_options.default_time_zone.value());diff --git a/Libraries/LibWebView/Options.h b/Libraries/LibWebView/Options.hindex ae8bcaff180..33356f8f671 100644--- a/Libraries/LibWebView/Options.h+++ b/Libraries/LibWebView/Options.h@@ -192,6 +192,7 @@ struct WebContentOptions {EnableAutoplay enable_autoplay { EnableAutoplay::No };CollectGarbageOnEveryAllocation collect_garbage_on_every_allocation { CollectGarbageOnEveryAllocation::No };Optional<u16> echo_server_port {};+ Optional<u16> https_echo_server_port {};PaintViewportScrollbars paint_viewport_scrollbars { PaintViewportScrollbars::Yes };FileSchemeUrlsHaveTupleOrigins file_scheme_urls_have_tuple_origins { FileSchemeUrlsHaveTupleOrigins::No };Optional<StringView> default_time_zone {};diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex 6e1052f15f9..6a19e6d25fc 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -186,6 +186,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool disable_scrollbar_painting = false;bool disable_sandbox = false;StringView echo_server_port_string_view {};+ StringView https_echo_server_port_string_view {};StringView default_time_zone {};bool file_origins_are_tuple_origins = false;@@ -205,6 +206,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(disable_scrollbar_painting, "Don't paint horizontal or vertical viewport scrollbars", "disable-scrollbar-painting");args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.add_option(echo_server_port_string_view, "Echo server port used in test internals", "echo-server-port", 0, "echo_server_port");+ args_parser.add_option(https_echo_server_port_string_view, "HTTPS echo server port used in test internals", "https-echo-server-port", 0, "https_echo_server_port");args_parser.add_option(is_headless, "Report that the browser is running in headless mode", "headless");args_parser.add_option(default_time_zone, "Default time zone", "default-time-zone", 0, "time-zone-id");args_parser.add_option(file_origins_are_tuple_origins, "Treat file:// URLs as having tuple origins", "tuple-file-origins");@@ -263,6 +265,13 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)VERIFY_NOT_REACHED();}+ if (!https_echo_server_port_string_view.is_empty()) {+ if (auto maybe_https_echo_server_port = https_echo_server_port_string_view.to_number<u16>(); maybe_https_echo_server_port.has_value())+ Web::Internals::Internals::set_https_echo_server_port(maybe_https_echo_server_port.value());+ else+ VERIFY_NOT_REACHED();+ }+OPENSSL_TRY(OSSL_set_max_threads(nullptr, Core::System::hardware_concurrency()));Web::HTML::Window::set_enable_test_mode(enable_test_mode);diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.pyindex 2ee3ed92dab..5da91edaa9b 100755--- a/Tests/LibWeb/Fixtures/http-test-server.py+++ b/Tests/LibWeb/Fixtures/http-test-server.py@@ -4,6 +4,7 @@ import argparseimport base64import hashlibimport http.server+import ipaddressimport itertoolsimport jsonimport logging@@ -138,7 +139,7 @@ class WPTContext:return handler- def configure_server(self, http_ports):+ def configure_server(self, http_ports, https_ports):def make_subdomains_product(subdomains, depth=2):return {".".join(labels)@@ -153,7 +154,7 @@ class WPTContext:logger,browser_host="web-platform.localhost",alternate_hosts={"alt": "not-localhost.localhost"},- ports={"http": http_ports},+ ports={"http": http_ports, "https": https_ports},subdomains=subdomains,not_subdomains=not_subdomains,check_subdomains=False,@@ -178,6 +179,19 @@ class TestHTTPServerIPv6(TestHTTPServer):address_family = socket.AF_INET6+class TestHTTPSServer(TestHTTPServer):+ ssl_context: ssl.SSLContext++ def get_request(self):+ sock, addr = super().get_request()+ # Leave the handshake to the first read, which happens on the request's own thread.+ return self.ssl_context.wrap_socket(sock, server_side=True, do_handshake_on_connect=False), addr+++class TestHTTPSServerIPv6(TestHTTPSServer):+ address_family = socket.AF_INET6++class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):static_directory: strwpt_directory: str@@ -743,7 +757,7 @@ class AIATLSServer(socketserver.ThreadingTCPServer):raise-def _setup_aia_test_servers(http_port, ca_cert_output):+def _setup_tls_test_servers(http_port, ca_cert_output):try:from cryptography import x509 # type: ignore[import-not-found]from cryptography.hazmat.primitives import hashes # type: ignore[import-not-found]@@ -756,8 +770,8 @@ def _setup_aia_test_servers(http_port, ca_cert_output):from cryptography.x509.oid import ExtendedKeyUsageOID # type: ignore[import-not-found]from cryptography.x509.oid import NameOID # type: ignore[import-not-found]except ImportError as error:- logging.warning("AIA test setup skipped: python 'cryptography' unavailable (%s)", error)- return+ logging.warning("TLS test setup skipped: python 'cryptography' unavailable (%s)", error)+ return Noneimport datetimeimport tempfile@@ -897,8 +911,35 @@ def _setup_aia_test_servers(http_port, ca_cert_output):with open(ca_cert_output, "wb") as ca_file:ca_file.write(root.public_bytes(Encoding.PEM))+ # WPT tests reach HTTPS origins on localhost and 127.0.0.1, so the WPT HTTPS server presents a leaf for both, issued+ # by the root itself.+ wpt_leaf_key = new_key()+ wpt_leaf = (+ x509.CertificateBuilder()+ .subject_name(dn("localhost"))+ .issuer_name(root.subject)+ .public_key(wpt_leaf_key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(not_before)+ .not_valid_after(not_after)+ .add_extension(+ x509.SubjectAlternativeName(+ [+ x509.DNSName("localhost"),+ x509.IPAddress(ipaddress.ip_address("127.0.0.1")),+ x509.IPAddress(ipaddress.ip_address("::1")),+ ]+ ),+ critical=False,+ )+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)+ .sign(root_key, hashes.SHA256())+ )+ scenarios["wpt"] = (wpt_leaf, wpt_leaf_key)+scratch = tempfile.mkdtemp(prefix="ladybird-aia-")config = {}+ wpt_ssl_context = Nonefor name, (leaf, leaf_key) in scenarios.items():# The cert file holds *only* the leaf — so, each HTTPS host presents a broken chain (the intermediate is omitted# and must be fetched via AIA).@@ -910,18 +951,25 @@ def _setup_aia_test_servers(http_port, ca_cert_output):f.write(leaf_key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()))context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)context.load_cert_chain(certfile=cert_path, keyfile=key_path)+ if name == "wpt":+ wpt_ssl_context = context+ continueserver = AIATLSServer(("127.0.0.1", 0), AIALeafHandler, context)config[name] = server.socket.getsockname()[1]threading.Thread(target=server.serve_forever, daemon=True).start()TestHTTPRequestHandler.aia_config = configlogging.info("AIA test servers ready: %s (root CA at %s)", config, ca_cert_output)+ return wpt_ssl_context-def start_mirror_server(server, server_class, address):+def start_mirror_server(server, server_class, address, ssl_context=None):mirror = server_class(address, TestHTTPRequestHandler)mirror.daemon_threads = Truemirror.scheme = server.scheme+ if ssl_context:+ mirror.ssl_context = ssl_context+ mirror.scheme = "https"mirror.router = server.routermirror.wpt = server.wptmirror.wpt_file_handler = server.wpt_file_handler@@ -949,6 +997,19 @@ def start_server(port, static_directory, ca_cert_output=None, exit_when_stdin_cl# WPT tests reach a second HTTP origin through {{ports[http][1]}}, so serve the same content on another port.alternate_httpd = start_mirror_server(httpd, TestHTTPServer, ("127.0.0.1", 0))+ https_httpd = None+ if ca_cert_output:+ # Avoid trusting a stale CA if setup fails. Preserve the inode granted by the sandbox.+ open(ca_cert_output, "wb").close()++ try:+ wpt_ssl_context = _setup_tls_test_servers(httpd.socket.getsockname()[1], ca_cert_output)+ if wpt_ssl_context:+ # WPT tests reach HTTPS origins through {{ports[https][0]}}, so serve the same content over TLS too.+ https_httpd = start_mirror_server(httpd, TestHTTPSServer, ("127.0.0.1", 0), wpt_ssl_context)+ except Exception as error:+ logging.exception("TLS test setup failed: %s", error)+# A localhost name resolves to ::1 first, which Windows is slow to refuse, so serve there too.ipv6_servers = []for server in (httpd, alternate_httpd):@@ -956,19 +1017,21 @@ def start_server(port, static_directory, ca_cert_output=None, exit_when_stdin_clipv6_servers.append(start_mirror_server(server, TestHTTPServerIPv6, ("::1", server.server_address[1])))except OSError as error:logging.warning("Not serving on ::1: %s", error)-- httpd.wpt.configure_server([httpd.socket.getsockname()[1], alternate_httpd.socket.getsockname()[1]])-- if ca_cert_output:- # Avoid trusting a stale CA if setup fails. Preserve the inode granted by the sandbox.- open(ca_cert_output, "wb").close()-+ if https_httpd:try:- _setup_aia_test_servers(httpd.socket.getsockname()[1], ca_cert_output)- except Exception as error:- logging.exception("AIA test setup failed: %s", error)+ ipv6_servers.append(+ start_mirror_server(+ https_httpd, TestHTTPSServerIPv6, ("::1", https_httpd.server_address[1]), https_httpd.ssl_context+ )+ )+ except OSError as error:+ logging.warning("Not serving HTTPS on ::1: %s", error)++ https_ports = [https_httpd.socket.getsockname()[1]] if https_httpd else []+ httpd.wpt.configure_server([httpd.socket.getsockname()[1], alternate_httpd.socket.getsockname()[1]], https_ports)- print(httpd.socket.getsockname()[1])+ # The first line holds the HTTP port, followed by the HTTPS port if there is one.+ print(" ".join(str(port) for port in [httpd.socket.getsockname()[1], *https_ports]))sys.stdout.flush()if exit_when_stdin_closes:@@ -988,6 +1051,8 @@ def start_server(port, static_directory, ca_cert_output=None, exit_when_stdin_clfor server in ipv6_servers:server.server_close()alternate_httpd.server_close()+ if https_httpd:+ https_httpd.server_close()httpd.server_close()diff --git a/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-match.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-match.https.any.txtindex ff664533b40..a190b078d9b 100644--- a/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-match.https.any.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-match.https.any.txt@@ -2,8 +2,7 @@ Harness status: OKFound 25 tests-23 Pass-2 Fail+25 PassPass Cache.match with no matching entriesPass Cache.match with URLPass Cache.match with Request@@ -25,7 +24,7 @@ Pass Cache.match with POST RequestPass Cache.match with a non-2xx ResponsePass Cache.match with a network error ResponsePass Cache produces large Responses that can be cloned and read correctly.-Fail cors-exposed header should be stored correctly.+Pass cors-exposed header should be stored correctly.Pass MIME type should be set from content-header correctly.Pass MIME type should reflect Content-Type headers of response.-Fail Cache.match ignores vary headers on opaque response.\ No newline at end of file+Pass Cache.match ignores vary headers on opaque response.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-put.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-put.https.any.txtindex 33f45e5e765..d02898284ec 100644--- a/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-put.https.any.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/service-workers/cache-storage/cache-put.https.any.txt@@ -2,8 +2,8 @@ Harness status: OKFound 27 tests-24 Pass-3 Fail+25 Pass+2 FailPass Cache.put called with simple Request and ResponsePass Cache.put called with Request and Response from fetch()Pass Cache.put with Request without a body@@ -27,7 +27,7 @@ Pass Cache.put with a used response bodyPass getReader() after Cache.putPass Cache.put with a VARY:* ResponsePass Cache.put with an embedded VARY:* Response-Fail Cache.put with a VARY:* opaque response should not reject+Pass Cache.put with a VARY:* opaque response should not rejectPass Cache.put should store Response.redirect() correctlyPass Cache.put called with simple Request and blob ResponsePass Cache.put called with simple Request and form data Response\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/worklets/audio-worklet-import.https.txt b/Tests/LibWeb/Text/expected/wpt-import/worklets/audio-worklet-import.https.txtindex 287d2b2f983..f6c4f585d88 100644--- a/Tests/LibWeb/Text/expected/wpt-import/worklets/audio-worklet-import.https.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/worklets/audio-worklet-import.https.txt@@ -2,8 +2,8 @@ Harness status: OKFound 18 tests-13 Pass-5 Fail+15 Pass+3 FailPass Importing a script resolves the given promise.Pass Importing scripts resolves all the given promises.Pass Importing nested scripts resolves the given promise@@ -15,9 +15,9 @@ Pass Importing a blob URL should resolve the given promise.Pass Importing a file:// URL should reject the given promise.Pass Importing a data URL should resolve the given promise.Pass Importing about:blank should reject the given promise.-Fail Importing a cross origin resource with the Access-Control-Allow-Origin header should resolve the given promise+Pass Importing a cross origin resource with the Access-Control-Allow-Origin header should resolve the given promisePass Importing a cross origin resource without the Access-Control-Allow-Origin header should reject the given promise-Fail Importing a cross-origin-redirected resource with the Access-Control-Allow-Origin header should resolve the given promise+Pass Importing a cross-origin-redirected resource with the Access-Control-Allow-Origin header should resolve the given promisePass Importing a cross-origin-redirected resource without the Access-Control-Allow-Origin header should reject the given promiseFail Importing a script that has a syntax error should reject the given promise.Fail Importing a nested script that has a syntax error should reject the given promise.diff --git a/Tests/LibWeb/Text/input/wpt-import/common/get-host-info.sub.js b/Tests/LibWeb/Text/input/wpt-import/common/get-host-info.sub.jsindex 7bc953bd983..24604c26c32 100644--- a/Tests/LibWeb/Text/input/wpt-import/common/get-host-info.sub.js+++ b/Tests/LibWeb/Text/input/wpt-import/common/get-host-info.sub.js@@ -8,7 +8,7 @@ function get_host_info() {var HTTP_PORT = ECHO_SERVER_PORT;var HTTP_PORT2 = ECHO_SERVER_PORT;- var HTTPS_PORT = '443';+ var HTTPS_PORT = String(internals.getHttpsEchoServerPort());var HTTPS_PORT2 = '8443';var PROTOCOL = self.location.protocol;var IS_HTTPS = (PROTOCOL == "https:");diff --git a/Tests/LibWeb/test-web/Fixture.cpp b/Tests/LibWeb/test-web/Fixture.cppindex 0d517e3b62d..794626f71b4 100644--- a/Tests/LibWeb/test-web/Fixture.cpp+++ b/Tests/LibWeb/test-web/Fixture.cpp@@ -95,11 +95,20 @@ ErrorOr<void> HttpEchoServerFixture::setup(WebView::WebContentOptions& web_conte}auto const raw_output = first_line.to_byte_string();- if (auto const maybe_port = raw_output.trim_whitespace().to_number<u16>(); maybe_port.has_value())+ // The first line holds the HTTP port, followed by the HTTPS port if the server could set one up.+ auto const ports = raw_output.split_view(' ');+ if (auto const maybe_port = ports.is_empty() ? Optional<u16> {} : ports[0].to_number<u16>(); maybe_port.has_value())web_content_options.echo_server_port = maybe_port.value();elsewarnln("Failed to read echo server port from buffer: '{}'", raw_output);+ if (ports.size() > 1) {+ if (auto const maybe_port = ports[1].to_number<u16>(); maybe_port.has_value())+ web_content_options.https_echo_server_port = maybe_port.value();+ else+ warnln("Failed to read HTTPS echo server port from buffer: '{}'", raw_output);+ }+return {};}