Truly independent web browser
LibWeb: Apply hyperlink referrer policy to downloads
Jelle Raaijmakerse44614d33ae3
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 4154db0fa6d..b66d3f5d224 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -779,6 +779,10 @@ void Element::download_the_hyperlink(Optional<Utf16String> hyperlink_suffix, HTMrequest->set_use_url_credentials(true);// NB: The synchronous flag is not set; the response is instead processed asynchronously on the main thread.+ // AD-HOC: The request's referrer policy is subject's hyperlink referrer policy, as when following the hyperlink.+ // See https://github.com/whatwg/html/issues/5623+ request->set_referrer_policy(hyperlink_referrer_policy());+// 3. Let response be the result of fetching request.// 4. Handle as a download response with subject's node navigable and null.auto controller_holder = Fetch::Infrastructure::FetchControllerHolder::create();diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 036731ce703..3027e3062e7 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -888,6 +888,10 @@ Text/input/HTML/module-script-moved-to-document-without-browsing-context.html; Reads the headers the echo server recorded for navigations of an iframe, which need a matching HTTP origin.Text/input/HTML/hyperlink-rel-noreferrer.html+; Reads request headers from the WPT dispatcher, which runs on the test server.+Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.html+Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.html+; Reads the headers the echo server recorded for links opened in new views, which need a matching HTTP origin.Text/input/HTML/link-opened-in-new-tab-headless.htmlText/input/Fetch/sec-fetch-site-link-opened-in-new-tab.htmldiff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.txtnew file mode 100644index 00000000000..eb85329a5f5--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.txt@@ -0,0 +1,9 @@+Harness status: OK++Found 4 tests++4 Pass+Pass <a download> without referrerpolicy follows the document's no-referrer policy+Pass <a download referrerpolicy=unsafe-url> overrides the document's no-referrer policy+Pass <area download> without referrerpolicy follows the document's no-referrer policy+Pass <area download referrerpolicy=unsafe-url> overrides the document's no-referrer policy\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.txtnew file mode 100644index 00000000000..504e3ae4ba1--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.txt@@ -0,0 +1,15 @@+Harness status: OK++Found 10 tests++10 Pass+Pass <a download> without referrerpolicy sends the full URL+Pass <a download referrerpolicy=no-referrer> sends no Referer+Pass <a download referrerpolicy=origin> sends the origin+Pass <a download> ignores an invalid referrerpolicy value+Pass <a download rel=noreferrer> wins over referrerpolicy+Pass <area download> without referrerpolicy sends the full URL+Pass <area download referrerpolicy=no-referrer> sends no Referer+Pass <area download referrerpolicy=origin> sends the origin+Pass <area download> ignores an invalid referrerpolicy value+Pass <area download rel=noreferrer> wins over referrerpolicy\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/common/dispatcher/dispatcher.js b/Tests/LibWeb/Text/input/wpt-import/common/dispatcher/dispatcher.jsnew file mode 100644index 00000000000..dab0100020b--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/dispatcher/dispatcher.js@@ -0,0 +1,281 @@+// Define a universal message passing API. It works cross-origin and across+// browsing context groups.+const dispatcher_path = "/common/dispatcher/dispatcher.py";++// Finds the nearest ancestor window that has a non srcdoc location. This should+// give us a usable location for constructing further URLs.+function findLocationFromAncestors(w) {+ if (w.location.href == 'about:srcdoc') {+ return findLocationFromAncestors(w.parent);+ }+ return w.location;+}++// Handles differences between workers vs frames (src vs srcdoc).+function findLocation() {+ if (location.href == 'about:srcdoc') {+ return findLocationFromAncestors(window.parent);+ }+ if (location.protocol == 'blob:' || location.protocol == 'data:') {+ // Allows working around blob and data URLs.+ if (self.document && self.document.baseURI) {+ return self.document.baseURI;+ }+ }+ return location;+}++const dispatcherLocation = findLocation();+const dispatcher_url = new URL(dispatcher_path, dispatcherLocation).href;++// Return a promise, limiting the number of concurrent accesses to a shared+// resources to |max_concurrent_access|.+const concurrencyLimiter = (max_concurrency) => {+ let pending = 0;+ let waiting = [];+ return async (task) => {+ pending++;+ if (pending > max_concurrency)+ await new Promise(resolve => waiting.push(resolve));+ let result = await task();+ pending--;+ waiting.shift()?.();+ return result;+ };+}++// Wait for a random amount of time in the range [10ms,100ms].+const randomDelay = () => {+ return new Promise(resolve => setTimeout(resolve, 10 + 90*Math.random()));+}++// Sending too many requests in parallel causes congestion. Limiting it improves+// throughput.+//+// Note: The following table has been determined on the test:+// ../cache-storage.tentative.https.html+// using Chrome with a 64 core CPU / 64GB ram, in release mode:+// ┌───────────┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬────┐+// │concurrency│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 10│ 15│ 20│ 30│ 50│ 100│+// ├───────────┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼────┤+// │time (s) │ 54│ 38│ 31│ 29│ 26│ 24│ 22│ 22│ 22│ 22│ 34│ 36 │+// └───────────┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴────┘+const limiter = concurrencyLimiter(6);++// While requests to different remote contexts can go in parallel, we need to+// ensure that requests to each remote context are done in order. This maps a+// uuid to a queue of requests to send. A queue is processed until it is empty+// and then is deleted from the map.+const sendQueues = new Map();++// Sends a single item (with rate-limiting) and calls the associated resolver+// when it is successfully sent.+const sendItem = async function (uuid, resolver, message) {+ await limiter(async () => {+ // Requests might be dropped. Retry until getting a confirmation it has been+ // processed.+ while(1) {+ try {+ let response = await fetch(dispatcher_url + `?uuid=${uuid}`, {+ method: 'POST',+ body: message+ })+ if (await response.text() == "done") {+ resolver();+ return;+ }+ } catch (fetch_error) {}+ await randomDelay();+ };+ });+}++// While the queue is non-empty, send the next item. This is async and new items+// may be added to the queue while others are being sent.+const processQueue = async function (uuid, queue) {+ while (queue.length) {+ const [resolver, message] = queue.shift();+ await sendItem(uuid, resolver, message);+ }+ // The queue is empty, delete it.+ sendQueues.delete(uuid);+}++const send = async function (uuid, message) {+ const itemSentPromise = new Promise((resolve) => {+ const item = [resolve, message];+ if (sendQueues.has(uuid)) {+ // There is already a queue for `uuid`, just add to it and it will be processed.+ sendQueues.get(uuid).push(item);+ } else {+ // There is no queue for `uuid`, create it and start processing.+ const queue = [item];+ sendQueues.set(uuid, queue);+ processQueue(uuid, queue);+ }+ });+ // Wait until the item has been successfully sent.+ await itemSentPromise;+}++const receive = async function (uuid) {+ while(1) {+ let data = "not ready";+ try {+ data = await limiter(async () => {+ let response = await fetch(dispatcher_url + `?uuid=${uuid}`);+ return await response.text();+ });+ } catch (fetch_error) {}++ if (data == "not ready") {+ await randomDelay();+ continue;+ }++ return data;+ }+}++// Returns an URL. When called, the server sends toward the `uuid` queue the+// request headers. Useful for determining if something was requested with+// Cookies.+const showRequestHeaders = function(origin, uuid) {+ return origin + dispatcher_path + `?uuid=${uuid}&show-headers`;+}++// Same as above, except for the response is cacheable.+const cacheableShowRequestHeaders = function(origin, uuid) {+ return origin + dispatcher_path + `?uuid=${uuid}&cacheable&show-headers`;+}++// This script requires+// - `/common/utils.js` for `token()`.++// Returns the URL of a document that can be used as a `RemoteContext`.+//+// `uuid` should be a UUID uniquely identifying the given remote context.+// `options` has the following shape:+//+// {+// host: (optional) Sets the returned URL's `host` property. Useful for+// cross-origin executors.+// protocol: (optional) Sets the returned URL's `protocol` property.+// }+function remoteExecutorUrl(uuid, options) {+ const url = new URL("/common/dispatcher/remote-executor.html", dispatcherLocation);+ url.searchParams.set("uuid", uuid);++ if (options?.host) {+ url.host = options.host;+ }++ if (options?.protocol) {+ url.protocol = options.protocol;+ }++ return url;+}++// Represents a remote executor. For more detailed explanation see `README.md`.+class RemoteContext {+ // `uuid` is a UUID string that identifies the remote context and should+ // match with the `uuid` parameter of the URL of the remote context.+ constructor(uuid) {+ this.context_id = uuid;+ }++ // Evaluates the script `expr` on the executor.+ // - If `expr` is evaluated to a Promise that is resolved with a value:+ // `execute_script()` returns a Promise resolved with the value.+ // - If `expr` is evaluated to a non-Promise value:+ // `execute_script()` returns a Promise resolved with the value.+ // - If `expr` throws an error or is evaluated to a Promise that is rejected:+ // `execute_script()` returns a rejected Promise with the error's+ // `message`.+ // Note that currently the type of error (e.g. DOMException) is not+ // preserved, except for `TypeError`.+ // The values should be able to be serialized by JSON.stringify().+ async execute_script(fn, args) {+ const receiver = token();+ await this.send({receiver: receiver, fn: fn.toString(), args: args});+ const response = JSON.parse(await receive(receiver));+ if (response.status === 'success') {+ return response.value;+ }++ // exception+ if (response.name === 'TypeError') {+ throw new TypeError(response.value);+ }+ throw new Error(response.value);+ }++ async send(msg) {+ return await send(this.context_id, JSON.stringify(msg));+ }+};++class Executor {+ constructor(uuid) {+ this.uuid = uuid;++ // If `suspend_callback` is not `null`, the executor should be suspended+ // when there are no ongoing tasks.+ this.suspend_callback = null;++ this.execute();+ }++ // Wait until there are no ongoing tasks nor fetch requests for polling+ // tasks, and then suspend the executor and call `callback()`.+ // Navigation from the executor page should be triggered inside `callback()`,+ // to avoid conflict with in-flight fetch requests.+ suspend(callback) {+ this.suspend_callback = callback;+ }++ resume() {+ }++ async execute() {+ while(true) {+ if (this.suspend_callback !== null) {+ this.suspend_callback();+ this.suspend_callback = null;+ // Wait for `resume()` to be called.+ await new Promise(resolve => this.resume = resolve);++ // Workaround for https://crbug.com/1244230.+ // Without this workaround, the executor is resumed and the fetch+ // request to poll the next task is initiated synchronously from+ // pageshow event after the page restored from BFCache, and the fetch+ // request promise is never resolved (and thus the test results in+ // timeout) due to https://crbug.com/1244230. The root cause is not yet+ // known, but setTimeout() with 0ms causes the resume triggered on+ // another task and seems to resolve the issue.+ await new Promise(resolve => setTimeout(resolve, 0));++ continue;+ }++ const task = JSON.parse(await receive(this.uuid));++ let response;+ try {+ const value = await eval(task.fn).apply(null, task.args);+ response = JSON.stringify({+ status: 'success',+ value: value+ });+ } catch(e) {+ response = JSON.stringify({+ status: 'exception',+ name: e.name,+ value: e.message+ });+ }+ await send(task.receiver, response);+ }+ }+}diff --git a/Tests/LibWeb/Text/input/wpt-import/common/dispatcher/dispatcher.py b/Tests/LibWeb/Text/input/wpt-import/common/dispatcher/dispatcher.pynew file mode 100644index 00000000000..9fe7a38ac87--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/dispatcher/dispatcher.py@@ -0,0 +1,53 @@+import json+from wptserve.utils import isomorphic_decode++# A server used to store and retrieve arbitrary data.+# This is used by: ./dispatcher.js+def main(request, response):+ # This server is configured so that is accept to receive any requests and+ # any cookies the web browser is willing to send.+ response.headers.set(b"Access-Control-Allow-Credentials", b"true")+ response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST')+ response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type')+ response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin") or '*')++ if b"cacheable" in request.GET:+ response.headers.set(b"Cache-Control", b"max-age=31536000")+ else:+ response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate')++ # CORS preflight+ if request.method == u'OPTIONS':+ return b''++ uuid = request.GET[b'uuid']+ stash = request.server.stash;++ # The stash is accessed concurrently by many clients. A lock is used to+ # avoid unterleaved read/write from different clients.+ with stash.lock:+ queue = stash.take(uuid, '/common/dispatcher') or [];++ # Push into the |uuid| queue, the requested headers.+ if b"show-headers" in request.GET:+ headers = {};+ for key, value in request.headers.items():+ headers[isomorphic_decode(key)] = isomorphic_decode(request.headers[key])+ headers = json.dumps(headers);+ queue.append(headers);+ ret = b'';++ # Push into the |uuid| queue, the posted data.+ elif request.method == u'POST':+ queue.append(request.body)+ ret = b'done'++ # Pull from the |uuid| queue, the posted data.+ else:+ if len(queue) == 0:+ ret = b'not ready'+ else:+ ret = queue.pop(0)++ stash.put(uuid, queue, '/common/dispatcher')+ return ret;diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.html b/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.htmlnew file mode 100644index 00000000000..0e8e469ab08--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy-overrides-document-policy.html@@ -0,0 +1,23 @@+<!doctype html>+<!-- Copied from https://github.com/web-platform-tests/wpt/pull/64051. Replace with an import of the upstream test once that PR merges. -->+<meta charset="utf-8">+<meta name="timeout" content="long">+<meta name="referrer" content="no-referrer">+<title>Downloading a hyperlink: referrerpolicy attribute overrides the document's referrer policy</title>+<link rel="help" href="https://html.spec.whatwg.org/multipage/links.html#downloading-hyperlinks">+<link rel="help" href="https://html.spec.whatwg.org/multipage/links.html#attr-hyperlink-referrerpolicy">+<link rel="help" href="https://github.com/whatwg/html/issues/5623">+<script src="../../../../resources/testharness.js"></script>+<script src="../../../../resources/testharnessreport.js"></script>+<script src="../../../../common/utils.js"></script>+<script src="../../../../common/dispatcher/dispatcher.js"></script>+<script src="resources/download-referrerpolicy.js"></script>+<body>+<script>+for (const tagName of ["a", "area"]) {+ downloadReferrerTest(tagName, {}, "",+ `<${tagName} download> without referrerpolicy follows the document's no-referrer policy`);+ downloadReferrerTest(tagName, { referrerpolicy: "unsafe-url" }, location.href,+ `<${tagName} download referrerpolicy=unsafe-url> overrides the document's no-referrer policy`);+}+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.html b/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.htmlnew file mode 100644index 00000000000..a9df0f40c28--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/download-referrerpolicy.html@@ -0,0 +1,29 @@+<!doctype html>+<!-- Copied from https://github.com/web-platform-tests/wpt/pull/64051. Replace with an import of the upstream test once that PR merges. -->+<meta charset="utf-8">+<meta name="timeout" content="long">+<title>Downloading a hyperlink uses the element's referrerpolicy attribute</title>+<link rel="help" href="https://html.spec.whatwg.org/multipage/links.html#downloading-hyperlinks">+<link rel="help" href="https://html.spec.whatwg.org/multipage/links.html#attr-hyperlink-referrerpolicy">+<link rel="help" href="https://github.com/whatwg/html/issues/5623">+<script src="../../../../resources/testharness.js"></script>+<script src="../../../../resources/testharnessreport.js"></script>+<script src="../../../../common/utils.js"></script>+<script src="../../../../common/dispatcher/dispatcher.js"></script>+<script src="resources/download-referrerpolicy.js"></script>+<body>+<script>+// Default policy: same-origin requests send the full URL.+for (const tagName of ["a", "area"]) {+ downloadReferrerTest(tagName, {}, location.href,+ `<${tagName} download> without referrerpolicy sends the full URL`);+ downloadReferrerTest(tagName, { referrerpolicy: "no-referrer" }, "",+ `<${tagName} download referrerpolicy=no-referrer> sends no Referer`);+ downloadReferrerTest(tagName, { referrerpolicy: "origin" }, location.origin + "/",+ `<${tagName} download referrerpolicy=origin> sends the origin`);+ downloadReferrerTest(tagName, { referrerpolicy: "invalid-policy" }, location.href,+ `<${tagName} download> ignores an invalid referrerpolicy value`);+ downloadReferrerTest(tagName, { referrerpolicy: "unsafe-url", rel: "noreferrer" }, "",+ `<${tagName} download rel=noreferrer> wins over referrerpolicy`);+}+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/resources/download-referrerpolicy.js b/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/resources/download-referrerpolicy.jsnew file mode 100644index 00000000000..3ab0d003df0--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/links/downloading-resources/resources/download-referrerpolicy.js@@ -0,0 +1,17 @@+function downloadReferrerTest(tagName, attributes, expectedReferrer, description) {+ promise_test(async t => {+ const id = token();+ const element = document.createElement(tagName);+ element.href = showRequestHeaders(location.origin, id);+ element.download = "";+ for (const [name, value] of Object.entries(attributes))+ element.setAttribute(name, value);+ document.body.append(element);+ t.add_cleanup(() => element.remove());++ element.click();++ const headers = JSON.parse(await receive(id));+ assert_equals(headers.referer ?? "", expectedReferrer, "Referer header of the download request");+ }, description);+}