Truly independent web browser
Tests/LibWeb: Import CSP tests for blocked worker script requests
Andreas Kling653a757d156c
diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.pyindex 5da91edaa9b..b0a695f3f33 100755--- a/Tests/LibWeb/Fixtures/http-test-server.py+++ b/Tests/LibWeb/Fixtures/http-test-server.py@@ -9,6 +9,7 @@ import itertoolsimport jsonimport loggingimport os+import reimport socketimport socketserverimport ssl@@ -17,6 +18,7 @@ import threadingimport timeimport urllib.parse+from collections import defaultdictfrom types import SimpleNamespacefrom typing import Anyfrom typing import Callable@@ -115,7 +117,13 @@ class WPTContext:from wptserve.stash import start_server as start_stash_serverfrom wptserve.utils import HTTPException- self.config_builder_class = ConfigBuilder+ class TestWebConfigBuilder(ConfigBuilder):+ # Our own servers serve HTTPS, not wptserve's, so keep the HTTPS ports that wptserve drops when its own TLS+ # support is not configured.+ def _get_ports(self, data):+ return defaultdict(list, {scheme: list(ports) for scheme, ports in data["ports"].items()})++ self.config_builder_class = TestWebConfigBuilderself.server_class = Serverself.request_class = Request@@ -140,6 +148,13 @@ class WPTContext:return handlerdef configure_server(self, http_ports, https_ports):+ # The HTTP(S) servers also accept WebSocket connections.+ self.ports = {"http": http_ports, "https": https_ports, "ws": http_ports[:1], "wss": https_ports}+ self.configs_by_host = {}+ 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 make_subdomains_product(subdomains, depth=2):return {".".join(labels)@@ -152,14 +167,33 @@ class WPTContext:logger = logging.getLogger("test-web-wptserve")with self.config_builder_class(logger,- browser_host="web-platform.localhost",+ browser_host=browser_host,alternate_hosts={"alt": "not-localhost.localhost"},- ports={"http": http_ports, "https": https_ports},+ ports=self.ports,subdomains=subdomains,not_subdomains=not_subdomains,check_subdomains=False,) as config:- cast(Any, self.server_class).config = config+ return config++ def apply_config_for_request(self, request):+ # test-web serves each test it loads over HTTP from a unique test-web-*.localhost host, so substitutions like+ # {{host}} and {{domains[www1]}} name that host and its subdomains, as they name the test's host in WPT.+ hostname = request.url_parts.hostname or ""+ match = re.search(r"(?:^|\.)(test-web-[0-9a-fA-F-]+\.localhost)$", hostname)+ if not match:+ return++ test_host = match.group(1)+ with self.configs_by_host_lock:+ config = self.configs_by_host.get(test_host)+ 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+ request.server.config = configdef close(self):self.stash_manager.shutdown()@@ -258,6 +292,7 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):def _create_wpt_request_response(self):server = self._test_server()request = server.wpt.request_class(self)+ server.wpt.apply_config_for_request(request)request.server._stash = server.wpt.stash_class(request.url_parts.path,server.wpt.stash_address,diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 6abc9a18868..c84b7badd80 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -795,6 +795,15 @@ Text/input/wpt-import/content-security-policy/style-src/style-src-inline-style-aText/input/wpt-import/content-security-policy/style-src/style-src-inline-style-with-csstext.htmlText/input/wpt-import/content-security-policy/unsafe-hashes/style_attribute_allowed.html+; Use the security-features Python handlers and stash to observe which subresource requests reach the server.+Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.html+Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.html+Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.html+Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.html+Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.html+Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.html+Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.html+; scroll-to-text-fragment tests all rely on loading/fetching other pages.Text/input/scroll-to-text-fragment/history.htmlText/input/scroll-to-text-fragment/searchable-text-visibility.htmldiff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.txtnew file mode 100644index 00000000000..0cb8672f9ef--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.txtnew file mode 100644index 00000000000..929e9c63085--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.txtnew file mode 100644index 00000000000..0cb8672f9ef--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.txtnew file mode 100644index 00000000000..929e9c63085--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.txtnew file mode 100644index 00000000000..929e9c63085--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.txtnew file mode 100644index 00000000000..e3bed1b8191--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.txt@@ -0,0 +1,10 @@+Harness status: OK++Found 4 tests++2 Pass+2 Fail+Pass Content Security Policy: Expects blocked for sharedworker-module to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-module to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for sharedworker-module to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for sharedworker-module to same-http origin and no-redirect redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.txtnew file mode 100644index 00000000000..7a557b0936a--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.txt@@ -0,0 +1,10 @@+Harness status: OK++Found 4 tests++2 Pass+2 Fail+Pass Content Security Policy: Expects blocked for worker-classic to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-classic to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-classic to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-classic to same-http origin and no-redirect redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.txtnew file mode 100644index 00000000000..9829ac2a624--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for worker-import to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.txtnew file mode 100644index 00000000000..929e9c63085--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.txt@@ -0,0 +1,18 @@+Harness status: OK++Found 12 tests++6 Pass+6 Fail+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context.: securitypolicyviolation+Pass Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.+Fail Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context.: securitypolicyviolation\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/common/__init__.py b/Tests/LibWeb/Text/input/wpt-import/common/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/__init__.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/resources/common.sub.js b/Tests/LibWeb/Text/input/wpt-import/common/security-features/resources/common.sub.jsnew file mode 100644index 00000000000..5c64926036b--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/resources/common.sub.js@@ -0,0 +1,1427 @@+/**+ * @fileoverview Utilities for mixed-content in web-platform-tests.+ * @author [email protected] (Kristijan Burnik)+ * Disclaimer: Some methods of other authors are annotated in the corresponding+ * method's JSDoc.+ */++// ===============================================================+// Types+// ===============================================================+// Objects of the following types are used to represent what kind of+// subresource requests should be sent with what kind of policies,+// from what kind of possibly nested source contexts.+// The objects are represented as JSON objects (not JavaScript/Python classes+// in a strict sense) to be passed between JavaScript/Python code.+//+// See also common/security-features/Types.md for high-level description.++/**+ @typedef PolicyDelivery+ @type {object}+ Referrer policy etc. can be applied/delivered in several ways.+ A PolicyDelivery object specifies what policy is delivered and how.++ @property {string} deliveryType+ Specifies how the policy is delivered.+ The valid deliveryType are:++ "attr"+ [A] DOM attributes e.g. referrerPolicy.++ "rel-noref"+ [A] <link rel="noreferrer"> (referrer-policy only).++ "http-rp"+ [B] HTTP response headers.++ "meta"+ [B] <meta> elements.++ @property {string} key+ @property {string} value+ Specifies what policy to be delivered. The valid keys are:++ "referrerPolicy"+ Referrer Policy+ https://w3c.github.io/webappsec-referrer-policy/+ Valid values are those listed in+ https://w3c.github.io/webappsec-referrer-policy/#referrer-policy+ (except that "" is represented as null/None)++ A PolicyDelivery can be specified in several ways:++ - (for [A]) Associated with an individual subresource request and+ specified in `Subresource.policies`,+ e.g. referrerPolicy attributes of DOM elements.+ This is handled in invokeRequest().++ - (for [B]) Associated with an nested environmental settings object and+ specified in `SourceContext.policies`,+ e.g. HTTP referrer-policy response headers of HTML/worker scripts.+ This is handled in server-side under /common/security-features/scope/.++ - (for [B]) Associated with the top-level HTML document.+ This is handled by the generators.d+*/++/**+ @typedef Subresource+ @type {object}+ A Subresource represents how a subresource request is sent.++ @property{SubresourceType} subresourceType+ How the subresource request is sent,+ e.g. "img-tag" for sending a request via <img src>.+ See the keys of `subresourceMap` for valid values.++ @property{string} url+ subresource's URL.+ Typically this is constructed by getRequestURLs() below.++ @property{PolicyDelivery} policyDeliveries+ Policies delivered specific to the subresource request.+*/++/**+ @typedef SourceContext+ @type {object}++ @property {string} sourceContextType+ Kind of the source context to be used.+ Valid values are the keys of `sourceContextMap` below.++ @property {Array<PolicyDelivery>} policyDeliveries+ A list of PolicyDelivery applied to the source context.+*/++// ===============================================================+// General utility functions+// ===============================================================++function timeoutPromise(t, ms) {+ return new Promise(resolve => { t.step_timeout(resolve, ms); });+}++/**+ * Normalizes the target port for use in a URL. For default ports, this is the+ * empty string (omitted port), otherwise it's a colon followed by the port+ * number. Ports 80, 443 and an empty string are regarded as default ports.+ * @param {number} targetPort The port to use+ * @return {string} The port portion for using as part of a URL.+ */+function getNormalizedPort(targetPort) {+ return ([80, 443, ""].indexOf(targetPort) >= 0) ? "" : ":" + targetPort;+}++/**+ * Creates a GUID.+ * See: https://en.wikipedia.org/wiki/Globally_unique_identifier+ * Original author: broofa (http://www.broofa.com/)+ * Sourced from: http://stackoverflow.com/a/2117523/4949715+ * @return {string} A pseudo-random GUID.+ */+function guid() {+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);+ return v.toString(16);+ });+}++/**+ * Initiates a new XHR via GET.+ * @param {string} url The endpoint URL for the XHR.+ * @param {string} responseType Optional - how should the response be parsed.+ * Default is "json".+ * See: https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype+ * @return {Promise} A promise wrapping the success and error events.+ */+function xhrRequest(url, responseType) {+ return new Promise(function(resolve, reject) {+ var xhr = new XMLHttpRequest();+ xhr.open('GET', url, true);+ xhr.responseType = responseType || "json";++ xhr.addEventListener("error", function() {+ reject(Error("Network Error"));+ });++ xhr.addEventListener("load", function() {+ if (xhr.status != 200)+ reject(Error(xhr.statusText));+ else+ resolve(xhr.response);+ });++ xhr.send();+ });+}++/**+ * Sets attributes on a given DOM element.+ * @param {DOMElement} element The element on which to set the attributes.+ * @param {object} An object with keys (serving as attribute names) and values.+ */+function setAttributes(el, attrs) {+ attrs = attrs || {}+ for (var attr in attrs) {+ if (attr !== 'src')+ el.setAttribute(attr.toLowerCase(), attrs[attr]);+ }+ // Workaround for Chromium: set <img>'s src attribute after all other+ // attributes to ensure the policy is applied.+ for (var attr in attrs) {+ if (attr === 'src')+ el.setAttribute(attr, attrs[attr]);+ }+}++/**+ * Binds to success and error events of an object wrapping them into a promise+ * available through {@code element.eventPromise}. The success event+ * resolves and error event rejects.+ * This method adds event listeners, and then removes all the added listeners+ * when one of listened event is fired.+ * @param {object} element An object supporting events on which to bind the+ * promise.+ * @param {string} resolveEventName [="load"] The event name to bind resolve to.+ * @param {string} rejectEventName [="error"] The event name to bind reject to.+ */+function bindEvents(element, resolveEventName, rejectEventName) {+ element.eventPromise =+ bindEvents2(element, resolveEventName, element, rejectEventName);+}++// Returns a promise wrapping success and error events of objects.+// This is a variant of bindEvents that can accept separate objects for each+// events and two events to reject, and doesn't set `eventPromise`.+//+// When `resolveObject`'s `resolveEventName` event (default: "load") is+// fired, the promise is resolved with the event.+//+// When `rejectObject`'s `rejectEventName` event (default: "error") or+// `rejectObject2`'s `rejectEventName2` event (default: "error") is+// fired, the promise is rejected.+//+// `rejectObject2` is optional.+function bindEvents2(resolveObject, resolveEventName, rejectObject, rejectEventName, rejectObject2, rejectEventName2) {+ return new Promise(function(resolve, reject) {+ const actualResolveEventName = resolveEventName || "load";+ const actualRejectEventName = rejectEventName || "error";+ const actualRejectEventName2 = rejectEventName2 || "error";++ const resolveHandler = function(event) {+ cleanup();+ resolve(event);+ };++ const rejectHandler = function(event) {+ // Chromium starts propagating errors from worker.onerror to+ // window.onerror. This handles the uncaught exceptions in tests.+ event.preventDefault();+ cleanup();+ reject(event);+ };++ const cleanup = function() {+ resolveObject.removeEventListener(actualResolveEventName, resolveHandler);+ rejectObject.removeEventListener(actualRejectEventName, rejectHandler);+ if (rejectObject2) {+ rejectObject2.removeEventListener(actualRejectEventName2, rejectHandler);+ }+ };++ resolveObject.addEventListener(actualResolveEventName, resolveHandler);+ rejectObject.addEventListener(actualRejectEventName, rejectHandler);+ if (rejectObject2) {+ rejectObject2.addEventListener(actualRejectEventName2, rejectHandler);+ }+ });+}++/**+ * Creates a new DOM element.+ * @param {string} tagName The type of the DOM element.+ * @param {object} attrs A JSON with attributes to apply to the element.+ * @param {DOMElement} parent Optional - an existing DOM element to append to+ * If not provided, the returned element will remain orphaned.+ * @param {boolean} doBindEvents Optional - Whether to bind to load and error+ * events and provide the promise wrapping the events via the element's+ * {@code eventPromise} property. Default value evaluates to false.+ * @return {DOMElement} The newly created DOM element.+ */+function createElement(tagName, attrs, parentNode, doBindEvents) {+ var element = document.createElement(tagName);++ if (doBindEvents) {+ bindEvents(element);+ if (element.tagName == "IFRAME" && !('srcdoc' in attrs || 'src' in attrs)) {+ // If we're loading a frame, ensure we spin the event loop after load to+ // paper over the different event timing in Gecko vs Blink/WebKit+ // see https://github.com/whatwg/html/issues/4965+ element.eventPromise = element.eventPromise.then(() => {+ return new Promise(resolve => setTimeout(resolve, 0))+ });+ }+ }+ // We set the attributes after binding to events to catch any+ // event-triggering attribute changes. E.g. form submission.+ //+ // But be careful with images: unlike other elements they will start the load+ // as soon as the attr is set, even if not in the document yet, and sometimes+ // complete it synchronously, so the append doesn't have the effect we want.+ // So for images, we want to set the attrs after appending, whereas for other+ // elements we want to do it before appending.+ var isImg = (tagName == "img");+ if (!isImg)+ setAttributes(element, attrs);++ if (parentNode)+ parentNode.appendChild(element);++ if (isImg)+ setAttributes(element, attrs);++ return element;+}++function createRequestViaElement(tagName, attrs, parentNode) {+ return createElement(tagName, attrs, parentNode, true).eventPromise;+}++function wrapResult(server_data) {+ if (typeof(server_data) === "string") {+ throw server_data;+ }+ return {+ referrer: server_data.headers.referer,+ headers: server_data.headers+ }+}++// ===============================================================+// Subresources+// ===============================================================++/**+ @typedef RequestResult+ @type {object}+ Represents the result of sending an request.+ All properties are optional. See the comments for+ requestVia*() and invokeRequest() below to see which properties are set.++ @property {Array<Object<string, string>>} headers+ HTTP request headers sent to server.+ @property {string} referrer - Referrer.+ @property {string} location - The URL of the subresource.+ @property {string} sourceContextUrl+ the URL of the global object where the actual request is sent.+*/++/**+ requestVia*(url, additionalAttributes) functions send a subresource+ request from the current environment settings object.++ @param {string} url+ The URL of the subresource.+ @param {Object<string, string>} additionalAttributes+ Additional attributes set to DOM elements+ (element-initiated requests only).++ @returns {Promise} that are resolved with a RequestResult object+ on successful requests.++ - Category 1:+ `headers`: set.+ `referrer`: set via `document.referrer`.+ `location`: set via `document.location`.+ See `template/document.html.template`.+ - Category 2:+ `headers`: set.+ `referrer`: set to `headers.referer` by `wrapResult()`.+ `location`: not set.+ - Category 3:+ All the keys listed above are NOT set.+ `sourceContextUrl` is not set here.++ -------------------------------- -------- --------------------------+ Function name Category Used in+ -------- ------- ---------+ referrer mixed- upgrade-+ policy content insecure-+ policy content request+ -------------------------------- -------- -------- ------- ---------+ requestViaAnchor 1 Y Y -+ requestViaArea 1 Y Y -+ requestViaAudio 3 - Y -+ requestViaDedicatedWorker 2 Y Y Y+ requestViaFetch 2 Y Y -+ requestViaForm 2 - Y -+ requestViaIframe 1 Y Y -+ requestViaImage 2 Y Y -+ requestViaLinkPrefetch 3 - Y -+ requestViaLinkStylesheet 3 - Y -+ requestViaObject 3 - Y -+ requestViaPicture 3 - Y -+ requestViaScript 2 Y Y -+ requestViaSendBeacon 3 - Y -+ requestViaSharedWorker 2 Y Y Y+ requestViaVideo 3 - Y -+ requestViaWebSocket 3 - Y -+ requestViaWorklet 3 - Y Y+ requestViaXhr 2 Y Y -+ -------------------------------- -------- -------- ------- ---------+*/++/**+ * Creates a new iframe, binds load and error events, sets the src attribute and+ * appends it to {@code document.body} .+ * @param {string} url The src for the iframe.+ * @return {Promise} The promise for success/error events.+ */+function requestViaIframe(url, additionalAttributes) {+ const iframe = createElement(+ "iframe",+ Object.assign({"src": url}, additionalAttributes),+ document.body,+ false);+ return bindEvents2(window, "message", iframe, "error", window, "error")+ .then(event => {+ if (event.source !== iframe.contentWindow)+ return Promise.reject(new Error('Unexpected event.source'));+ return event.data;+ });+}++/**+ * Creates a new image, binds load and error events, sets the src attribute and+ * appends it to {@code document.body} .+ * @param {string} url The src for the image.+ * @return {Promise} The promise for success/error events.+ */+function requestViaImage(url, additionalAttributes) {+ const img = createElement(+ "img",+ // crossOrigin attribute is added to read the pixel data of the response.+ Object.assign({"src": url, "crossOrigin": "Anonymous"}, additionalAttributes),+ document.body, true);+ return img.eventPromise.then(() => wrapResult(decodeImageData(img)));+}++// Helper for requestViaImage().+function decodeImageData(img) {+ var canvas = document.createElement("canvas");+ var context = canvas.getContext('2d');+ context.drawImage(img, 0, 0);+ var imgData = context.getImageData(0, 0, img.clientWidth, img.clientHeight);+ const rgba = imgData.data;++ let decodedBytes = new Uint8ClampedArray(rgba.length);+ let decodedLength = 0;++ for (var i = 0; i + 12 <= rgba.length; i += 12) {+ // A single byte is encoded in three pixels. 8 pixel octets (among+ // 9 octets = 3 pixels * 3 channels) are used to encode 8 bits,+ // the most significant bit first, where `0` and `255` in pixel values+ // represent `0` and `1` in bits, respectively.+ // This encoding is used to avoid errors due to different color spaces.+ const bits = [];+ for (let j = 0; j < 3; ++j) {+ bits.push(rgba[i + j * 4 + 0]);+ bits.push(rgba[i + j * 4 + 1]);+ bits.push(rgba[i + j * 4 + 2]);+ // rgba[i + j * 4 + 3]: Skip alpha channel.+ }+ // The last one element is not used.+ bits.pop();++ // Decode a single byte.+ let byte = 0;+ for (let j = 0; j < 8; ++j) {+ byte <<= 1;+ if (bits[j] >= 128)+ byte |= 1;+ }++ // Zero is the string terminator.+ if (byte == 0)+ break;++ decodedBytes[decodedLength++] = byte;+ }++ // Remove trailing nulls from data.+ decodedBytes = decodedBytes.subarray(0, decodedLength);+ var string_data = (new TextDecoder("ascii")).decode(decodedBytes);++ return JSON.parse(string_data);+}++/**+ * Initiates a new XHR GET request to provided URL.+ * @param {string} url The endpoint URL for the XHR.+ * @return {Promise} The promise for success/error events.+ */+function requestViaXhr(url) {+ return xhrRequest(url).then(result => wrapResult(result));+}++/**+ * Initiates a new GET request to provided URL via the Fetch API.+ * @param {string} url The endpoint URL for the Fetch.+ * @return {Promise} The promise for success/error events.+ */+function requestViaFetch(url) {+ return fetch(url)+ .then(res => res.json())+ .then(j => wrapResult(j));+}++function dedicatedWorkerUrlThatFetches(url) {+ return `data:text/javascript,+ fetch('${url}')+ .then(r => r.json())+ .then(j => postMessage(j))+ .catch((e) => postMessage(e.message));`;+}++function workerUrlThatImports(url, additionalAttributes) {+ let csp = "";+ if (additionalAttributes && additionalAttributes.contentSecurityPolicy) {+ csp=`&contentSecurityPolicy=${additionalAttributes.contentSecurityPolicy}`;+ }+ return `/common/security-features/subresource/static-import.py` ++ `?import_url=${encodeURIComponent(url)}${csp}`;+}++function workerDataUrlThatImports(url) {+ return `data:text/javascript,import '${url}';`;+}++/**+ * Creates a new Worker, binds message and error events wrapping them into.+ * {@code worker.eventPromise} and posts an empty string message to start+ * the worker.+ * @param {string} url The endpoint URL for the worker script.+ * @param {object} options The options for Worker constructor.+ * @return {Promise} The promise for success/error events.+ */+function requestViaDedicatedWorker(url, options) {+ var worker;+ try {+ worker = new Worker(url, options);+ } catch (e) {+ return Promise.reject(e);+ }+ worker.postMessage('');+ return bindEvents2(worker, "message", worker, "error")+ .then(event => wrapResult(event.data));+}++function requestViaSharedWorker(url, options) {+ var worker;+ try {+ worker = new SharedWorker(url, options);+ } catch(e) {+ return Promise.reject(e);+ }+ const promise = bindEvents2(worker.port, "message", worker, "error")+ .then(event => wrapResult(event.data));+ worker.port.start();+ return promise;+}++// Returns a reference to a worklet object corresponding to a given type.+function get_worklet(type) {+ if (type == 'animation')+ return CSS.animationWorklet;+ if (type == 'layout')+ return CSS.layoutWorklet;+ if (type == 'paint')+ return CSS.paintWorklet;+ if (type == 'audio')+ return new OfflineAudioContext(2,44100*40,44100).audioWorklet;++ throw new Error('unknown worklet type is passed.');+}++function requestViaWorklet(type, url) {+ try {+ return get_worklet(type).addModule(url);+ } catch (e) {+ return Promise.reject(e);+ }+}++/**+ * Creates a navigable element with the name `navigableElementName`+ * (<a>, <area>, or <form>) under `parentNode`, and+ * performs a navigation by `trigger()` (e.g. clicking <a>).+ * To avoid navigating away from the current execution context,+ * a target attribute is set to point to a new helper iframe.+ * @param {string} navigableElementName+ * @param {object} additionalAttributes The attributes of the navigable element.+ * @param {DOMElement} parentNode+ * @param {function(DOMElement} trigger A callback called after the navigable+ * element is inserted and should trigger navigation using the element.+ * @return {Promise} The promise for success/error events.+ */+function requestViaNavigable(navigableElementName, additionalAttributes,+ parentNode, trigger) {+ const name = guid();++ const iframe =+ createElement("iframe", {"name": name, "id": name}, parentNode, false);++ const navigable = createElement(+ navigableElementName,+ Object.assign({"target": name}, additionalAttributes),+ parentNode, false);++ const promise =+ bindEvents2(window, "message", iframe, "error", window, "error")+ .then(event => {+ if (event.source !== iframe.contentWindow)+ return Promise.reject(new Error('Unexpected event.source'));+ return event.data;+ });+ trigger(navigable);+ return promise;+}++/**+ * Creates a new anchor element, appends it to {@code document.body} and+ * performs the navigation.+ * @param {string} url The URL to navigate to.+ * @return {Promise} The promise for success/error events.+ */+function requestViaAnchor(url, additionalAttributes) {+ return requestViaNavigable(+ "a",+ Object.assign({"href": url, "innerHTML": "Link to resource"},+ additionalAttributes),+ document.body, a => a.click());+}++/**+ * Creates a new area element, appends it to {@code document.body} and performs+ * the navigation.+ * @param {string} url The URL to navigate to.+ * @return {Promise} The promise for success/error events.+ */+function requestViaArea(url, additionalAttributes) {+ // TODO(kristijanburnik): Append to map and add image.+ return requestViaNavigable(+ "area",+ Object.assign({"href": url}, additionalAttributes),+ document.body, area => area.click());+}++/**+ * Creates a new script element, sets the src to url, and appends it to+ * {@code document.body}.+ * @param {string} url The src URL.+ * @return {Promise} The promise for success/error events.+ */+function requestViaScript(url, additionalAttributes) {+ const script = createElement(+ "script",+ Object.assign({"src": url}, additionalAttributes),+ document.body,+ false);++ return bindEvents2(window, "message", script, "error", window, "error")+ .then(event => wrapResult(event.data));+}++/**+ * Creates a new script element that performs a dynamic import to `url`, and+ * appends the script element to {@code document.body}.+ * @param {string} url The src URL.+ * @return {Promise} The promise for success/error events.+ */+function requestViaDynamicImport(url, additionalAttributes) {+ const scriptUrl = `data:text/javascript,import("${url}");`;+ const script = createElement(+ "script",+ Object.assign({"src": scriptUrl}, additionalAttributes),+ document.body,+ false);++ return bindEvents2(window, "message", script, "error", window, "error")+ .then(event => wrapResult(event.data));+}++/**+ * Creates a new form element, sets attributes, appends it to+ * {@code document.body} and submits the form.+ * @param {string} url The URL to submit to.+ * @return {Promise} The promise for success/error events.+ */+function requestViaForm(url, additionalAttributes) {+ return requestViaNavigable(+ "form",+ Object.assign({"action": url, "method": "POST"}, additionalAttributes),+ document.body, form => form.submit());+}++/**+ * Creates a new link element for a stylesheet, binds load and error events,+ * sets the href to url and appends it to {@code document.head}.+ * @param {string} url The URL for a stylesheet.+ * @return {Promise} The promise for success/error events.+ */+function requestViaLinkStylesheet(url) {+ return createRequestViaElement("link",+ {"rel": "stylesheet", "href": url},+ document.head);+}++/**+ * Creates a new link element for a prefetch, binds load and error events, sets+ * the href to url and appends it to {@code document.head}.+ * @param {string} url The URL of a resource to prefetch.+ * @return {Promise} The promise for success/error events.+ */+function requestViaLinkPrefetch(url) {+ var link = document.createElement('link');+ if (link.relList && link.relList.supports && link.relList.supports("prefetch")) {+ return createRequestViaElement("link",+ {"rel": "prefetch", "href": url},+ document.head);+ } else {+ return Promise.reject("This browser does not support 'prefetch'.");+ }+}++/**+ * Initiates a new beacon request.+ * @param {string} url The URL of a resource to prefetch.+ * @return {Promise} The promise for success/error events.+ */+async function requestViaSendBeacon(url) {+ function wait(ms) {+ return new Promise(resolve => step_timeout(resolve, ms));+ }+ if (!navigator.sendBeacon(url)) {+ // If mixed-content check fails, it should return false.+ throw new Error('sendBeacon() fails.');+ }+ // We don't have a means to see the result of sendBeacon() request+ // for sure. Let's wait for a while and let the generic test function+ // ask the server for the result.+ await wait(500);+ return 'allowed';+}++/**+ * Creates a new media element with a child source element, binds loadeddata and+ * error events, sets attributes and appends to document.body.+ * @param {string} type The type of the media element (audio/video/picture).+ * @param {object} media_attrs The attributes for the media element.+ * @param {object} source_attrs The attributes for the child source element.+ * @return {DOMElement} The newly created media element.+ */+function createMediaElement(type, media_attrs, source_attrs) {+ var mediaElement = createElement(type, {});++ var sourceElement = createElement("source", {});++ mediaElement.eventPromise = new Promise(function(resolve, reject) {+ mediaElement.addEventListener("loadeddata", function (e) {+ resolve(e);+ });++ // Safari doesn't fire an `error` event when blocking mixed content.+ mediaElement.addEventListener("stalled", function(e) {+ reject(e);+ });++ sourceElement.addEventListener("error", function(e) {+ reject(e);+ });+ });++ setAttributes(mediaElement, media_attrs);+ setAttributes(sourceElement, source_attrs);++ mediaElement.appendChild(sourceElement);+ document.body.appendChild(mediaElement);++ return mediaElement;+}++/**+ * Creates a new video element, binds loadeddata and error events, sets+ * attributes and source URL and appends to {@code document.body}.+ * @param {string} url The URL of the video.+ * @return {Promise} The promise for success/error events.+ */+function requestViaVideo(url) {+ return createMediaElement("video",+ {},+ {"src": url}).eventPromise;+}++/**+ * Creates a new audio element, binds loadeddata and error events, sets+ * attributes and source URL and appends to {@code document.body}.+ * @param {string} url The URL of the audio.+ * @return {Promise} The promise for success/error events.+ */+function requestViaAudio(url) {+ return createMediaElement("audio",+ {},+ {"type": "audio/wav", "src": url}).eventPromise;+}++/**+ * Creates a new picture element, binds loadeddata and error events, sets+ * attributes and source URL and appends to {@code document.body}. Also+ * creates new image element appending it to the picture+ * @param {string} url The URL of the image for the source and image elements.+ * @return {Promise} The promise for success/error events.+ */+function requestViaPicture(url) {+ var picture = createMediaElement("picture", {}, {"srcset": url,+ "type": "image/png"});+ return createRequestViaElement("img", {"src": url}, picture);+}++/**+ * Creates a new object element, binds load and error events, sets the data to+ * url, and appends it to {@code document.body}.+ * @param {string} url The data URL.+ * @return {Promise} The promise for success/error events.+ */+function requestViaObject(url) {+ return createRequestViaElement("object", {"data": url, "type": "text/html"}, document.body);+}++/**+ * Creates a new WebSocket pointing to {@code url} and sends a message string+ * "echo". The {@code message} and {@code error} events are triggering the+ * returned promise resolve/reject events.+ * @param {string} url The URL for WebSocket to connect to.+ * @return {Promise} The promise for success/error events.+ */+function requestViaWebSocket(url) {+ return new Promise(function(resolve, reject) {+ var websocket = new WebSocket(url);++ websocket.addEventListener("message", function(e) {+ resolve(e.data);+ });++ websocket.addEventListener("open", function(e) {+ websocket.send("echo");+ });++ websocket.addEventListener("error", function(e) {+ reject(e)+ });+ })+ .then(data => {+ return JSON.parse(data);+ });+}++/**+ * Creates a svg anchor element and the corresponding svg setup, appends the+ * setup to {@code document.body} and performs the navigation.+ * @param {string} url The URL to navigate to.+ * @return {Promise} The promise for success/error events.+ */+function requestViaSVGAnchor(url, additionalAttributes) {+ const name = guid();++ const iframe =+ createElement("iframe", { "name": name, "id": name }, document.body, false);++ // Create SVG container+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");++ // Create SVG anchor element+ const svgAnchor = document.createElementNS("http://www.w3.org/2000/svg", "a");+ const link_attributes = Object.assign({ "href": url, "target": name }, additionalAttributes);+ setAttributes(svgAnchor, link_attributes);++ // Add some text content for the anchor+ const text = document.createElementNS("http://www.w3.org/2000/svg", "text");+ text.setAttribute("y", "50");+ text.textContent = "SVG Link to resource";++ svgAnchor.appendChild(text);+ svg.appendChild(svgAnchor);+ document.body.appendChild(svg);++ const promise =+ bindEvents2(window, "message", iframe, "error", window, "error")+ .then(event => {+ if (event.source !== iframe.contentWindow)+ return Promise.reject(new Error('Unexpected event.source'));+ return event.data;+ });++ // Simulate a click event on the SVG anchor+ const event = new MouseEvent('click', {+ view: window,+ bubbles: true,+ cancelable: true+ });+ svgAnchor.dispatchEvent(event);++ return promise;+}++/**+ * Creates a MathML anchor element and the corresponding MathML setup, appends+ * the setup to {@code document.body} and performs the navigation.+ * @param {string} url The URL to navigate to.+ * @return {Promise} The promise for success/error events.+ */+function requestViaMathMLAnchor(url, additionalAttributes) {+ const name = guid();++ const iframe =+ createElement('iframe', {'name': name, 'id': name}, document.body, false);++ // Create MathML container+ const math =+ document.createElementNS('http://www.w3.org/1998/Math/MathML', 'math');++ // Create MathML anchor element+ const mathmlAnchor =+ document.createElementNS('http://www.w3.org/1998/Math/MathML', 'a');+ const link_attributes =+ Object.assign({'href': url, 'target': name}, additionalAttributes);+ setAttributes(mathmlAnchor, link_attributes);++ // Add text content+ mathmlAnchor.textContent = 'MathML Link to resource';++ math.appendChild(mathmlAnchor);+ document.body.appendChild(math);++ const promise =+ bindEvents2(window, 'message', iframe, 'error', window, 'error')+ .then(event => {+ if (event.source !== iframe.contentWindow)+ return Promise.reject(new Error('Unexpected event.source'));+ return event.data;+ });++ // Simulate a click event on the MathML anchor+ const event =+ new MouseEvent('click', {view: window, bubbles: true, cancelable: true});+ mathmlAnchor.dispatchEvent(event);++ return promise;+}++/**+ @typedef SubresourceType+ @type {string}++ Represents how a subresource is sent.+ The keys of `subresourceMap` below are the valid values.+*/++// Subresource paths and invokers.+const subresourceMap = {+ "a-tag": {+ path: "/common/security-features/subresource/document.py",+ invoker: requestViaAnchor,+ },+ "area-tag": {+ path: "/common/security-features/subresource/document.py",+ invoker: requestViaArea,+ },+ "audio-tag": {+ path: "/common/security-features/subresource/audio.py",+ invoker: requestViaAudio,+ },+ "beacon": {+ path: "/common/security-features/subresource/empty.py",+ invoker: requestViaSendBeacon,+ },+ "fetch": {+ path: "/common/security-features/subresource/xhr.py",+ invoker: requestViaFetch,+ },+ "form-tag": {+ path: "/common/security-features/subresource/document.py",+ invoker: requestViaForm,+ },+ "iframe-tag": {+ path: "/common/security-features/subresource/document.py",+ invoker: requestViaIframe,+ },+ "img-tag": {+ path: "/common/security-features/subresource/image.py",+ invoker: requestViaImage,+ },+ "link-css-tag": {+ path: "/common/security-features/subresource/empty.py",+ invoker: requestViaLinkStylesheet,+ },+ "link-prefetch-tag": {+ path: "/common/security-features/subresource/empty.py",+ invoker: requestViaLinkPrefetch,+ },+ "mathml-a-tag": {+ path: "/common/security-features/subresource/document.py",+ invoker: requestViaMathMLAnchor,+ },+ "object-tag": {+ path: "/common/security-features/subresource/empty.py",+ invoker: requestViaObject,+ },+ "picture-tag": {+ path: "/common/security-features/subresource/image.py",+ invoker: requestViaPicture,+ },+ "script-tag": {+ path: "/common/security-features/subresource/script.py",+ invoker: requestViaScript,+ },+ "script-tag-dynamic-import": {+ path: "/common/security-features/subresource/script.py",+ invoker: requestViaDynamicImport,+ },+ "svg-a-tag": {+ path: "/common/security-features/subresource/document.py",+ invoker: requestViaSVGAnchor,+ },+ "video-tag": {+ path: "/common/security-features/subresource/video.py",+ invoker: requestViaVideo,+ },+ "xhr": {+ path: "/common/security-features/subresource/xhr.py",+ invoker: requestViaXhr,+ },++ "worker-classic": {+ path: "/common/security-features/subresource/worker.py",+ invoker: url => requestViaDedicatedWorker(url),+ },+ "worker-module": {+ path: "/common/security-features/subresource/worker.py",+ invoker: url => requestViaDedicatedWorker(url, {type: "module"}),+ },+ "worker-import": {+ path: "/common/security-features/subresource/worker.py",+ invoker: (url, additionalAttributes) =>+ requestViaDedicatedWorker(workerUrlThatImports(url, additionalAttributes), {type: "module"}),+ },+ "worker-import-data": {+ path: "/common/security-features/subresource/worker.py",+ invoker: url =>+ requestViaDedicatedWorker(workerDataUrlThatImports(url), {type: "module"}),+ },+ "sharedworker-classic": {+ path: "/common/security-features/subresource/shared-worker.py",+ invoker: url => requestViaSharedWorker(url),+ },+ "sharedworker-module": {+ path: "/common/security-features/subresource/shared-worker.py",+ invoker: url => requestViaSharedWorker(url, {type: "module"}),+ },+ "sharedworker-import": {+ path: "/common/security-features/subresource/shared-worker.py",+ invoker: (url, additionalAttributes) =>+ requestViaSharedWorker(workerUrlThatImports(url, additionalAttributes), {type: "module"}),+ },+ "sharedworker-import-data": {+ path: "/common/security-features/subresource/shared-worker.py",+ invoker: url =>+ requestViaSharedWorker(workerDataUrlThatImports(url), {type: "module"}),+ },++ "websocket": {+ path: "/stash_responder",+ invoker: requestViaWebSocket,+ },+};+for (const workletType of ['animation', 'audio', 'layout', 'paint']) {+ subresourceMap[`worklet-${workletType}`] = {+ path: "/common/security-features/subresource/worker.py",+ invoker: url => requestViaWorklet(workletType, url)+ };+ subresourceMap[`worklet-${workletType}-import-data`] = {+ path: "/common/security-features/subresource/worker.py",+ invoker: url =>+ requestViaWorklet(workletType, workerDataUrlThatImports(url))+ };+}++/**+ @typedef RedirectionType+ @type {string}++ Represents what redirects should occur to the subresource request+ after initial request.+ See preprocess_redirection() in+ /common/security-features/subresource/subresource.py for valid values.+*/++/**+ Construct subresource (and related) origin.++ @param {string} originType+ @returns {object} the origin of the subresource.+*/+function getSubresourceOrigin(originType) {+ const httpProtocol = "http";+ const httpsProtocol = "https";+ const wsProtocol = "ws";+ const wssProtocol = "wss";++ const sameOriginHost = "{{host}}";+ const crossOriginHost = "{{domains[www1]}}";++ // These values can evaluate to either empty strings or a ":port" string.+ const httpPort = getNormalizedPort(parseInt("{{ports[http][0]}}", 10));+ const httpsRawPort = parseInt("{{ports[https][0]}}", 10);+ const httpsPort = getNormalizedPort(httpsRawPort);+ const wsPort = getNormalizedPort(parseInt("{{ports[ws][0]}}", 10));+ const wssRawPort = parseInt("{{ports[wss][0]}}", 10);+ const wssPort = getNormalizedPort(wssRawPort);++ /**+ @typedef OriginType+ @type {string}++ Represents the origin of the subresource request URL.+ The keys of `originMap` below are the valid values.++ Note that there can be redirects from the specified origin+ (see RedirectionType), and thus the origin of the subresource+ response URL might be different from what is specified by OriginType.+ */+ const originMap = {+ "same-https": httpsProtocol + "://" + sameOriginHost + httpsPort,+ "same-http": httpProtocol + "://" + sameOriginHost + httpPort,+ "cross-https": httpsProtocol + "://" + crossOriginHost + httpsPort,+ "cross-http": httpProtocol + "://" + crossOriginHost + httpPort,+ "same-wss": wssProtocol + "://" + sameOriginHost + wssPort,+ "same-ws": wsProtocol + "://" + sameOriginHost + wsPort,+ "cross-wss": wssProtocol + "://" + crossOriginHost + wssPort,+ "cross-ws": wsProtocol + "://" + crossOriginHost + wsPort,++ // The following origin types are used for upgrade-insecure-requests and+ // mixed content tests tests. These rely on some unintuitive cleverness due+ // to WPT's test setup: 'Upgrade-Insecure-Requests' does not upgrade the+ // port number, so we use URLs in the form `http://[domain]:[https-port]`,+ // which will be upgraded to `https://[domain]:[https-port]`. If the upgrade+ // fails, the load will fail, as we don't serve HTTP over the secure port.+ "same-http-downgrade":+ httpProtocol + "://" + sameOriginHost + ":" + httpsRawPort,+ "cross-http-downgrade":+ httpProtocol + "://" + crossOriginHost + ":" + httpsRawPort,+ "same-ws-downgrade":+ wsProtocol + "://" + sameOriginHost + ":" + wssRawPort,+ "cross-ws-downgrade":+ wsProtocol + "://" + crossOriginHost + ":" + wssRawPort,+ };++ return originMap[originType];+}++/**+ Construct subresource (and related) URLs.++ @param {SubresourceType} subresourceType+ @param {OriginType} originType+ @param {RedirectionType} redirectionType+ @param {boolean} checkScheme Optional+ @returns {object} with following properties:+ {string} testUrl+ The subresource request URL.+ {string} announceUrl+ {string} assertUrl+ The URLs to be used for detecting whether `testUrl` is actually sent+ to the server.+ 1. Fetch `announceUrl` first,+ 2. then possibly fetch `testUrl`, and+ 3. finally fetch `assertUrl`.+ The fetch result of `assertUrl` should indicate whether `testUrl` is+ actually sent to the server or not, or if `checkScheme` is specified+ and this is a insecure origin type, whether the request was upgraded or+ not.+*/+function getRequestURLs(subresourceType, originType, redirectionType, checkScheme = false) {+ const key = guid();+ const value = guid();++ // We use the same stash path for both HTTP/S and WS/S stash requests.+ const stashPath = encodeURIComponent("/mixed-content");++ const stashEndpoint = "/common/security-features/subresource/xhr.py?key=" ++ key + "&path=" + stashPath;+ return {+ testUrl:+ getSubresourceOrigin(originType) ++ subresourceMap[subresourceType].path ++ "?redirection=" + encodeURIComponent(redirectionType) ++ "&action=" + (checkScheme && !["https", "wss"].includes(originType.split("-").pop()) ? "check-scheme" : "purge") ++ "&key=" + key ++ "&path=" + stashPath,+ announceUrl: stashEndpoint + "&action=put&value=" + value,+ assertUrl: stashEndpoint + "&action=take",+ };+}++// ===============================================================+// Source Context+// ===============================================================+// Requests can be sent from several source contexts,+// such as the main documents, iframes, workers, or so,+// possibly nested, and possibly with <meta>/http headers added.+// invokeRequest() and invokeFrom*() functions handles+// SourceContext-related setup in client-side.++/**+ invokeRequest() invokes a subresource request+ (specified as `subresource`)+ from a (possibly nested) environment settings object+ (specified as `sourceContextList`).++ For nested contexts, invokeRequest() calls an invokeFrom*() function+ that creates a nested environment settings object using+ /common/security-features/scope/, which calls invokeRequest()+ again inside the nested environment settings object.+ This cycle continues until all specified+ nested environment settings object are created, and+ finally invokeRequest() calls a requestVia*() function to start the+ subresource request from the inner-most environment settings object.++ @param {Subresource} subresource+ @param {Array<SourceContext>} sourceContextList++ @returns {Promise} A promise that is resolved with an RequestResult object.+ `sourceContextUrl` is always set. For whether other properties are set,+ see the comments for requestVia*() above.+*/+function invokeRequest(subresource, sourceContextList) {+ if (sourceContextList.length === 0) {+ // No further nested global objects. Send the subresource request here.++ const additionalAttributes = {};+ /** @type {PolicyDelivery} policyDelivery */+ for (const policyDelivery of (subresource.policyDeliveries || [])) {+ // Depending on the delivery method, extend the subresource element with+ // these attributes.+ if (policyDelivery.deliveryType === "attr") {+ additionalAttributes[policyDelivery.key] = policyDelivery.value;+ } else if (policyDelivery.deliveryType === "rel-noref") {+ additionalAttributes["rel"] = "noreferrer";+ } else if (policyDelivery.deliveryType === "http-rp") {+ additionalAttributes[policyDelivery.key] = policyDelivery.value;+ } else if (policyDelivery.deliveryType === "meta") {+ additionalAttributes[policyDelivery.key] = policyDelivery.value;+ }+ }++ return subresourceMap[subresource.subresourceType].invoker(+ subresource.url,+ additionalAttributes)+ .then(result => Object.assign(+ {sourceContextUrl: location.toString()},+ result));+ }++ // Defines invokers for each valid SourceContext.sourceContextType.+ const sourceContextMap = {+ "srcdoc": { // <iframe srcdoc></iframe>+ invoker: invokeFromIframe,+ },+ "iframe": { // <iframe src="same-origin-URL"></iframe>+ invoker: invokeFromIframe,+ },+ "iframe-blank": { // <iframe></iframe>+ invoker: invokeFromIframe,+ },+ "iframe-data": {+ invoker: invokeFromIframe,+ },+ "worker-classic": {+ // Classic dedicated worker loaded from same-origin.+ invoker: invokeFromWorker.bind(undefined, "worker", false, {}),+ },+ "worker-classic-data": {+ // Classic dedicated worker loaded from data: URL.+ invoker: invokeFromWorker.bind(undefined, "worker", true, {}),+ },+ "worker-module": {+ // Module dedicated worker loaded from same-origin.+ invoker: invokeFromWorker.bind(undefined, "worker", false, {type: 'module'}),+ },+ "worker-module-data": {+ // Module dedicated worker loaded from data: URL.+ invoker: invokeFromWorker.bind(undefined, "worker", true, {type: 'module'}),+ },+ "sharedworker-classic": {+ // Classic shared worker loaded from same-origin.+ invoker: invokeFromWorker.bind(undefined, "sharedworker", false, {}),+ },+ "sharedworker-classic-data": {+ // Classic shared worker loaded from data: URL.+ invoker: invokeFromWorker.bind(undefined, "sharedworker", true, {}),+ },+ "sharedworker-module": {+ // Module shared worker loaded from same-origin.+ invoker: invokeFromWorker.bind(undefined, "sharedworker", false, {type: 'module'}),+ },+ "sharedworker-module-data": {+ // Module shared worker loaded from data: URL.+ invoker: invokeFromWorker.bind(undefined, "sharedworker", true, {type: 'module'}),+ },+ };++ return sourceContextMap[sourceContextList[0].sourceContextType].invoker(+ subresource, sourceContextList);+}++// Quick hack to expose invokeRequest when common.sub.js is loaded either+// as a classic or module script.+self.invokeRequest = invokeRequest;++/**+ invokeFrom*() functions are helper functions with the same parameters+ and return values as invokeRequest(), that are tied to specific types+ of top-most environment settings objects.+ For example, invokeFromIframe() is the helper function for the cases where+ sourceContextList[0] is an iframe.+*/++/**+ @param {string} workerType+ "worker" (for dedicated worker) or "sharedworker".+ @param {boolean} isDataUrl+ true if the worker script is loaded from data: URL.+ Otherwise, the script is loaded from same-origin.+ @param {object} workerOptions+ The `options` argument for Worker constructor.++ Other parameters and return values are the same as those of invokeRequest().+*/+function invokeFromWorker(workerType, isDataUrl, workerOptions,+ subresource, sourceContextList) {+ const currentSourceContext = sourceContextList[0];+ let workerUrl =+ "/common/security-features/scope/worker.py?policyDeliveries=" ++ encodeURIComponent(JSON.stringify(+ currentSourceContext.policyDeliveries || []));+ if (workerOptions.type === 'module') {+ workerUrl += "&type=module";+ }++ let promise;+ if (isDataUrl) {+ promise = fetch(workerUrl)+ .then(r => r.text())+ .then(source => {+ return 'data:text/javascript;base64,' + btoa(source);+ });+ } else {+ promise = Promise.resolve(workerUrl);+ }++ return promise+ .then(url => {+ if (workerType === "worker") {+ const worker = new Worker(url, workerOptions);+ worker.postMessage({subresource: subresource,+ sourceContextList: sourceContextList.slice(1)});+ return bindEvents2(worker, "message", worker, "error", window, "error");+ } else if (workerType === "sharedworker") {+ const worker = new SharedWorker(url, workerOptions);+ worker.port.start();+ worker.port.postMessage({subresource: subresource,+ sourceContextList: sourceContextList.slice(1)});+ return bindEvents2(worker.port, "message", worker, "error", window, "error");+ } else {+ throw new Error('Invalid worker type: ' + workerType);+ }+ })+ .then(event => {+ if (event.data.error)+ return Promise.reject(event.data.error);+ return event.data;+ });+}++function invokeFromIframe(subresource, sourceContextList) {+ const currentSourceContext = sourceContextList[0];+ const frameUrl =+ "/common/security-features/scope/document.py?policyDeliveries=" ++ encodeURIComponent(JSON.stringify(+ currentSourceContext.policyDeliveries || []));++ let iframe;+ let promise;+ if (currentSourceContext.sourceContextType === 'srcdoc') {+ promise = fetch(frameUrl)+ .then(r => r.text())+ .then(srcdoc => {+ iframe = createElement(+ "iframe", {srcdoc: srcdoc}, document.body, true);+ return iframe.eventPromise;+ });+ } else if (currentSourceContext.sourceContextType === 'iframe') {+ iframe = createElement("iframe", {src: frameUrl}, document.body, true);+ promise = iframe.eventPromise;+ } else if (currentSourceContext.sourceContextType === 'iframe-blank') {+ let frameContent;+ promise = fetch(frameUrl)+ .then(r => r.text())+ .then(t => {+ frameContent = t;+ iframe = createElement("iframe", {}, document.body, true);+ return iframe.eventPromise;+ })+ .then(() => {+ // Reinitialize `iframe.eventPromise` with a new promise+ // that catches the load event for the document.write() below.+ bindEvents(iframe);++ iframe.contentDocument.write(frameContent);+ iframe.contentDocument.close();+ return iframe.eventPromise;+ });+ } else if (currentSourceContext.sourceContextType === 'iframe-data') {+ promise = fetch(frameUrl)+ .then(r => r.text())+ .then(content => {+ let dataSrc = "data:text/html;base64," + btoa(content)+ iframe = createElement(+ "iframe", {src: dataSrc}, document.body, true);+ return iframe.eventPromise;+ });+ }++ return promise+ .then(() => {+ const promise = bindEvents2(+ window, "message", iframe, "error", window, "error");+ iframe.contentWindow.postMessage(+ {subresource: subresource,+ sourceContextList: sourceContextList.slice(1)},+ "*");+ return promise;+ })+ .then(event => {+ if (event.data.error)+ return Promise.reject(event.data.error);+ return event.data;+ });+}++// SanityChecker does nothing in release mode. See sanity-checker.js for debug+// mode.+function SanityChecker() {}+SanityChecker.prototype.checkScenario = function() {};+SanityChecker.prototype.setFailTimeout = function(test, timeout) {};+SanityChecker.prototype.checkSubresourceResult = function() {};diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/resources/common.sub.js.headers b/Tests/LibWeb/Text/input/wpt-import/common/security-features/resources/common.sub.js.headersnew file mode 100644index 00000000000..cb762eff806--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/resources/common.sub.js.headers@@ -0,0 +1 @@+Access-Control-Allow-Origin: *diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/__init__.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/document.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/document.pynew file mode 100644index 00000000000..c10a6c6b0ee--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/document.py@@ -0,0 +1,37 @@+import os, sys, json++from wptserve.utils import isomorphic_decode, isomorphic_encode++import importlib+util = importlib.import_module("common.security-features.scope.util")++def main(request, response):+ policyDeliveries = json.loads(request.GET.first(b"policyDeliveries", b"[]"))+ maybe_additional_headers = {}+ meta = u''+ error = u''+ for delivery in policyDeliveries:+ if delivery[u'deliveryType'] == u'meta':+ if delivery[u'key'] == u'referrerPolicy':+ meta += u'<meta name="referrer" content="%s">' % delivery[u'value']+ else:+ error = u'invalid delivery key'+ elif delivery[u'deliveryType'] == u'http-rp':+ if delivery[u'key'] == u'referrerPolicy':+ maybe_additional_headers[b'Referrer-Policy'] = isomorphic_encode(delivery[u'value'])+ else:+ error = u'invalid delivery key'+ else:+ error = u'invalid deliveryType'++ handler = lambda: util.get_template(u"document.html.template") % ({+ u"meta": meta,+ u"error": error,+ u"scriptOrigin": request.url_parts.scheme + u'://' + request.url_parts.hostname + u':' + str(request.url_parts.port)+ })+ util.respond(+ request,+ response,+ payload_generator=handler,+ content_type=b"text/html",+ maybe_additional_headers=maybe_additional_headers)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/template/document.html.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/template/document.html.templatenew file mode 100644index 00000000000..623436cff76--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/template/document.html.template@@ -0,0 +1,32 @@+<!DOCTYPE html>+<html>+ <head>+ %(meta)s+ <script src="%(scriptOrigin)s/common/security-features/resources/common.sub.js"></script>+ <script src="%(scriptOrigin)s/resources/testharness.js"></script>+ <script src="%(scriptOrigin)s/resources/testharnessreport.js"></script>+ <script>+ // Receive a message from the parent and start the test.+ function onMessageFromParent(event) {+ // Because this window might receive messages from child iframe during+ // tests, we first remove the listener here before staring the test.+ window.removeEventListener('message', onMessageFromParent);++ const configurationError = "%(error)s";+ if (configurationError.length > 0) {+ parent.postMessage({error: configurationError}, "*");+ return;+ }++ invokeRequest(event.data.subresource,+ event.data.sourceContextList)+ .then(result => parent.postMessage(result, "*"))+ .catch(e => {+ const message = (e.error && e.error.stack) || e.message || "Error";+ parent.postMessage({error: message}, "*");+ });+ }+ window.addEventListener('message', onMessageFromParent);+ </script>+ </head>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/template/worker.js.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/template/worker.js.templatenew file mode 100644index 00000000000..7a2a6e05c44--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/template/worker.js.template@@ -0,0 +1,29 @@+%(import)s++if ('DedicatedWorkerGlobalScope' in self &&+ self instanceof DedicatedWorkerGlobalScope) {+ self.onmessage = event => onMessageFromParent(event, self);+} else if ('SharedWorkerGlobalScope' in self &&+ self instanceof SharedWorkerGlobalScope) {+ onconnect = event => {+ const port = event.ports[0];+ port.onmessage = event => onMessageFromParent(event, port);+ };+}++// Receive a message from the parent and start the test.+function onMessageFromParent(event, port) {+ const configurationError = "%(error)s";+ if (configurationError.length > 0) {+ port.postMessage({error: configurationError});+ return;+ }++ invokeRequest(event.data.subresource,+ event.data.sourceContextList)+ .then(result => port.postMessage(result))+ .catch(e => {+ const message = (e.error && e.error.stack) || e.message || "Error";+ port.postMessage({error: message});+ });+}diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/util.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/util.pynew file mode 100644index 00000000000..da5aacf35e9--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/util.py@@ -0,0 +1,43 @@+import os++from wptserve.utils import isomorphic_decode++def get_template(template_basename):+ script_directory = os.path.dirname(os.path.abspath(isomorphic_decode(__file__)))+ template_directory = os.path.abspath(+ os.path.join(script_directory, u"template"))+ template_filename = os.path.join(template_directory, template_basename)++ with open(template_filename, "r") as f:+ return f.read()+++def __noop(request, response):+ return u""+++def respond(request,+ response,+ status_code=200,+ content_type=b"text/html",+ payload_generator=__noop,+ cache_control=b"no-cache; must-revalidate",+ access_control_allow_origin=b"*",+ maybe_additional_headers=None):+ response.add_required_headers = False+ response.writer.write_status(status_code)++ if access_control_allow_origin != None:+ response.writer.write_header(b"access-control-allow-origin",+ access_control_allow_origin)+ response.writer.write_header(b"content-type", content_type)+ response.writer.write_header(b"cache-control", cache_control)++ additional_headers = maybe_additional_headers or {}+ for header, value in additional_headers.items():+ response.writer.write_header(header, value)++ response.writer.end_headers()++ payload = payload_generator()+ response.writer.write(payload)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/worker.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/worker.pynew file mode 100644index 00000000000..6b321e7de17--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/scope/worker.py@@ -0,0 +1,44 @@+import os, sys, json++from wptserve.utils import isomorphic_decode, isomorphic_encode+import importlib+util = importlib.import_module("common.security-features.scope.util")++def main(request, response):+ policyDeliveries = json.loads(request.GET.first(b'policyDeliveries', b'[]'))+ worker_type = request.GET.first(b'type', b'classic')+ commonjs_url = u'%s://%s:%s/common/security-features/resources/common.sub.js' % (+ request.url_parts.scheme, request.url_parts.hostname,+ request.url_parts.port)+ if worker_type == b'classic':+ import_line = u'importScripts("%s");' % commonjs_url+ else:+ import_line = u'import "%s";' % commonjs_url++ maybe_additional_headers = {}+ error = u''+ for delivery in policyDeliveries:+ if delivery[u'deliveryType'] == u'meta':+ error = u'<meta> cannot be used in WorkerGlobalScope'+ elif delivery[u'deliveryType'] == u'http-rp':+ if delivery[u'key'] == u'referrerPolicy':+ maybe_additional_headers[b'Referrer-Policy'] = isomorphic_encode(delivery[u'value'])+ elif delivery[u'key'] == u'mixedContent' and delivery[u'value'] == u'opt-in':+ maybe_additional_headers[b'Content-Security-Policy'] = b'block-all-mixed-content'+ elif delivery[u'key'] == u'upgradeInsecureRequests' and delivery[u'value'] == u'upgrade':+ maybe_additional_headers[b'Content-Security-Policy'] = b'upgrade-insecure-requests'+ else:+ error = u'invalid delivery key for http-rp: %s' % delivery[u'key']+ else:+ error = u'invalid deliveryType: %s' % delivery[u'deliveryType']++ handler = lambda: util.get_template(u'worker.js.template') % ({+ u'import': import_line,+ u'error': error+ })+ util.respond(+ request,+ response,+ payload_generator=handler,+ content_type=b'text/javascript',+ maybe_additional_headers=maybe_additional_headers)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/__init__.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/audio.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/audio.pynew file mode 100644index 00000000000..f16a0f7fbbe--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/audio.py@@ -0,0 +1,18 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(request, server_data):+ file = os.path.join(request.doc_root, u"webaudio", u"resources",+ u"sin_440Hz_-6dBFS_1s.wav")+ return open(file, "rb").read()+++def main(request, response):+ handler = lambda data: generate_payload(request, data)+ subresource.respond(request,+ response,+ payload_generator = handler,+ access_control_allow_origin = b"*",+ content_type = b"audio/wav")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/document.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/document.pynew file mode 100644index 00000000000..52b684a4d9f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/document.py@@ -0,0 +1,12 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(server_data):+ return subresource.get_template(u"document.html.template") % server_data++def main(request, response):+ subresource.respond(request,+ response,+ payload_generator = generate_payload)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/empty.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/empty.pynew file mode 100644index 00000000000..312e12cbed9--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/empty.py@@ -0,0 +1,14 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(server_data):+ return u''++def main(request, response):+ subresource.respond(request,+ response,+ payload_generator = generate_payload,+ access_control_allow_origin = b"*",+ content_type = b"text/plain")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/font.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/font.pynew file mode 100644index 00000000000..7900079cdf3--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/font.py@@ -0,0 +1,76 @@+import os, sys+from base64 import decodebytes++from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")+++def generate_payload(request, server_data):+ data = (u'{"headers": %(headers)s}') % server_data+ if b"id" in request.GET:+ request.server.stash.put(request.GET[b"id"], data)+ # Simple base64 encoded .tff font+ return decodebytes(b"AAEAAAANAIAAAwBQRkZUTU6u6MkAAAXcAAAAHE9TLzJWYW"+ b"QKAAABWAAAAFZjbWFwAA8D7wAAAcAAAAFCY3Z0IAAhAnkA"+ b"AAMEAAAABGdhc3D//wADAAAF1AAAAAhnbHlmCC6aTwAAAx"+ b"QAAACMaGVhZO8ooBcAAADcAAAANmhoZWEIkAV9AAABFAAA"+ b"ACRobXR4EZQAhQAAAbAAAAAQbG9jYQBwAFQAAAMIAAAACm"+ b"1heHAASQA9AAABOAAAACBuYW1lehAVOgAAA6AAAAIHcG9z"+ b"dP+uADUAAAWoAAAAKgABAAAAAQAAMhPyuV8PPPUACwPoAA"+ b"AAAMU4Lm0AAAAAxTgubQAh/5wFeAK8AAAACAACAAAAAAAA"+ b"AAEAAAK8/5wAWgXcAAAAAAV4AAEAAAAAAAAAAAAAAAAAAA"+ b"AEAAEAAAAEAAwAAwAAAAAAAgAAAAEAAQAAAEAALgAAAAAA"+ b"AQXcAfQABQAAAooCvAAAAIwCigK8AAAB4AAxAQIAAAIABg"+ b"kAAAAAAAAAAAABAAAAAAAAAAAAAAAAUGZFZABAAEEAQQMg"+ b"/zgAWgK8AGQAAAABAAAAAAAABdwAIQAAAAAF3AAABdwAZA"+ b"AAAAMAAAADAAAAHAABAAAAAAA8AAMAAQAAABwABAAgAAAA"+ b"BAAEAAEAAABB//8AAABB////wgABAAAAAAAAAQYAAAEAAA"+ b"AAAAAAAQIAAAACAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ b"AAAAAAAAAAAAAAAAAAAhAnkAAAAqACoAKgBGAAAAAgAhAA"+ b"ABKgKaAAMABwAusQEALzyyBwQA7TKxBgXcPLIDAgDtMgCx"+ b"AwAvPLIFBADtMrIHBgH8PLIBAgDtMjMRIREnMxEjIQEJ6M"+ b"fHApr9ZiECWAAAAwBk/5wFeAK8AAMABwALAAABNSEVATUh"+ b"FQE1IRUB9AH0/UQDhPu0BRQB9MjI/tTIyP7UyMgAAAAAAA"+ b"4ArgABAAAAAAAAACYATgABAAAAAAABAAUAgQABAAAAAAAC"+ b"AAYAlQABAAAAAAADACEA4AABAAAAAAAEAAUBDgABAAAAAA"+ b"AFABABNgABAAAAAAAGAAUBUwADAAEECQAAAEwAAAADAAEE"+ b"CQABAAoAdQADAAEECQACAAwAhwADAAEECQADAEIAnAADAA"+ b"EECQAEAAoBAgADAAEECQAFACABFAADAAEECQAGAAoBRwBD"+ b"AG8AcAB5AHIAaQBnAGgAdAAgACgAYwApACAAMgAwADAAOA"+ b"AgAE0AbwB6AGkAbABsAGEAIABDAG8AcgBwAG8AcgBhAHQA"+ b"aQBvAG4AAENvcHlyaWdodCAoYykgMjAwOCBNb3ppbGxhIE"+ b"NvcnBvcmF0aW9uAABNAGEAcgBrAEEAAE1hcmtBAABNAGUA"+ b"ZABpAHUAbQAATWVkaXVtAABGAG8AbgB0AEYAbwByAGcAZQ"+ b"AgADIALgAwACAAOgAgAE0AYQByAGsAQQAgADoAIAA1AC0A"+ b"MQAxAC0AMgAwADAAOAAARm9udEZvcmdlIDIuMCA6IE1hcm"+ b"tBIDogNS0xMS0yMDA4AABNAGEAcgBrAEEAAE1hcmtBAABW"+ b"AGUAcgBzAGkAbwBuACAAMAAwADEALgAwADAAMAAgAABWZX"+ b"JzaW9uIDAwMS4wMDAgAABNAGEAcgBrAEEAAE1hcmtBAAAA"+ b"AgAAAAAAAP+DADIAAAABAAAAAAAAAAAAAAAAAAAAAAAEAA"+ b"AAAQACACQAAAAAAAH//wACAAAAAQAAAADEPovuAAAAAMU4"+ b"Lm0AAAAAxTgubQ==")++def generate_report_headers_payload(request, server_data):+ stashed_data = request.server.stash.take(request.GET[b"id"])+ return stashed_data++def main(request, response):+ handler = lambda data: generate_payload(request, data)+ content_type = b'application/x-font-truetype'++ if b"report-headers" in request.GET:+ handler = lambda data: generate_report_headers_payload(request, data)+ content_type = b'application/json'++ subresource.respond(request,+ response,+ payload_generator = handler,+ content_type = content_type,+ access_control_allow_origin = b"*")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/image.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/image.pynew file mode 100644index 00000000000..5c9a0c063c3--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/image.py@@ -0,0 +1,116 @@+import os, sys, array, math++from io import BytesIO++from wptserve.utils import isomorphic_decode++import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++class Image:+ """This class partially implements the interface of the PIL.Image.Image.+ One day in the future WPT might support the PIL module or another imaging+ library, so this hacky BMP implementation will no longer be required.+ """+ def __init__(self, width, height):+ self.width = width+ self.height = height+ self.img = bytearray([0 for i in range(3 * width * height)])++ @staticmethod+ def new(mode, size, color=0):+ return Image(size[0], size[1])++ def _int_to_bytes(self, number):+ packed_bytes = [0, 0, 0, 0]+ for i in range(4):+ packed_bytes[i] = number & 0xFF+ number >>= 8++ return packed_bytes++ def putdata(self, color_data):+ for y in range(self.height):+ for x in range(self.width):+ i = x + y * self.width+ if i > len(color_data) - 1:+ return++ self.img[i * 3: i * 3 + 3] = color_data[i][::-1]++ def save(self, f, type):+ assert type == "BMP"+ # 54 bytes of preambule + image color data.+ filesize = 54 + 3 * self.width * self.height+ # 14 bytes of header.+ bmpfileheader = bytearray([ord('B'), ord('M')] + self._int_to_bytes(filesize) ++ [0, 0, 0, 0, 54, 0, 0, 0])+ # 40 bytes of info.+ bmpinfoheader = bytearray([40, 0, 0, 0] ++ self._int_to_bytes(self.width) ++ self._int_to_bytes(self.height) ++ [1, 0, 24] + (25 * [0]))++ padlength = (4 - (self.width * 3) % 4) % 4+ bmppad = bytearray([0, 0, 0])+ padding = bmppad[0 : padlength]++ f.write(bmpfileheader)+ f.write(bmpinfoheader)++ for i in range(self.height):+ offset = self.width * (self.height - i - 1) * 3+ f.write(self.img[offset : offset + 3 * self.width])+ f.write(padding)++def encode_string_as_bmp_image(string_data):+ data_bytes = array.array("B", string_data.encode("utf-8"))++ num_bytes = len(data_bytes)++ # Encode data bytes to color data (RGB), one bit per channel.+ # This is to avoid errors due to different color spaces used in decoding.+ color_data = []+ for byte in data_bytes:+ p = [int(x) * 255 for x in '{0:08b}'.format(byte)]+ color_data.append((p[0], p[1], p[2]))+ color_data.append((p[3], p[4], p[5]))+ color_data.append((p[6], p[7], 0))++ # Render image.+ num_pixels = len(color_data)+ sqrt = int(math.ceil(math.sqrt(num_pixels)))+ img = Image.new("RGB", (sqrt, sqrt), "black")+ img.putdata(color_data)++ # Flush image to string.+ f = BytesIO()+ img.save(f, "BMP")+ f.seek(0)++ return f.read()++def generate_payload(request, server_data):+ data = (u'{"headers": %(headers)s}') % server_data+ if b"id" in request.GET:+ request.server.stash.put(request.GET[b"id"], data)+ data = encode_string_as_bmp_image(data)+ return data++def generate_report_headers_payload(request, server_data):+ stashed_data = request.server.stash.take(request.GET[b"id"])+ return stashed_data++def main(request, response):+ handler = lambda data: generate_payload(request, data)+ content_type = b'image/bmp'++ if b"report-headers" in request.GET:+ handler = lambda data: generate_report_headers_payload(request, data)+ content_type = b'application/json'++ subresource.respond(request,+ response,+ payload_generator = handler,+ content_type = content_type,+ access_control_allow_origin = b"*")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/referrer.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/referrer.pynew file mode 100644index 00000000000..e36631479e6--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/referrer.py@@ -0,0 +1,4 @@+def main(request, response):+ referrer = request.headers.get(b"referer", b"")+ response_headers = [(b"Content-Type", b"text/javascript")]+ return (200, response_headers, b"window.referrer = '" + referrer + b"'")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/script.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/script.pynew file mode 100644index 00000000000..9701816b9fa--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/script.py@@ -0,0 +1,14 @@+import os, sys+from wptserve.utils import isomorphic_decode++import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(server_data):+ return subresource.get_template(u"script.js.template") % server_data++def main(request, response):+ subresource.respond(request,+ response,+ payload_generator = generate_payload,+ content_type = b"application/javascript")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/shared-worker.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/shared-worker.pynew file mode 100644index 00000000000..bdfb61bbb3f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/shared-worker.py@@ -0,0 +1,13 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(server_data):+ return subresource.get_template(u"shared-worker.js.template") % server_data++def main(request, response):+ subresource.respond(request,+ response,+ payload_generator = generate_payload,+ content_type = b"application/javascript")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/static-import.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/static-import.pynew file mode 100644index 00000000000..3c3a6f6871d--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/static-import.py@@ -0,0 +1,61 @@+import os, sys, json+from urllib.parse import unquote++from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def get_csp_value(value):+ '''+ Returns actual CSP header values (e.g. "worker-src 'self'") for the+ given string used in PolicyDelivery's value (e.g. "worker-src-self").+ '''++ # script-src+ # Test-related scripts like testharness.js and inline scripts containing+ # test bodies.+ # 'unsafe-inline' is added as a workaround here. This is probably not so+ # bad, as it shouldn't intefere non-inline-script requests that we want to+ # test.+ if value == 'script-src-wildcard':+ return "script-src * 'unsafe-inline'"+ if value == 'script-src-self':+ return "script-src 'self' 'unsafe-inline'"+ # Workaround for "script-src 'none'" would be more complicated, because+ # - "script-src 'none' 'unsafe-inline'" is handled somehow differently from+ # "script-src 'none'", i.e.+ # https://w3c.github.io/webappsec-csp/#match-url-to-source-list Step 3+ # handles the latter but not the former.+ # - We need nonce- or path-based additional values to allow same-origin+ # test scripts like testharness.js.+ # Therefore, we disable 'script-src-none' tests for now in+ # `/content-security-policy/spec.src.json`.+ if value == 'script-src-none':+ return "script-src 'none'"++ # worker-src+ if value == 'worker-src-wildcard':+ return 'worker-src *'+ if value == 'worker-src-self':+ return "worker-src 'self'"+ if value == 'worker-src-none':+ return "worker-src 'none'"+ raise Exception('Invalid delivery_value: %s' % value)++def generate_payload(request):+ import_url = unquote(isomorphic_decode(request.GET[b'import_url']))+ return subresource.get_template(u"static-import.js.template") % {+ u"import_url": import_url+ }++def main(request, response):+ def payload_generator(_): return generate_payload(request)+ maybe_additional_headers = {}+ if b'contentSecurityPolicy' in request.GET:+ csp = unquote(isomorphic_decode(request.GET[b'contentSecurityPolicy']))+ maybe_additional_headers[b'Content-Security-Policy'] = get_csp_value(csp)+ subresource.respond(request,+ response,+ payload_generator = payload_generator,+ content_type = b"application/javascript",+ maybe_additional_headers = maybe_additional_headers)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/stylesheet.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/stylesheet.pynew file mode 100644index 00000000000..05db249250d--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/stylesheet.py@@ -0,0 +1,61 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(request, server_data):+ data = (u'{"headers": %(headers)s}') % server_data+ type = b'image'+ if b"type" in request.GET:+ type = request.GET[b"type"]++ if b"id" in request.GET:+ request.server.stash.put(request.GET[b"id"], data)++ if type == b'image':+ return subresource.get_template(u"image.css.template") % {u"id": isomorphic_decode(request.GET[b"id"])}++ elif type == b'font':+ return subresource.get_template(u"font.css.template") % {u"id": isomorphic_decode(request.GET[b"id"])}++ elif type == b'svg':+ return subresource.get_template(u"svg.css.template") % {+ u"id": isomorphic_decode(request.GET[b"id"]),+ u"property": isomorphic_decode(request.GET[b"property"])}++ # A `'stylesheet-only'`-type stylesheet has no nested resources; this is+ # useful in tests that cover referrers for stylesheet fetches (e.g. fetches+ # triggered by `@import` statements).+ elif type == b'stylesheet-only':+ return u''++def generate_import_rule(request, server_data):+ return u"@import url('%(url)s');" % {+ u"url": subresource.create_url(request, swap_origin=True,+ query_parameter_to_remove=u"import-rule")+ }++def generate_report_headers_payload(request, server_data):+ stashed_data = request.server.stash.take(request.GET[b"id"])+ return stashed_data++def main(request, response):+ payload_generator = lambda data: generate_payload(request, data)+ content_type = b"text/css"+ referrer_policy = b"unsafe-url"+ if b"import-rule" in request.GET:+ payload_generator = lambda data: generate_import_rule(request, data)++ if b"report-headers" in request.GET:+ payload_generator = lambda data: generate_report_headers_payload(request, data)+ content_type = b'application/json'++ if b"referrer-policy" in request.GET:+ referrer_policy = request.GET[b"referrer-policy"]++ subresource.respond(+ request,+ response,+ payload_generator = payload_generator,+ content_type = content_type,+ maybe_additional_headers = { b"Referrer-Policy": referrer_policy })diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/subresource.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/subresource.pynew file mode 100644index 00000000000..261b1d69307--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/subresource.py@@ -0,0 +1,209 @@+import os, json+from urllib.parse import parse_qsl, SplitResult, urlencode, urlsplit, urlunsplit++from wptserve.utils import isomorphic_decode, isomorphic_encode++def get_template(template_basename):+ script_directory = os.path.dirname(os.path.abspath(isomorphic_decode(__file__)))+ template_directory = os.path.abspath(os.path.join(script_directory,+ u"template"))+ template_filename = os.path.join(template_directory, template_basename)++ with open(template_filename, "r") as f:+ return f.read()+++def redirect(url, response):+ response.add_required_headers = False+ response.writer.write_status(301)+ response.writer.write_header(b"access-control-allow-origin", b"*")+ response.writer.write_header(b"location", isomorphic_encode(url))+ response.writer.end_headers()+ response.writer.write(u"")+++# TODO(kristijanburnik): subdomain_prefix is a hardcoded value aligned with+# referrer-policy-test-case.js. The prefix should be configured in one place.+def __get_swapped_origin_netloc(netloc, subdomain_prefix = u"www1."):+ if netloc.startswith(subdomain_prefix):+ return netloc[len(subdomain_prefix):]+ else:+ return subdomain_prefix + netloc+++# Creates a URL (typically a redirect target URL) that is the same as the+# current request URL `request.url`, except for:+# - When `swap_scheme` or `swap_origin` is True, its scheme/origin is changed+# to the other one. (http <-> https, ws <-> wss, etc.)+# - For `downgrade`, we redirect to a URL that would be successfully loaded+# if and only if upgrade-insecure-request is applied.+# - `query_parameter_to_remove` parameter is removed from query part.+# Its default is "redirection" to avoid redirect loops.+def create_url(request,+ swap_scheme=False,+ swap_origin=False,+ downgrade=False,+ query_parameter_to_remove=u"redirection"):+ parsed = urlsplit(request.url)+ destination_netloc = parsed.netloc++ scheme = parsed.scheme+ if swap_scheme:+ scheme = u"http" if parsed.scheme == u"https" else u"https"+ hostname = parsed.netloc.split(u':')[0]+ # Always use the HTTPS port to allow testing upgrades correctly, similar+ # to the downgrade case below.+ port = request.server.config[u"ports"]["https"][0]+ destination_netloc = u":".join([hostname, str(port)])++ if downgrade:+ # These rely on some unintuitive cleverness due to WPT's test setup:+ # 'Upgrade-Insecure-Requests' does not upgrade the port number,+ # so we use URLs in the form `http://[domain]:[https-port]`,+ # which will be upgraded to `https://[domain]:[https-port]`.+ # If the upgrade fails, the load will fail, as we don't serve HTTP over+ # the secure port.+ if parsed.scheme == u"https":+ scheme = u"http"+ elif parsed.scheme == u"wss":+ scheme = u"ws"+ else:+ raise ValueError(u"Downgrade redirection: Invalid scheme '%s'" %+ parsed.scheme)+ hostname = parsed.netloc.split(u':')[0]+ port = request.server.config[u"ports"][parsed.scheme][0]+ destination_netloc = u":".join([hostname, str(port)])++ if swap_origin:+ destination_netloc = __get_swapped_origin_netloc(destination_netloc)++ parsed_query = parse_qsl(parsed.query, keep_blank_values=True)+ parsed_query = [x for x in parsed_query if x[0] != query_parameter_to_remove]++ destination_url = urlunsplit(SplitResult(+ scheme = scheme,+ netloc = destination_netloc,+ path = parsed.path,+ query = urlencode(parsed_query),+ fragment = None))++ return destination_url+++def preprocess_redirection(request, response):+ if b"redirection" not in request.GET:+ return False++ redirection = request.GET[b"redirection"]++ if redirection == b"no-redirect":+ return False+ elif redirection == b"keep-scheme":+ redirect_url = create_url(request, swap_scheme=False)+ elif redirection == b"swap-scheme":+ redirect_url = create_url(request, swap_scheme=True)+ elif redirection == b"downgrade":+ redirect_url = create_url(request, downgrade=True)+ elif redirection == b"keep-origin":+ redirect_url = create_url(request, swap_origin=False)+ elif redirection == b"swap-origin":+ redirect_url = create_url(request, swap_origin=True)+ else:+ raise ValueError(u"Invalid redirection type '%s'" % isomorphic_decode(redirection))++ redirect(redirect_url, response)+ return True+++def preprocess_stash_action(request, response):+ if b"action" not in request.GET:+ return False++ action = request.GET[b"action"]++ key = request.GET[b"key"]+ stash = request.server.stash+ path = request.GET[b"path"] if b"path" in request.GET \+ else isomorphic_encode(request.url.split(u'?')[0])++ if action == b"put":+ value = isomorphic_decode(request.GET[b"value"])+ stash.take(key=key, path=path)+ stash.put(key=key, value=value, path=path)+ response_data = json.dumps({u"status": u"success", u"result": isomorphic_decode(key)})+ elif action == b"purge":+ value = stash.take(key=key, path=path)+ return False+ elif action == b"check-scheme":+ scheme = urlsplit(request.url).scheme+ if scheme in [u"https", u"wss"]:+ stash.take(key=key, path=path)+ stash.put(key=key, value=u"upgraded", path=path)+ return False+ elif action == b"take":+ value = stash.take(key=key, path=path)+ if value == u"upgraded":+ status = u"upgraded"+ elif value is None:+ status = u"allowed"+ else:+ status = u"blocked"+ response_data = json.dumps({u"status": status, u"result": value})+ else:+ return False++ response.add_required_headers = False+ response.writer.write_status(200)+ response.writer.write_header(b"content-type", b"text/javascript")+ response.writer.write_header(b"cache-control", b"no-cache; must-revalidate")+ response.writer.end_headers()+ response.writer.write(response_data)+ return True+++def __noop(request, response):+ return u""+++def respond(request,+ response,+ status_code = 200,+ content_type = b"text/html",+ payload_generator = __noop,+ cache_control = b"no-cache; must-revalidate",+ access_control_allow_origin = b"*",+ maybe_additional_headers = None):+ if preprocess_redirection(request, response):+ return++ if preprocess_stash_action(request, response):+ return++ response.add_required_headers = False+ response.writer.write_status(status_code)++ if access_control_allow_origin != None:+ response.writer.write_header(b"access-control-allow-origin",+ access_control_allow_origin)+ response.writer.write_header(b"content-type", content_type)+ response.writer.write_header(b"cache-control", cache_control)++ additional_headers = maybe_additional_headers or {}+ for header, value in additional_headers.items():+ response.writer.write_header(header, value)++ response.writer.end_headers()++ new_headers = {}+ new_val = []+ for key, val in request.headers.items():+ if len(val) == 1:+ new_val = isomorphic_decode(val[0])+ else:+ new_val = [isomorphic_decode(x) for x in val]+ new_headers[isomorphic_decode(key)] = new_val++ server_data = {u"headers": json.dumps(new_headers, indent = 4)}++ payload = payload_generator(server_data)+ response.writer.write(payload)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/svg.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/svg.pynew file mode 100644index 00000000000..9c569e3bf52--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/svg.py@@ -0,0 +1,37 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(request, server_data):+ data = (u'{"headers": %(headers)s}') % server_data+ if b"id" in request.GET:+ with request.server.stash.lock:+ request.server.stash.take(request.GET[b"id"])+ request.server.stash.put(request.GET[b"id"], data)+ return u"<svg xmlns='http://www.w3.org/2000/svg'></svg>"++def generate_payload_embedded(request, server_data):+ return subresource.get_template(u"svg.embedded.template") % {+ u"id": isomorphic_decode(request.GET[b"id"]),+ u"property": isomorphic_decode(request.GET[b"property"])}++def generate_report_headers_payload(request, server_data):+ stashed_data = request.server.stash.take(request.GET[b"id"])+ return stashed_data++def main(request, response):+ handler = lambda data: generate_payload(request, data)+ content_type = b'image/svg+xml'++ if b"embedded-svg" in request.GET:+ handler = lambda data: generate_payload_embedded(request, data)++ if b"report-headers" in request.GET:+ handler = lambda data: generate_report_headers_payload(request, data)+ content_type = b'application/json'++ subresource.respond(request,+ response,+ payload_generator = handler,+ content_type = content_type)diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/document.html.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/document.html.templatenew file mode 100644index 00000000000..141711c1483--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/document.html.template@@ -0,0 +1,16 @@+<!DOCTYPE html>+<html>+ <head>+ <title>This page reports back it's request details to the parent frame</title>+ </head>+ <body>+ <script>+ var result = {+ location: document.location.toString(),+ referrer: document.referrer.length > 0 ? document.referrer : undefined,+ headers: %(headers)s+ };+ parent.postMessage(result, "*");+ </script>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/font.css.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/font.css.templatenew file mode 100644index 00000000000..9d1e9c421cc--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/font.css.template@@ -0,0 +1,9 @@+@font-face {+ font-family: 'wpt';+ font-style: normal;+ font-weight: normal;+ src: url(/common/security-features/subresource/font.py?id=%(id)s) format('truetype');+}+body {+ font-family: 'wpt';+}diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/image.css.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/image.css.templatenew file mode 100644index 00000000000..dfe41f1bf16--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/image.css.template@@ -0,0 +1,3 @@+div.styled::before {+ content:url(/common/security-features/subresource/image.py?id=%(id)s)+}diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/script.js.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/script.js.templatenew file mode 100644index 00000000000..e2edf21819d--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/script.js.template@@ -0,0 +1,3 @@+postMessage({+ "headers": %(headers)s+}, "*");diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/shared-worker.js.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/shared-worker.js.templatenew file mode 100644index 00000000000..c3f109e4a90--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/shared-worker.js.template@@ -0,0 +1,5 @@+onconnect = function(e) {+ e.ports[0].postMessage({+ "headers": %(headers)s+ });+};diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/static-import.js.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/static-import.js.templatenew file mode 100644index 00000000000..095459b5475--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/static-import.js.template@@ -0,0 +1 @@+import '%(import_url)s';diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/svg.css.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/svg.css.templatenew file mode 100644index 00000000000..c2e509cc3b8--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/svg.css.template@@ -0,0 +1,3 @@+path {+ %(property)s: url(/common/security-features/subresource/svg.py?id=%(id)s#invalidFragment);+}diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/svg.embedded.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/svg.embedded.templatenew file mode 100644index 00000000000..5986c4800a7--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/svg.embedded.template@@ -0,0 +1,5 @@+<?xml version='1.0' standalone='no'?>+<?xml-stylesheet href='stylesheet.py?id=%(id)s&type=svg&property=%(property)s' type='text/css'?>+<svg xmlns='http://www.w3.org/2000/svg'>+ <path d='M 50,5 95,100 5,100 z' />+</svg>diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/worker.js.template b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/worker.js.templatenew file mode 100644index 00000000000..817dd8c87ac--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/template/worker.js.template@@ -0,0 +1,3 @@+postMessage({+ "headers": %(headers)s+});diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/video.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/video.pynew file mode 100644index 00000000000..9db8e9fbb5a--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/video.py@@ -0,0 +1,17 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(request, server_data):+ file = os.path.join(request.doc_root, u"media", u"movie_5.webm")+ return open(file, "rb").read()+++def main(request, response):+ handler = lambda data: generate_payload(request, data)+ subresource.respond(request,+ response,+ payload_generator = handler,+ access_control_allow_origin = b"*",+ content_type = b"video/webm")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/worker.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/worker.pynew file mode 100644index 00000000000..f655633b5db--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/worker.py@@ -0,0 +1,13 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(server_data):+ return subresource.get_template(u"worker.js.template") % server_data++def main(request, response):+ subresource.respond(request,+ response,+ payload_generator = generate_payload,+ content_type = b"application/javascript")diff --git a/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/xhr.py b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/xhr.pynew file mode 100644index 00000000000..75921e91569--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/common/security-features/subresource/xhr.py@@ -0,0 +1,16 @@+import os, sys+from wptserve.utils import isomorphic_decode+import importlib+subresource = importlib.import_module("common.security-features.subresource.subresource")++def generate_payload(server_data):+ data = (u'{"headers": %(headers)s}') % server_data+ return data++def main(request, response):+ subresource.respond(request,+ response,+ payload_generator = generate_payload,+ access_control_allow_origin = b"*",+ content_type = b"application/json",+ cache_control = b"no-store")diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.htmlnew file mode 100644index 00000000000..06efff34770--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.html@@ -0,0 +1,82 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.html.headers b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.html.headersnew file mode 100644index 00000000000..c75aa51ab41--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-none/sharedworker-import-data.http.html.headers@@ -0,0 +1 @@+Content-Security-Policy: worker-src 'none'diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.htmlnew file mode 100644index 00000000000..4a691c66746--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.html@@ -0,0 +1,82 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.html.headers b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.html.headersnew file mode 100644index 00000000000..d55f863f727--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.http-rp/worker-src-self/worker-import-data.http.html.headers@@ -0,0 +1 @@+Content-Security-Policy: worker-src 'self'diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.htmlnew file mode 100644index 00000000000..91f0a35ffe6--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/sharedworker-import-data.http.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-import-data to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.htmlnew file mode 100644index 00000000000..a7899dd6de1--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-self/worker-import-data.http.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.htmlnew file mode 100644index 00000000000..f49cff79355--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/script-src-wildcard/worker-import-data.http.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-inline'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.htmlnew file mode 100644index 00000000000..7045ec75c20--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/sharedworker-module.http.html@@ -0,0 +1,43 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="worker-src 'none'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-module",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-module to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "sharedworker-module",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for sharedworker-module to same-http origin and no-redirect redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.htmlnew file mode 100644index 00000000000..a1ba9e9db03--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-classic.http.html@@ -0,0 +1,43 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="worker-src 'none'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-classic",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-classic to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-classic",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-classic to same-http origin and no-redirect redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.htmlnew file mode 100644index 00000000000..70bddb40805--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-none/worker-import.http.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="worker-src 'none'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.htmlnew file mode 100644index 00000000000..baa9a073d59--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/gen/top.meta/worker-src-self/worker-import-data.http.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` -->+<html>+ <head>+ <meta charset="utf-8">+ <meta name="timeout" content="long">+ <meta http-equiv="Content-Security-Policy" content="worker-src 'self'">+ <script src="../../../../resources/testharness.js"></script>+ <script src="../../../../resources/testharnessreport.js"></script>+ <script src="../../../../common/security-features/resources/common.sub.js"></script>+ <script src="../../../generic/test-case.sub.js"></script>+ </head>+ <body>+ <script>+ TestCase(+ [+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "cross-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to cross-http origin and swap-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "keep-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and keep-origin redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "no-redirect",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and no-redirect redirection from http context."+ },+ {+ "expectation": "blocked",+ "origin": "same-http",+ "redirection": "swap-origin",+ "source_context_list": [],+ "source_scheme": "http",+ "subresource": "worker-import-data",+ "subresource_policy_deliveries": [],+ "test_description": "Content Security Policy: Expects blocked for worker-import-data to same-http origin and swap-origin redirection from http context."+ }+ ],+ new SanityChecker()+ ).start();+ </script>+ <div id="log"></div>+ </body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/generic/test-case.sub.js b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/generic/test-case.sub.jsnew file mode 100644index 00000000000..43171f5b1fa--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/generic/test-case.sub.js@@ -0,0 +1,104 @@+function TestCase(scenarios, sanityChecker) {+ function runTest(scenario) {+ sanityChecker.checkScenario(scenario, subresourceMap);++ const urls = getRequestURLs(scenario.subresource,+ scenario.origin,+ scenario.redirection);++ /** @type {Subresource} */+ const subresource = {+ subresourceType: scenario.subresource,+ url: urls.testUrl,+ policyDeliveries: scenario.subresource_policy_deliveries,+ };++ let violationEventResolve;+ // Resolved with an array of securitypolicyviolation events.+ const violationEventPromise = new Promise(resolve => {+ violationEventResolve = resolve;+ });++ promise_test(async t => {+ await xhrRequest(urls.announceUrl);++ // Currently only requests from top-level Documents are tested+ // (specified by `spec.src.json`) and thus securitypolicyviolation+ // events are assumed to be fired on the top-level Document here.+ // When adding non-top-level Document tests, securitypolicyviolation+ // events should be caught in appropriate contexts.+ const violationEvents = [];+ const listener = e => { violationEvents.push(e); };+ document.addEventListener('securitypolicyviolation', listener);++ try {+ // Send out the real resource request.+ // This should tear down the key if it's not blocked.+ const mainPromise = invokeRequest(subresource, scenario.source_context_list);+ if (scenario.expectation === 'allowed') {+ await mainPromise;+ } else {+ await mainPromise+ .then(t.unreached_func('main promise resolved unexpectedly'))+ .catch(_ => {});+ }+ } finally {+ // Always perform post-processing/clean up for+ // 'securitypolicyviolation' events and resolve+ // `violationEventPromise`, to prevent timeout of the+ // promise_test() below.++ // securitypolicyviolation events are fired in a queued task in+ // https://w3c.github.io/webappsec-csp/#report-violation+ // so wait for queued tasks to run using setTimeout().+ let timeout = 0;+ if (scenario.subresource.startsWith('worklet-') &&+ navigator.userAgent.includes("Firefox/")) {+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1808911+ // In Firefox sometimes violations from Worklets are delayed.+ timeout = 10;+ } else if (scenario.subresource.startsWith('worker-') &&+ navigator.userAgent.includes("Servo/")) {+ // In Servo, worker violations are also delayed, as they are+ // sent via IPC. However, they typically arrive relatively+ // quickly after that.+ timeout = 1;+ }+ await new Promise(resolve => setTimeout(resolve, timeout));++ // Pass violation events to `violationEventPromise` (which will be tested+ // in the subsequent promise_test()) and clean up the listener.+ violationEventResolve(violationEvents);+ document.removeEventListener('securitypolicyviolation', listener);+ }++ // Send request to check if the key has been torn down.+ const assertResult = await xhrRequest(urls.assertUrl);++ // Now check if the value has been torn down. If it's still there,+ // we have blocked the request by content security policy.+ assert_equals(assertResult.status, scenario.expectation,+ "The resource request should be '" + scenario.expectation + "'.");++ }, scenario.test_description);++ promise_test(async _ => {+ const violationEvents = await violationEventPromise;+ if (scenario.expectation === 'allowed') {+ assert_array_equals(violationEvents, [],+ 'no violation events should be fired');+ } else {+ assert_equals(violationEvents.length, 1,+ 'One violation event should be fired');+ }+ }, scenario.test_description + ": securitypolicyviolation");+ } // runTest++ function runTests() {+ for (const scenario of scenarios) {+ runTest(scenario);+ }+ }++ return {start: runTests};+}