Skip to content

Truly independent web browser

LibWeb: Only trust script text that the HTML parser inserted

Tim Ledbetter50c9f48515c0
diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp
index 6d230599a68..b781dd479a9 100644
--- a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp
@@ -645,9 +645,31 @@ void HTMLOrSVGScriptElement::prepare_script()
}
}
+void HTMLOrSVGScriptElement::set_script_text_from_parser()
+{
+ // https://w3c.github.io/trusted-types/dist/spec/#setting-slot-values-from-parser
+ // NOTE: The above algorithm doesn’t account for the case when the script element’s content is changed mid-parse.
+ // Implementors must ensure they protect against this case.
+ // See https://github.com/w3c/trusted-types/issues/507.
+ if (m_children_changed_by_api)
+ return;
+
+ m_script_text = as_element().child_text_content();
+}
+
+void HTMLOrSVGScriptElement::ParserChildrenChangeScope::begin_changing_children(DOM::Element& element)
+{
+ m_script_element = as_if<HTMLOrSVGScriptElement>(element);
+ if (m_script_element)
+ m_was_changing_children = exchange(m_script_element->m_parser_is_changing_children, true);
+}
+
// https://html.spec.whatwg.org/multipage/scripting.html#script-processing-model:children-changed-steps
void HTMLOrSVGScriptElement::script_element_children_changed(DOM::Node::ChildrenChangedMetadata const& metadata)
{
+ if (!m_parser_is_changing_children)
+ m_children_changed_by_api = true;
+
// AD-HOC: Avoid running script on child removal, matching the behaviour of other browsers.
// We also do not run script on child mutation, matching the behaviour of chromium and webkit.
// See: https://github.com/whatwg/html/issues/12279
diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h
index 51af3b00d3b..6d75ebcac76 100644
--- a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h
+++ b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h
@@ -9,14 +9,17 @@
#include <AK/Badge.h>
#include <AK/Function.h>
+#include <AK/Noncopyable.h>
#include <AK/Utf16String.h>
#include <LibWeb/DOM/DocumentLoadEventDelayer.h>
+#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/Forward.h>
#include <LibWeb/HTML/CORSSettingAttribute.h>
#include <LibWeb/HTML/Scripting/ImportMapParseResult.h>
#include <LibWeb/HTML/Scripting/Script.h>
#include <LibWeb/HTML/Scripting/ScriptFetchOptions.h>
+#include <LibWeb/HTML/TagNames.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
@@ -51,6 +54,31 @@ public:
void set_source_line_number(Badge<HTMLParser>, size_t source_line_number) { m_source_line_number = source_line_number; }
void set_string_text(Utf16View value) { m_script_text = Utf16String::from_utf16(value); }
+ void set_script_text_from_parser();
+
+ class ParserChildrenChangeScope {
+ AK_MAKE_NONCOPYABLE(ParserChildrenChangeScope);
+ AK_MAKE_NONMOVABLE(ParserChildrenChangeScope);
+
+ public:
+ explicit ParserChildrenChangeScope(DOM::Node& parent)
+ {
+ if (auto* element = as_if<DOM::Element>(parent); element && element->local_name() == TagNames::script)
+ begin_changing_children(*element);
+ }
+
+ ~ParserChildrenChangeScope()
+ {
+ if (m_script_element)
+ m_script_element->m_parser_is_changing_children = m_was_changing_children;
+ }
+
+ private:
+ void begin_changing_children(DOM::Element&);
+
+ HTMLOrSVGScriptElement* m_script_element { nullptr };
+ bool m_was_changing_children { false };
+ };
virtual DOM::Element& as_element() = 0;
virtual DOM::Element const& as_element() const = 0;
@@ -142,6 +170,9 @@ private:
// https://www.w3.org/TR/trusted-types/#htmlscriptelement-script-text
Utf16String m_script_text;
+
+ bool m_parser_is_changing_children { false };
+ bool m_children_changed_by_api { false };
};
}
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 3621111b995..8b8a32f280d 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -406,7 +406,7 @@ bool HTMLParser::process_script_end_tag_from_rust_parser(HTMLScriptElement& scri
// https://w3c.github.io/trusted-types/dist/spec/#setting-slot-values-from-parser
// Set script’s script text value to its child text content.
- script.set_string_text(script.child_text_content());
+ script.set_script_text_from_parser();
// If the active speculative HTML parser is null, then prepare the script element script.
// This might cause some script to execute, which might cause new characters to be inserted into the tokenizer,
@@ -2924,6 +2924,7 @@ struct NodeAndOffset {
static void insert_node_for_parser(DOM::Node& parent, DOM::Node& node, DOM::Node* child)
{
+ HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { parent };
if (!parent.is_tracked_by_style_engine()) {
parent.parser_insert_before(node, child);
return;
@@ -3013,6 +3014,7 @@ extern "C" void ladybird_html_parser_insert_text(size_t parent, size_t offset, u
auto data = text_node_data_from_span(ReadonlySpan<char> { reinterpret_cast<char const*>(data_ptr), data_len });
if (auto* previous_text = as_if<DOM::Text>(insertion_location.previous_child())) {
+ HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { parent_node };
(void)previous_text->append_data(data);
return;
}
@@ -3290,8 +3292,7 @@ extern "C" bool ladybird_html_parser_is_shadow_host(size_t node)
extern "C" void ladybird_html_parser_set_script_text_from_parser(size_t element)
{
// Set script's script text value to its child text content.
- auto& script = as<HTMLScriptElement>(node_from_html_parser_ffi(element));
- script.set_string_text(script.child_text_content());
+ as<HTMLScriptElement>(node_from_html_parser_ffi(element)).set_script_text_from_parser();
}
}
diff --git a/Tests/LibWeb/Text/expected/HTML/script-text-replaced-while-parsing-with-trusted-types.txt b/Tests/LibWeb/Text/expected/HTML/script-text-replaced-while-parsing-with-trusted-types.txt
new file mode 100644
index 00000000000..7d463e9fc27
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/script-text-replaced-while-parsing-with-trusted-types.txt
@@ -0,0 +1,2 @@
+Inline script under require-trusted-types-for: ran
+Inline script whose text a mutation observer replaced while parsing: blocked
diff --git a/Tests/LibWeb/Text/input/HTML/script-text-replaced-while-parsing-with-trusted-types.html b/Tests/LibWeb/Text/input/HTML/script-text-replaced-while-parsing-with-trusted-types.html
new file mode 100644
index 00000000000..012065bd3e7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/script-text-replaced-while-parsing-with-trusted-types.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const observerURL = await server.createEcho("GET", "/script-text-replaced-while-parsing-observer.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: `new MutationObserver((records, observer) => {
+ const script = document.getElementById("target");
+ if (script && script.firstChild) {
+ observer.disconnect();
+ script.firstChild.data = 'parent.postMessage("replaced", "*");';
+ }
+ }).observe(document.documentElement, { subtree: true, childList: true });`,
+ });
+ const doneURL = await server.createEcho("GET", "/script-text-replaced-while-parsing-done.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: `parent.postMessage("done", "*");`,
+ });
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const documentURL = await server.createEcho("GET", "/script-text-replaced-while-parsing.html", {
+ status: 200,
+ headers: {
+ "Content-Type": "text/html",
+ "Content-Security-Policy": "require-trusted-types-for 'script'",
+ },
+ body: `<!DOCTYPE html>
+ ${scriptStartTag}>parent.postMessage("untouched", "*");${scriptEndTag}
+ ${scriptStartTag} src="${observerURL}">${scriptEndTag}
+ ${scriptStartTag} id="target">parent.postMessage("original", "*");${scriptEndTag}
+ ${scriptStartTag} src="${doneURL}">${scriptEndTag}`,
+ });
+
+ const received = [];
+ const finished = new Promise(resolve => {
+ window.addEventListener("message", event => {
+ if (event.data === "done") {
+ resolve();
+ } else {
+ received.push(event.data);
+ }
+ });
+ });
+ const frame = document.createElement("iframe");
+ frame.src = documentURL;
+ document.body.appendChild(frame);
+ await finished;
+
+ const untouched = received.includes("untouched") ? "ran" : "blocked";
+ const replaced = received.includes("replaced") ? "ran" : "blocked";
+ println(`Inline script under require-trusted-types-for: ${untouched}`);
+ println(`Inline script whose text a mutation observer replaced while parsing: ${replaced}`);
+ });
+</script>