Truly independent web browser
LibWeb: Send `Accept-Language` in the WebSocket opening handshake
Callum Lawc83814337f90
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 33b0872c525..619973f2fc4 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -318,6 +318,19 @@ static void store_response_in_cache(HTTP::MemoryCache& http_cache, Infrastructurhttp_cache.create_entry(request.current_url(), request.method(), request.header_list(), request.request_time(), response.status(), response.status_message(), response.header_list());}+// https://fetch.spec.whatwg.org/#concept-fetch+// NB: The WebSocket opening handshake does not go through fetch yet, so it runs this step on its own.+void append_accept_language_header_if_missing(Infrastructure::Request& request, LoaderConfig const& loader_config)+{+ if (!request.header_list()->contains("Accept-Language"sv)) {+ StringBuilder accept_language;+ accept_language.join(","sv, loader_config.preferred_languages);++ auto header = HTTP::Header::isomorphic_encode("Accept-Language"sv, accept_language.string_view());+ request.header_list()->append(move(header));+ }+}+// https://fetch.spec.whatwg.org/#concept-fetchGC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure::Request& request, Infrastructure::FetchAlgorithms const& algorithms, UseParallelQueue use_parallel_queue, CreateResponseBodyTransferLease create_response_body_transfer_lease){@@ -498,13 +511,7 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:// 12. If request’s header list does not contain `Accept-Language`, then user agents should append// (`Accept-Language, an appropriate header value) to request’s header list.- if (!request.header_list()->contains("Accept-Language"sv)) {- StringBuilder accept_language;- accept_language.join(","sv, fetch_params->loader_config().preferred_languages);-- auto header = HTTP::Header::isomorphic_encode("Accept-Language"sv, accept_language.string_view());- request.header_list()->append(move(header));- }+ append_accept_language_header_if_missing(request, fetch_params->loader_config());// 13. If request’s internal priority is null, then use request’s priority, initiator, destination, and// render-blocking in an implementation-defined manner to set request’s internal priority to andiff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.hindex a26d661e489..740b8581e2c 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h@@ -51,6 +51,7 @@ ENUMERATE_BOOL_PARAMS#undef __ENUMERATE_BOOL_PARAMWEB_API GC::Ref<Infrastructure::FetchController> fetch(JS::Realm&, Infrastructure::Request&, Infrastructure::FetchAlgorithms const&, UseParallelQueue use_parallel_queue = UseParallelQueue::No, CreateResponseBodyTransferLease = CreateResponseBodyTransferLease::No);+void append_accept_language_header_if_missing(Infrastructure::Request&, LoaderConfig const&);GC::Ptr<PendingResponse> main_fetch(JS::Realm&, Infrastructure::FetchParams const&, Recursive recursive = Recursive::No);void upgrade_request_to_https_for_known_hsts_host_if_appropriate(Page&, Infrastructure::Request&);// Runs the in-parallel steps that main fetch deferred under the id.diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cppindex abde06a2993..fe263fa858b 100644--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp@@ -198,8 +198,11 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_recrequest->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Error);// FIXME: Fetch request as per the remaining steps of https://websockets.spec.whatwg.org/#concept-websocket-establish- // AD-HOC: Until the opening handshake goes through fetch, run the blocking checks and the HSTS upgrade of main- // fetch here.+ // AD-HOC: Until the opening handshake goes through fetch, append `Accept-Language` and run the blocking checks+ // and the HSTS upgrade of main fetch here.+ auto loader_config = current_loader_config();+ Fetch::Fetching::append_accept_language_header_if_missing(*request, loader_config->config);+request->set_policy_container(client.policy_container()->clone());request->set_client_snapshot(Fetch::Fetching::snapshot_client_context(client));auto report_violation = ContentSecurityPolicy::violation_reporter_for_request(client.realm(), request);@@ -232,10 +235,8 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_recfor (auto const& protocol : protocols)TRY(protocol_byte_strings.try_append(protocol.to_utf8().to_byte_string()));- auto additional_headers = HTTP::HeaderList::create();-- auto user_agent = Fetch::Infrastructure::default_user_agent_value(current_loader_config()->config, request);- additional_headers->append({ "User-Agent"sv, user_agent.to_byte_string() });+ auto user_agent = Fetch::Infrastructure::default_user_agent_value(loader_config->config, request);+ request->header_list()->append({ "User-Agent"sv, user_agent.to_byte_string() });if (ResourceLoader::proxy_autoconfig_url().has_value()) {dbgln("FIXME: Evaluate the PAC file to find the proxy for {}; failing the WebSocket connection", url_record);@@ -253,7 +254,7 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_recauto& page = Bindings::principal_host_defined_page(client.realm());auto originating_page_id = page.has_top_level_traversable() ? page.client().id().value() : 0;- m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, additional_headers, originating_page_id, { .status = request->same_site_status(), .is_safe_method = true });+ m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, *request->header_list(), originating_page_id, { .status = request->same_site_status(), .is_safe_method = true });m_websocket->on_open = GC::weak_callback(*this, [](auto& self) {self.on_open();diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.pyindex 7bff6391fe3..211df98a32f 100755--- a/Tests/LibWeb/Fixtures/http-test-server.py+++ b/Tests/LibWeb/Fixtures/http-test-server.py@@ -45,6 +45,7 @@ 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 /reflect-websocket-accept-language does the same for the handshake's Accept-Language header.- GET /websocket-close-without-response with an "Upgrade: websocket" header: Closes the connection withoutresponding to the handshake.- GET /recorded-request-count/<echo path>: Responds with the number of requests the server has seen at <echo path>,@@ -806,6 +807,8 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):if self.path == "/reflect-websocket-cookie":self._send_websocket_frame(self.headers.get("Cookie", "").encode("utf-8"))+ elif self.path == "/reflect-websocket-accept-language":+ self._send_websocket_frame(self.headers.get("Accept-Language", "").encode("utf-8"))query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)if "send-binary" in query:diff --git a/Tests/LibWeb/Text/expected/WebSocket/handshake-accept-language.txt b/Tests/LibWeb/Text/expected/WebSocket/handshake-accept-language.txtnew file mode 100644index 00000000000..0581f65091c--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebSocket/handshake-accept-language.txt@@ -0,0 +1,2 @@+WebSocket sent Accept-Language: true+Accept-Language matches fetch(): truediff --git a/Tests/LibWeb/Text/input/WebSocket/handshake-accept-language.html b/Tests/LibWeb/Text/input/WebSocket/handshake-accept-language.htmlnew file mode 100644index 00000000000..2a99116a924--- /dev/null+++ b/Tests/LibWeb/Text/input/WebSocket/handshake-accept-language.html@@ -0,0 +1,22 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const url = await server.createEcho("GET", "/accept-language", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*" },+ reflect_headers_in_body: true,+ });+ const headers = await (await fetch(url)).json();+ const socket = new WebSocket(`${server.baseURL}/reflect-websocket-accept-language`);+ const language = await new Promise((resolve, reject) => {+ socket.onmessage = event => resolve(event.data);+ socket.onerror = () => reject(new Error("WebSocket handshake failed"));+ });+ socket.close();++ println(`WebSocket sent Accept-Language: ${language.length > 0}`);+ println(`Accept-Language matches fetch(): ${language === headers["Accept-Language"][0]}`);+ });+</script>