Truly independent web browser
LibWeb: Check CSP synchronously for string timer handlers
Shannon Boothe82ab9a823cf
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex a0af5d9dac8..ca07e5ee383 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -722,6 +722,13 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatiomove(handler).downcast<Utf16String, GC::Ref<TrustedTypes::TrustedScript>>(),sink,TrustedTypes::Script.view()));++ // 5. Perform EnsureCSPDoesNotBlockStringCompilation(global's relevant realm, « », handler, handler, timer, « »,+ // handler). If this throws an exception, catch it and return 0.+ auto const& source = handler.get<Utf16String>();+ auto handler_primitive_string = JS::PrimitiveString::create(this_impl().vm(), source);+ if (ContentSecurityPolicy::ensure_csp_does_not_block_string_compilation(relevant_realm(*this), {}, source, source, JS::CompilationType::Timer, {}, handler_primitive_string).is_throw_completion())+ return 0;}auto function_or_string = move(handler).downcast<GC::Ref<WebIDL::CallbackType>, Utf16String>();@@ -756,18 +763,13 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatioelse if (timeout == 0)throttling_class = TimerThrottlingClass::Immediate;- // 7. Let realm be global's relevant realm.- auto& realm = relevant_realm(*this);-- // 8. Let initiating script be the active script.+ // 7. Let initiating script be the active script.auto const* initiating_script = Web::Bindings::active_script();- auto& vm = this_impl().vm();-- // FIXME: 9. Let uniqueHandle be null.+ // FIXME: 8. Let uniqueHandle be null.- // 10. Let task be a task that runs the following substeps:- auto task = GC::create_function(GC::Heap::the(), Function<void()>([this, handler = move(function_or_string), timeout, arguments = move(arguments), repeat, id, initiating_script, &vm, &realm]() {+ // 9. Let task be a task that runs the following substeps:+ auto task = GC::create_function(GC::Heap::the(), Function<void()>([this, handler = move(function_or_string), timeout, arguments = move(arguments), repeat, id, initiating_script]() {// FIXME: 1. Assert: uniqueHandle is a unique internal value, not null.// 2. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.@@ -777,38 +779,31 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// FIXME: 3. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.// FIXME: 4. Record timing info for timer handler given handler, global's relevant settings object, and repeat.- bool continue_ = handler.visit(+ handler.visit(// 5. If handler is a Function, then invoke handler given arguments and "report", and with callback this value set to thisArg.[&](GC::Root<WebIDL::CallbackType> const& callback) {auto this_value = [&]() -> JS::Value {if (auto* window = as_if<Window>(this_impl()))return &window->window()->object();+ auto& realm = relevant_realm(*this);return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { this_impl() });}();(void)WebIDL::invoke_callback(*callback, this_value, WebIDL::ExceptionBehavior::Report, arguments);- return true;},// 6. Otherwise:[&](Utf16String const& source) {// 1. Assert: handler is a string.- // 2. Perform EnsureCSPDoesNotBlockStringCompilation(realm, « », handler, handler, timer, « », handler).- // If this throws an exception, catch it, report it for global, and abort these steps.- auto handler_primitive_string = JS::PrimitiveString::create(vm, source);- if (auto result = ContentSecurityPolicy::ensure_csp_does_not_block_string_compilation(realm, {}, source, source, JS::CompilationType::Timer, {}, handler_primitive_string); result.is_throw_completion()) {- report_exception(result, realm);- return false;- }- // 3. Let settings object be global's relevant settings object.+ // 2. Let settings object be global's relevant settings object.auto& settings_object = relevant_settings_object(*this);- // 4. Let fetch options be the default classic script fetch options.+ // 3. Let fetch options be the default classic script fetch options.ScriptFetchOptions options {};- // 5. Let base URL be settings object's API base URL.+ // 4. Let base URL be settings object's API base URL.auto base_url = settings_object.api_base_url();- // 6. If initiating script is not null, then:+ // 5. If initiating script is not null, then:if (initiating_script) {// FIXME: 1. Set fetch options to a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce,// integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch@@ -821,19 +816,15 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// done by eval(). That is, module script fetches via import() will behave the same in both contexts.}- // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.+ // 6. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.// FIXME: Pass fetch options.auto basename = base_url.basename();auto script = ClassicScript::create(basename, source, settings_object, move(base_url));- // 8. Run the classic script script.+ // 7. Run the classic script script.(void)script->run();- return true;});- if (!continue_)- return;-// 7. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.if (!m_timers.contains(id))return;diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 1990940f5bc..cb2a0f6afa9 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -519,6 +519,12 @@ Text/input/css/style-engine/imported-sheet-media-text-flips.html; whose process hosts only what that content made.Text/input/SiteIsolation/iframe/opaque-origin-iframe-is-hosted-with-its-initiator.html+; Its meta policy allows script-src 'self', which a file:// testharness doesn't match.+Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.html++; Adds a policy to a same-origin iframe's document.+Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.html+[Skipped]; Needs vertical-rl inline geometry fidelity beyond the binary transposeRef/input/wpt-import/css/css-position/position-absolute-in-inline-006.htmldiff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.txtnew file mode 100644index 00000000000..ada08c3329e--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass setTimeout() with a blocked string handler returns 0 and doesn't report an exception+Pass setInterval() with a blocked string handler returns 0 and doesn't report an exception\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-cross-realm.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-cross-realm.txtnew file mode 100644index 00000000000..1312e51e991--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-cross-realm.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 6 tests++6 Pass+Pass setTimeout() on a global whose policy blocks eval returns 0+Pass setTimeout() from another realm on a global whose policy blocks eval returns 0+Pass setTimeout() from a realm whose policy blocks eval on a global whose policy doesn't returns an ID and runs+Pass setInterval() on a global whose policy blocks eval returns 0+Pass setInterval() from another realm on a global whose policy blocks eval returns 0+Pass setInterval() from a realm whose policy blocks eval on a global whose policy doesn't returns an ID and runs\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.txtnew file mode 100644index 00000000000..4d659984bb5--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass setTimeout() string handler runs after a policy blocking eval is added+Pass setInterval() string handler keeps running after a policy blocking eval is added\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.txtnew file mode 100644index 00000000000..dadcf2c6481--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.txt@@ -0,0 +1,9 @@+Harness status: OK++Found 4 tests++4 Pass+Pass setTimeout() reports a violation for a string handler even if the timer is cleared right away+Pass setTimeout() reports a violation for a string handler and runs it+Pass setInterval() reports a violation for a string handler even if the timer is cleared right away+Pass setInterval() reports a violation for a string handler and runs it\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.txtnew file mode 100644index 00000000000..df3590a152d--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass setTimeout() runs the default policy and then blocks the rewritten string handler+Pass setInterval() runs the default policy and then blocks the rewritten string handler\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.htmlnew file mode 100644index 00000000000..19222543e72--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-blocked-no-exception.html@@ -0,0 +1,32 @@+<!DOCTYPE html>+<meta charset="utf-8">+<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' 'report-sample'">+<title>Blocked string handlers for setTimeout() and setInterval() don't report an exception</title>+<link rel="help" href="https://html.spec.whatwg.org/#timer-initialisation-steps">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<script>+ const errors = [];+ addEventListener("error", e => errors.push(e.message));++ function violationWithSample(sample) {+ return new Promise(resolve => {+ document.addEventListener("securitypolicyviolation", function listener(e) {+ if (e.sample === sample) {+ document.removeEventListener("securitypolicyviolation", listener);+ resolve(e);+ }+ });+ });+ }++ for (const method of ["setTimeout", "setInterval"]) {+ promise_test(async t => {+ const handler = `${method}Blocked()`;+ const violation = violationWithSample(handler);+ assert_equals(window[method](handler, 0), 0);+ await violation;+ assert_array_equals(errors, []);+ }, `${method}() with a blocked string handler returns 0 and doesn't report an exception`);+ }+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-cross-realm.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-cross-realm.htmlnew file mode 100644index 00000000000..173c80f0117--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-cross-realm.html@@ -0,0 +1,41 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>setTimeout() and setInterval() use the policy of this's global for string handlers</title>+<link rel="help" href="https://html.spec.whatwg.org/#timer-initialisation-steps">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<body>+<script>+ const iframeLoaded = new Promise(resolve => {+ const iframe = document.createElement("iframe");+ iframe.srcdoc = `<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">`;+ iframe.onload = () => resolve(iframe.contentWindow);+ document.body.append(iframe);+ });++ for (const [set, clear] of [["setTimeout", "clearTimeout"], ["setInterval", "clearInterval"]]) {+ promise_test(async t => {+ const win = await iframeLoaded;+ assert_equals(win[set]("void 0", 0), 0);+ }, `${set}() on a global whose policy blocks eval returns 0`);++ promise_test(async t => {+ const win = await iframeLoaded;+ assert_equals(window[set].call(win, "void 0", 0), 0);+ }, `${set}() from another realm on a global whose policy blocks eval returns 0`);++ promise_test(async t => {+ const win = await iframeLoaded;+ let id;+ const ran = new Promise(resolve => {+ window[`${set}Ran`] = () => {+ window[clear](id);+ resolve();+ };+ });+ id = win[set].call(window, `${set}Ran()`, 0);+ assert_not_equals(id, 0);+ await ran;+ }, `${set}() from a realm whose policy blocks eval on a global whose policy doesn't returns an ID and runs`);+ }+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.htmlnew file mode 100644index 00000000000..7eed3214d89--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-policy-added-later.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>A policy added after setTimeout() or setInterval() doesn't block its string handler</title>+<link rel="help" href="https://html.spec.whatwg.org/#timer-initialisation-steps">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<body>+<script>+ function loadIframe(t) {+ return new Promise(resolve => {+ const iframe = document.createElement("iframe");+ t.add_cleanup(() => iframe.remove());+ iframe.onload = () => resolve(iframe.contentWindow);+ iframe.src = "../../common/blank.html";+ document.body.append(iframe);+ });+ }++ function addPolicy(win) {+ const meta = win.document.createElement("meta");+ meta.httpEquiv = "Content-Security-Policy";+ meta.content = "script-src 'self' 'unsafe-inline'";+ win.document.head.append(meta);+ assert_throws_js(win.EvalError, () => win.eval("1"), "precondition: the policy blocks eval");+ }++ promise_test(async t => {+ const win = await loadIframe(t);+ const ran = new Promise(resolve => { win.timeoutRan = resolve; });+ assert_not_equals(win.setTimeout("timeoutRan()", 0), 0);+ addPolicy(win);+ await ran;+ }, "setTimeout() string handler runs after a policy blocking eval is added");++ promise_test(async t => {+ const win = await loadIframe(t);+ let runs = 0;+ let id;+ const ran = new Promise(resolve => {+ win.intervalRan = () => {+ if (++runs === 2) {+ win.clearInterval(id);+ resolve();+ }+ };+ });+ id = win.setInterval("intervalRan()", 0);+ assert_not_equals(id, 0);+ addPolicy(win);+ await ran;+ }, "setInterval() string handler keeps running after a policy blocking eval is added");+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.htmlnew file mode 100644index 00000000000..4c1a9e44d9c--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.html@@ -0,0 +1,45 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>setTimeout() and setInterval() with string handlers under a report-only policy</title>+<link rel="help" href="https://html.spec.whatwg.org/#timer-initialisation-steps">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<script>+ function violationWithSample(sample) {+ return new Promise(resolve => {+ document.addEventListener("securitypolicyviolation", function listener(e) {+ if (e.sample === sample) {+ document.removeEventListener("securitypolicyviolation", listener);+ resolve(e);+ }+ });+ });+ }++ for (const [set, clear] of [["setTimeout", "clearTimeout"], ["setInterval", "clearInterval"]]) {+ promise_test(async t => {+ const handler = `${set}Cleared()`;+ const violation = violationWithSample(handler);+ const id = window[set](handler, 0);+ assert_not_equals(id, 0);+ window[clear](id);+ const e = await violation;+ assert_equals(e.disposition, "report");+ }, `${set}() reports a violation for a string handler even if the timer is cleared right away`);++ promise_test(async t => {+ const handler = `${set}Allowed()`;+ const violation = violationWithSample(handler);+ let id;+ const ran = new Promise(resolve => {+ window[`${set}Allowed`] = () => {+ window[clear](id);+ resolve();+ };+ });+ id = window[set](handler, 0);+ assert_not_equals(id, 0);+ await Promise.all([violation, ran]);+ }, `${set}() reports a violation for a string handler and runs it`);+ }+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.html.headers b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.html.headersnew file mode 100644index 00000000000..0aaa3237f1f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/unsafe-eval/eval-scripts-setTimeout-setInterval-report-only.html.headers@@ -0,0 +1 @@+Content-Security-Policy-Report-Only: script-src 'self' 'unsafe-inline' 'report-sample'diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.htmlnew file mode 100644index 00000000000..92c7143c856--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.html@@ -0,0 +1,34 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Timers run the default policy before the CSP check for string handlers</title>+<link rel="help" href="https://html.spec.whatwg.org/#timer-initialisation-steps">+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>+<script>+ const log = [];+ trustedTypes.createPolicy("default", {+ createScript: s => { log.push(`createScript ${s}`); return `rewritten ${s}`; }+ });++ function violationWithSample(sample) {+ return new Promise(resolve => {+ document.addEventListener("securitypolicyviolation", function listener(e) {+ if (e.sample === sample) {+ document.removeEventListener("securitypolicyviolation", listener);+ resolve(e);+ }+ });+ });+ }++ for (const method of ["setTimeout", "setInterval"]) {+ promise_test(async t => {+ log.length = 0;+ const violation = violationWithSample(`rewritten ${method}`);+ assert_equals(window[method](method, 0), 0);+ assert_array_equals(log, [`createScript ${method}`]);+ const e = await violation;+ assert_equals(e.blockedURI, "eval");+ }, `${method}() runs the default policy and then blocks the rewritten string handler`);+ }+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.html.headers b/Tests/LibWeb/Text/input/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.html.headersnew file mode 100644index 00000000000..fe6c047aa4f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/Window-setTimeout-setInterval-default-policy-before-csp.html.headers@@ -0,0 +1 @@+Content-Security-Policy: script-src 'self' 'unsafe-inline' 'report-sample'; require-trusted-types-for 'script'