Truly independent web browser
Tests: Serve HTTPS text tests on isolated origins
Shannon Booth8461fa51636c
diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.pyindex da0033dab9e..bfc65d38352 100755--- a/Tests/LibWeb/Fixtures/http-test-server.py+++ b/Tests/LibWeb/Fixtures/http-test-server.py@@ -9,7 +9,6 @@ import itertoolsimport jsonimport loggingimport os-import reimport socketimport socketserverimport ssl@@ -19,6 +18,7 @@ import timeimport urllib.parsefrom collections import defaultdict+from functools import lru_cachefrom types import SimpleNamespacefrom typing import Anyfrom typing import Callable@@ -129,6 +129,15 @@ def name_of_download_in_progress(filename: str) -> Optional[str]:return name+def test_web_host_for(hostname):+ # A test's subdomains and its -alt host belong to the test-web-*.localhost or test-web-*.test host of the test.+ rest, _, top_level_domain = hostname.rpartition(".")+ host = rest.rpartition(".")[2].removesuffix("-alt")+ if top_level_domain not in ("localhost", "test") or not host.startswith("test-web-"):+ return None+ return f"{host}.{top_level_domain}"++class WPTContext:def __init__(self, wpt_directory):vendored_tools_root = os.path.join(wpt_directory, "_wpttools")@@ -195,7 +204,7 @@ class WPTContext:self.configs_by_host_lock = threading.Lock()cast(Any, self.server_class).config = self._build_config("web-platform.localhost")- def _build_config(self, browser_host):+ def _build_config(self, browser_host, alternate_host="not-localhost.localhost"):def make_subdomains_product(subdomains, depth=2):return {".".join(labels)@@ -209,7 +218,7 @@ class WPTContext:with self.config_builder_class(logger,browser_host=browser_host,- alternate_hosts={"alt": "not-localhost.localhost"},+ alternate_hosts={"alt": alternate_host},ports=self.ports,subdomains=subdomains,not_subdomains=not_subdomains,@@ -221,19 +230,23 @@ class WPTContext:# test-web uses unique test-web-*.localhost hosts, or test-web-*.test for insecure-origin tests.# Substitutions like {{host}} and {{domains[www1]}} must name that test host and its subdomains.hostname = request.url_parts.hostname or ""- match = re.search(r"(?:^|\.)(test-web-[0-9a-fA-F-]+\.(?:localhost|test))$", hostname)- if not match:+ test_host = test_web_host_for(hostname)+ if not test_host:return- test_host = match.group(1)+ is_https = request.url_parts.scheme == "https"+ key = (test_host, is_https)with self.configs_by_host_lock:- config = self.configs_by_host.get(test_host)+ config = self.configs_by_host.get(key)if config is None:# Each test has its own host, so only keep the configs of the most recent ones.if len(self.configs_by_host) >= 64:self.configs_by_host.pop(next(iter(self.configs_by_host)))- config = self._build_config(test_host)- self.configs_by_host[test_host] = config+ if is_https:+ config = self._build_config(test_host, test_host.removesuffix(".localhost") + "-alt.localhost")+ else:+ config = self._build_config(test_host)+ self.configs_by_host[key] = configrequest.server.config = configdef close(self):@@ -1072,29 +1085,30 @@ def _setup_tls_test_servers(http_port, ca_cert_output):# subdomains ({{hosts[alt][]}} and {{hosts[alt][www]}}), so the WPT HTTPS server presents a leaf for all of them,# 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"),- # NB: curl ignores a wildcard with fewer than two dots, so the alternate host is named outright.- x509.DNSName("not-localhost.localhost"),- x509.DNSName("*.not-localhost.localhost"),- x509.IPAddress(ipaddress.ip_address("127.0.0.1")),- x509.IPAddress(ipaddress.ip_address("::1")),- ]- ),- critical=False,++ def make_wpt_leaf(names):+ return (+ 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(names), critical=False)+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)+ .sign(root_key, hashes.SHA256()))- .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)- .sign(root_key, hashes.SHA256())++ wpt_leaf = make_wpt_leaf(+ [+ x509.DNSName("localhost"),+ # NB: curl ignores a wildcard with fewer than two dots, so the alternate host is named outright.+ x509.DNSName("not-localhost.localhost"),+ x509.DNSName("*.not-localhost.localhost"),+ x509.IPAddress(ipaddress.ip_address("127.0.0.1")),+ x509.IPAddress(ipaddress.ip_address("::1")),+ ])scenarios["wpt"] = (wpt_leaf, wpt_leaf_key)@@ -1119,6 +1133,25 @@ def _setup_tls_test_servers(http_port, ca_cert_output):config[name] = server.socket.getsockname()[1]threading.Thread(target=server.serve_forever, daemon=True).start()+ # Tests reach HTTPS origins on unique *.localhost hosts, which no wildcard can cover, so each host gets a leaf.+ @lru_cache(maxsize=128)+ def context_for_host(host):+ leaf = make_wpt_leaf([x509.DNSName(host)])+ with tempfile.TemporaryDirectory(dir=scratch) as certificate_directory:+ certificate_path = os.path.join(certificate_directory, "leaf.pem")+ with open(certificate_path, "wb") as certificate:+ certificate.write(leaf.public_bytes(Encoding.PEM))+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(certfile=certificate_path, keyfile=os.path.join(scratch, "wpt.key"))+ return context++ def use_host_certificate(socket, server_name, _context):+ if server_name and server_name.endswith(".localhost"):+ socket.context = context_for_host(server_name)++ assert wpt_ssl_context is not None+ wpt_ssl_context.sni_callback = use_host_certificate+TestHTTPRequestHandler.aia_config = configlogging.info("AIA test servers ready: %s (root CA at %s)", config, ca_cert_output)return wpt_ssl_contextdiff --git a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.sharedworker.txt b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.sharedworker.txtindex c579e929a9e..14bae90f021 100644--- a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.sharedworker.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.sharedworker.txt@@ -2,8 +2,7 @@ Harness status: OKFound 18 tests-17 Pass-1 Fail+18 PassPass Empty string integrityPass SHA-256 integrityPass SHA-384 integrity@@ -20,5 +19,5 @@ Pass Multiple integrities: both are invalidPass CORS empty integrityPass CORS SHA-512 integrityPass CORS invalid integrity-Fail Empty string integrity for opaque response+Pass Empty string integrity for opaque responsePass SHA-* integrity for opaque response\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.txt b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.txtindex c579e929a9e..14bae90f021 100644--- a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.txt@@ -2,8 +2,7 @@ Harness status: OKFound 18 tests-17 Pass-1 Fail+18 PassPass Empty string integrityPass SHA-256 integrityPass SHA-384 integrity@@ -20,5 +19,5 @@ Pass Multiple integrities: both are invalidPass CORS empty integrityPass CORS SHA-512 integrityPass CORS invalid integrity-Fail Empty string integrity for opaque response+Pass Empty string integrity for opaque responsePass SHA-* integrity for opaque response\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.worker.txtindex c579e929a9e..14bae90f021 100644--- a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.worker.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/basic/integrity.sub.any.worker.txt@@ -2,8 +2,7 @@ Harness status: OKFound 18 tests-17 Pass-1 Fail+18 PassPass Empty string integrityPass SHA-256 integrityPass SHA-384 integrity@@ -20,5 +19,5 @@ Pass Multiple integrities: both are invalidPass CORS empty integrityPass CORS SHA-512 integrityPass CORS invalid integrity-Fail Empty string integrity for opaque response+Pass Empty string integrity for opaque responsePass SHA-* integrity for opaque response\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/include.js b/Tests/LibWeb/Text/input/include.jsindex be11acd6762..d5405d4a8ea 100644--- a/Tests/LibWeb/Text/input/include.js+++ b/Tests/LibWeb/Text/input/include.js@@ -292,7 +292,10 @@ class HTTPTestServer {const __httpTestServer = (function () {if (globalThis.internals && globalThis.internals.getEchoServerPort) {const echoServerPort = internals.getEchoServerPort();- const isLoadedFromEchoServer = location.protocol === "http:" && location.port === String(echoServerPort);+ const httpsEchoServerPort = internals.getHttpsEchoServerPort();+ const isLoadedFromEchoServer =+ (location.protocol === "http:" && location.port === String(echoServerPort)) ||+ (location.protocol === "https:" && location.port === String(httpsEchoServerPort));// Tests loaded through the echo server should create echo URLs on their current origin,// so same-origin iframe/fetch checks keep working with unique localhost hostnames.diff --git a/Tests/LibWeb/test-web/main.cpp b/Tests/LibWeb/test-web/main.cppindex 40dfb13d6c3..db19998c843 100644--- a/Tests/LibWeb/test-web/main.cpp+++ b/Tests/LibWeb/test-web/main.cpp@@ -60,6 +60,7 @@ static HashMap<WebView::ViewImplementation const*, size_t> s_view_index_by_view;static RefPtr<Core::Promise<Empty>> s_all_tests_complete;static Vector<ByteString> s_skipped_tests;static Vector<ByteString> s_loaded_from_http_server;+static Vector<ByteString> s_loaded_from_https_server;static Vector<ByteString> s_frame_rate_capped;static Vector<ByteString> s_loaded_from_insecure_origin;static HashMap<WebView::ViewImplementation const*, size_t> s_current_test_index_by_view;@@ -146,6 +147,8 @@ static ErrorOr<void> load_test_config(StringView test_root_path)TRY(add_config_paths(test_root_path, config->keys(group), s_skipped_tests));} else if (group == "LoadFromHttpServer"sv) {TRY(add_config_paths(test_root_path, config->keys(group), s_loaded_from_http_server));+ } else if (group == "LoadFromHttpsServer"sv) {+ TRY(add_config_paths(test_root_path, config->keys(group), s_loaded_from_https_server));} else if (group == "CapFrameRate"sv) {TRY(add_config_paths(test_root_path, config->keys(group), s_frame_rate_capped));} else if (group == "LoadFromInsecureOrigin"sv) {@@ -1027,16 +1030,18 @@ static void run_test(TestWebView& view, TestRunContext& context, size_t test_indOptional<URL::URL> url;auto is_loaded_from_insecure_origin = s_loaded_from_insecure_origin.contains_slow(test.input_path);- if (FileSystem::exists(headers_path) || is_loaded_from_insecure_origin || s_loaded_from_http_server.contains_slow(test.input_path)) {+ auto is_loaded_over_https = s_loaded_from_https_server.contains_slow(test.input_path);+ if (FileSystem::exists(headers_path) || is_loaded_from_insecure_origin || is_loaded_over_https || s_loaded_from_http_server.contains_slow(test.input_path)) {// Some tests need to be served via the echo server so, for example, HTTP headers from .headers// files are sent, or so that the resulting HTML document has a HTTP based origin (e.g for testing// cookies), or one that is not potentially trustworthy.- auto echo_server_port = Application::web_content_options().echo_server_port;+ auto const& options = Application::web_content_options();+ auto echo_server_port = is_loaded_over_https ? options.https_echo_server_port : options.echo_server_port;VERIFY(echo_server_port.has_value());auto relative_path = LexicalPath::relative_path(real_path, app.test_root_path);VERIFY(relative_path.has_value());auto hostname = unique_hostname_within(is_loaded_from_insecure_origin ? "test"sv : "localhost"sv, "test-web"sv);- url = URL::Parser::basic_parse(ByteString::formatted("http://{}:{}/static/{}", hostname, echo_server_port.value(), relative_path.value())).release_value();+ url = URL::Parser::basic_parse(ByteString::formatted("{}://{}:{}/static/{}", is_loaded_over_https ? "https"sv : "http"sv, hostname, echo_server_port.value(), relative_path.value())).release_value();} else {url = URL::create_with_file_scheme(real_path).release_value();}