Skip to content

Truly independent web browser

LibWeb: Check execCommand’s insertHTML value for Trusted Types first

sideshowbarkereda1df19b52e
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 64fd49943f8..9b26d0d581f 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -69,6 +69,7 @@
#include <LibWeb/ResizeObserver/ResizeObserver.h>
#include <LibWeb/SVG/SVGPatternElement.h>
#include <LibWeb/SVG/SVGUseElement.h>
+#include <LibWeb/TrustedTypes/TrustedHTML.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/XPath/EvaluateResult.h>
#include <LibWebCommon/CSS/PreferredColorScheme.h>
@@ -1174,7 +1175,7 @@ public:
No,
Yes,
};
- WebIDL::ExceptionOr<bool> exec_command(Utf16FlyString const& command, bool show_ui, Utf16View value);
+ WebIDL::ExceptionOr<bool> exec_command(Utf16FlyString const& command, bool show_ui, TrustedTypes::TrustedHTMLOrString const& value);
WebIDL::ExceptionOr<bool> exec_command_internal(Utf16FlyString const& command, bool show_ui, Utf16View value, DispatchInputEvent, Optional<Utf16FlyString> const& user_input_type = {}, GC::Ptr<StaticRange> deletion_range = nullptr);
WebIDL::ExceptionOr<bool> query_command_enabled(Utf16FlyString const& command);
WebIDL::ExceptionOr<bool> query_command_indeterm(Utf16FlyString const& command);
diff --git a/Libraries/LibWeb/DOM/Document.idl b/Libraries/LibWeb/DOM/Document.idl
index 8fe14828314..96e8eb6c409 100644
--- a/Libraries/LibWeb/DOM/Document.idl
+++ b/Libraries/LibWeb/DOM/Document.idl
@@ -97,7 +97,7 @@ partial interface Document {
readonly attribute WindowProxy? defaultView;
[ImplementedAs=has_focus_for_bindings] boolean hasFocus();
[CEReactions] attribute DOMString designMode;
- [CEReactions] boolean execCommand([FlyString] DOMString commandId, optional boolean showUI = false, optional DOMString value = "");
+ [CEReactions] boolean execCommand([FlyString] DOMString commandId, optional boolean showUI = false, optional (TrustedHTML or DOMString) value = "");
boolean queryCommandEnabled([FlyString] DOMString commandId);
boolean queryCommandIndeterm([FlyString] DOMString commandId);
boolean queryCommandState([FlyString] DOMString commandId);
diff --git a/Libraries/LibWeb/Editing/Commands.cpp b/Libraries/LibWeb/Editing/Commands.cpp
index 5b098325b0c..5f041d7e1e8 100644
--- a/Libraries/LibWeb/Editing/Commands.cpp
+++ b/Libraries/LibWeb/Editing/Commands.cpp
@@ -35,8 +35,6 @@
#include <LibWeb/Namespace.h>
#include <LibWeb/Selection/CaretNavigation.h>
#include <LibWeb/Selection/SelectionModifier.h>
-#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
-#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
namespace Web::Editing {
@@ -1564,12 +1562,8 @@ bool command_insert_html_action(DOM::Document& document, Utf16View value)
{
// 1. Set value to the result of invoking get trusted types compliant string with TrustedHTML, this's relevant
// global object, value, "Document execCommand", and "script".
- auto const resulting_value = MUST(TrustedTypes::get_trusted_type_compliant_string(
- TrustedTypes::TrustedTypeName::TrustedHTML,
- HTML::relevant_global_object(document),
- Utf16String::from_utf16(value),
- TrustedTypes::InjectionSink::Document_execCommand,
- TrustedTypes::Script.view()));
+ // NB: Document::exec_command() does this for a script's value; see the AD-HOC note there. So, the fragments below
+ // are parsed without the injection-sink check createContextualFragment() makes.
// 2. Delete the selection.
auto& selection = *document.get_selection();
@@ -1586,7 +1580,7 @@ bool command_insert_html_action(DOM::Document& document, Utf16View value)
GC::Ptr<DOM::DocumentFragment> fragment;
{
EditingHistory::ProxyMutationScope mutation_scope { *range->start_container() };
- auto result = range->create_contextual_fragment(resulting_value);
+ auto result = range->create_contextual_fragment(value.to_utf8_but_should_be_ported_to_utf16());
if (result.is_exception())
return false;
fragment = result.release_value();
@@ -1609,7 +1603,7 @@ bool command_insert_html_action(DOM::Document& document, Utf16View value)
// non-breaking space, just as it does when inserting text at the same boundary.
canonicalize_whitespace(range->start());
range = active_range(document);
- replace_selection_with_fragment(document, resulting_value);
+ replace_selection_with_fragment(document, value);
return true;
}
diff --git a/Libraries/LibWeb/Editing/ExecCommand.cpp b/Libraries/LibWeb/Editing/ExecCommand.cpp
index 1a069c0375c..32d13f097c9 100644
--- a/Libraries/LibWeb/Editing/ExecCommand.cpp
+++ b/Libraries/LibWeb/Editing/ExecCommand.cpp
@@ -30,6 +30,8 @@
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Page/EventHandler.h>
#include <LibWeb/Selection/Selection.h>
+#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
+#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
#include <LibWeb/UIEvents/InputEvent.h>
#include <LibWeb/UIEvents/InputTypes.h>
@@ -149,13 +151,37 @@ static bool clipboard_command_is_enabled(Document& document, Utf16FlyString cons
}
// https://w3c.github.io/editing/docs/execCommand/#execcommand()
-WebIDL::ExceptionOr<bool> Document::exec_command(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, Utf16View value)
+WebIDL::ExceptionOr<bool> Document::exec_command(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, TrustedTypes::TrustedHTMLOrString const& trusted_value)
{
// NB: Clipboard actions can delete through the internal editing entry point, but their script callbacks must
// not recursively execute public commands, including input listeners on text controls.
if (m_inside_clipboard_exec_command)
return false;
+ // AD-HOC: The spec gets the Trusted Types compliant string for an insertHTML value in step 1 of the insertHTML
+ // command's action. Get it here instead, where only a script's value arrives: The action also inserts the
+ // HTML a user pastes, which isn't an injection sink. And so a script's string is rejected even when the
+ // command isn't enabled, before any beforeinput event fires.
+ Utf16String compliant_value;
+ if (command.equals_ignoring_ascii_case(Editing::CommandNames::insertHTML)) {
+ // NB: See the AD-HOC note about recursive calls in exec_command_internal(). A default policy's createHTML
+ // callback runs the page's script, so that script mustn't run a command while this one gets its value.
+ if (m_inside_exec_command)
+ return false;
+ TemporaryChange guard_recursion { m_inside_exec_command, true };
+ compliant_value = TRY(TrustedTypes::get_trusted_type_compliant_string(
+ TrustedTypes::TrustedTypeName::TrustedHTML,
+ HTML::relevant_global_object(*this),
+ trusted_value,
+ TrustedTypes::InjectionSink::Document_execCommand,
+ TrustedTypes::Script.view()));
+ } else {
+ compliant_value = trusted_value.visit(
+ [](GC::Ref<TrustedTypes::TrustedHTML> const& html) { return html->to_string(); },
+ [](Utf16String const& string) { return string; });
+ }
+ Utf16View value = compliant_value;
+
// https://w3c.github.io/clipboard-apis/#integration-with-rich-text-editing
// These are the steps to follow when triggering copy, cut or paste actions through a scripting API:
// 1. Execute the corresponding action synchronously.
diff --git a/Libraries/LibWeb/Editing/ReplaceSelection.cpp b/Libraries/LibWeb/Editing/ReplaceSelection.cpp
index 467aa6f1781..f1c22559b65 100644
--- a/Libraries/LibWeb/Editing/ReplaceSelection.cpp
+++ b/Libraries/LibWeb/Editing/ReplaceSelection.cpp
@@ -445,13 +445,13 @@ static void replace_selection_with_inline_fragment(Layout::BegunRead const& read
fix_disallowed_ancestors_of_node(descendant);
}
-void replace_selection_with_fragment(DOM::Document& document, TrustedTypes::TrustedHTMLOrString const& value)
+void replace_selection_with_fragment(DOM::Document& document, Utf16View html)
{
Layout::ForcedReadScope read { document };
auto range = active_range(document);
VERIFY(range && range->collapsed());
- ReplacementFragment replacement_fragment { *range, value };
+ ReplacementFragment replacement_fragment { *range, html };
InsertedContent inserted_content { replacement_fragment.children() };
if (inserted_content.is_empty())
return;
diff --git a/Libraries/LibWeb/Editing/ReplaceSelection.h b/Libraries/LibWeb/Editing/ReplaceSelection.h
index c3b7ad86cb1..04d42ba742b 100644
--- a/Libraries/LibWeb/Editing/ReplaceSelection.h
+++ b/Libraries/LibWeb/Editing/ReplaceSelection.h
@@ -6,11 +6,11 @@
#pragma once
+#include <AK/Utf16View.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/TrustedTypes/TrustedHTML.h>
namespace Web::Editing {
-void replace_selection_with_fragment(DOM::Document&, TrustedTypes::TrustedHTMLOrString const&);
+void replace_selection_with_fragment(DOM::Document&, Utf16View html);
}
diff --git a/Libraries/LibWeb/Editing/ReplacementFragment.cpp b/Libraries/LibWeb/Editing/ReplacementFragment.cpp
index d2a61f40d18..ccf02ad9a54 100644
--- a/Libraries/LibWeb/Editing/ReplacementFragment.cpp
+++ b/Libraries/LibWeb/Editing/ReplacementFragment.cpp
@@ -119,10 +119,12 @@ static void remove_empty_inline_staging_wrappers(DOM::DocumentFragment& fragment
}
}
-ReplacementFragment::ReplacementFragment(DOM::Range& range, TrustedTypes::TrustedHTMLOrString const& value)
+ReplacementFragment::ReplacementFragment(DOM::Range& range, Utf16View html)
{
EditingHistory::ProxyMutationScope mutation_scope { *range.start_container() };
- m_fragment = MUST(range.create_contextual_fragment(value));
+ // NB: The HTML is either a script's insertHTML value, which execCommand() already got a Trusted Types compliant
+ // string for, or HTML the user pasted. So, it skips the injection-sink check createContextualFragment() makes.
+ m_fragment = MUST(range.create_contextual_fragment(html.to_utf8_but_should_be_ported_to_utf16()));
remove_formatting_whitespace_between_blocks(*m_fragment);
auto* first_leaf = m_fragment->first_child();
diff --git a/Libraries/LibWeb/Editing/ReplacementFragment.h b/Libraries/LibWeb/Editing/ReplacementFragment.h
index 042c1e89d98..f8e5c345623 100644
--- a/Libraries/LibWeb/Editing/ReplacementFragment.h
+++ b/Libraries/LibWeb/Editing/ReplacementFragment.h
@@ -6,10 +6,10 @@
#pragma once
+#include <AK/Utf16View.h>
#include <LibGC/Root.h>
#include <LibGC/RootVector.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/TrustedTypes/TrustedHTML.h>
namespace Web::Editing {
@@ -19,7 +19,7 @@ class ReplacementFragment {
AK_MAKE_NONCOPYABLE(ReplacementFragment);
public:
- ReplacementFragment(DOM::Range&, TrustedTypes::TrustedHTMLOrString const&);
+ ReplacementFragment(DOM::Range&, Utf16View html);
ReplacementFragment(ReplacementFragment&&) = default;
bool contains_block_content() const { return m_contains_block_content; }
diff --git a/Tests/LibWeb/Text/expected/Editing/clipboard-paste-html-with-trusted-types-enforced.txt b/Tests/LibWeb/Text/expected/Editing/clipboard-paste-html-with-trusted-types-enforced.txt
new file mode 100644
index 00000000000..abfe072de88
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/clipboard-paste-html-with-trusted-types-enforced.txt
@@ -0,0 +1,3 @@
+text: "abold and italicb"
+pasted bold: true
+violations: 0
diff --git a/Tests/LibWeb/Text/expected/Editing/execCommand-insertHTML-with-trusted-types-enforced.txt b/Tests/LibWeb/Text/expected/Editing/execCommand-insertHTML-with-trusted-types-enforced.txt
new file mode 100644
index 00000000000..3c00aa3a2fd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/execCommand-insertHTML-with-trusted-types-enforced.txt
@@ -0,0 +1,8 @@
+string: TypeError
+after string: ab
+TrustedHTML returned: true
+after TrustedHTML: a<b>trusted</b>b
+default policy returned: true
+after default policy: a<b>default</b>b
+default policy sinks: ["Document execCommand"]
+nested insertHTML from the default policy returned: false
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/Document-execCommand.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/Document-execCommand.txt
new file mode 100644
index 00000000000..ea0e8961746
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/Document-execCommand.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass Document.execCommand("insertHTML") works as usual.
+Pass Document.execCommand("paste") works as usual.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/block-Document-execCommand.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/block-Document-execCommand.txt
new file mode 100644
index 00000000000..2801cbf4350
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/block-Document-execCommand.txt
@@ -0,0 +1,11 @@
+Harness status: OK
+
+Found 6 tests
+
+6 Pass
+Pass Document.execCommand("insertHTML") throws.
+Pass Document.execCommand("insertHTML") works with a TrustedHTML argument.
+Pass Document.execCommand("paste") works as usual."
+Pass Document.execCommand("paste") works with a TrustedHTML argument.
+Pass Document.execCommand("insertHTML") works as usual with a default policy.
+Pass Document.execCommand("paste") works as usual with a default policy.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/trusted-types-secondary-document.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/trusted-types-secondary-document.txt
new file mode 100644
index 00000000000..5e484f700f3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/trusted-types-secondary-document.txt
@@ -0,0 +1,102 @@
+Harness status: OK
+
+Found 97 tests
+
+97 Pass
+Pass HTMLElement innerHTML throws with a plain string
+Pass HTMLElement setHTMLUnsafe throws with a plain string
+Pass ShadowRoot innerHTML throws with a plain string
+Pass ShadowRoot setHTMLUnsafe throws with a plain string
+Pass HTMLIFrameElement srcdoc throws with a plain string
+Pass HTMLScriptElement textContent throws with a plain string
+Pass HTMLScriptElement innerText throws with a plain string
+Pass HTMLScriptElement text throws with a plain string
+Pass Element insertAdjacentHTML throws with a plain string
+Pass Document execCommand throws with a plain string
+Pass Range createContextualFragment throws with a plain string
+Pass HTMLElement innerHTML works with a TrustedHTML
+Pass HTMLElement setHTMLUnsafe works with a TrustedHTML
+Pass ShadowRoot innerHTML works with a TrustedHTML
+Pass ShadowRoot setHTMLUnsafe works with a TrustedHTML
+Pass HTMLIFrameElement srcdoc works with a TrustedHTML
+Pass HTMLScriptElement textContent works with a TrustedScript
+Pass HTMLScriptElement innerText works with a TrustedScript
+Pass HTMLScriptElement text works with a TrustedScript
+Pass Element insertAdjacentHTML works with a TrustedHTML
+Pass Document execCommand works with a TrustedHTML
+Pass Trusted Type assignment required for Range createContextualFragment
+Pass Element.setAttribute throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Element.setAttribute throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Element.setAttribute throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Element.setAttribute throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Element.setAttribute throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Element.setAttribute throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Element.setAttributeNS throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Element.setAttributeNode throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Element.setAttributeNodeNS throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass NamedNodeMap.setNamedItem throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass NamedNodeMap.setNamedItemNS throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Attr.value throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Node.nodeValue throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a plain string
+Pass Node.textContent throws for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a plain string
+Pass Element.setAttribute works for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a TrustedScript input.
+Pass Element.setAttribute works for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a TrustedScript input.
+Pass Element.setAttribute works for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a TrustedScript input.
+Pass Element.setAttribute works for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a TrustedHTML input.
+Pass Element.setAttribute works for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a TrustedScriptURL input.
+Pass Element.setAttribute works for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a TrustedScriptURL input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/1999/xhtml, element=DIV, attrName=onclick with a TrustedScript input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/2000/svg, element=g, attrName=ondblclick with a TrustedScript input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/1998/Math/MathML, element=mrow, attrName=onmousedown with a TrustedScript input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/1999/xhtml, element=IFRAME, attrName=srcdoc with a TrustedHTML input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/1999/xhtml, element=SCRIPT, attrName=src with a TrustedScriptURL input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/2000/svg, element=script, attrName=href with a TrustedScriptURL input.
+Pass Element.setAttributeNS works for elementNS=http://www.w3.org/2000/svg, element=script, attrNS=http://www.w3.org/1999/xlink, attrName=href with a TrustedScriptURL input.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/Editing/clipboard-paste-html-with-trusted-types-enforced.html b/Tests/LibWeb/Text/input/Editing/clipboard-paste-html-with-trusted-types-enforced.html
new file mode 100644
index 00000000000..baf2cc2fc1b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/clipboard-paste-html-with-trusted-types-enforced.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
+<script src="../include.js"></script>
+<div id="editor" contenteditable="true">ab</div>
+<script>
+ promiseTest(async () => {
+ const platformControl = internals.MOD_CTRL | internals.MOD_SUPER;
+ const selection = getSelection();
+
+ let violations = 0;
+ document.addEventListener("securitypolicyviolation", () => ++violations);
+
+ editor.addEventListener("copy", event => {
+ event.clipboardData.setData("text/plain", "plain fallback");
+ event.clipboardData.setData("text/html", `<b id="bold">bold</b> and <i>italic</i>`);
+ event.preventDefault();
+ }, { once: true });
+
+ selection.setBaseAndExtent(editor.firstChild, 0, editor.firstChild, 1);
+ internals.sendKey(editor, "C", platformControl);
+ internals.dispatchUserActivatedEvent(editor, new Event("mousedown"));
+ await navigator.clipboard.read();
+
+ selection.collapse(editor.firstChild, 1);
+ const pasteInput = new Promise(resolve => editor.addEventListener("input", resolve, { once: true }));
+ internals.sendKey(editor, "V", platformControl);
+ await pasteInput;
+
+ println(`text: ${JSON.stringify(editor.textContent)}`);
+ println(`pasted bold: ${editor.querySelector("#bold") !== null}`);
+ println(`violations: ${violations}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/execCommand-insertHTML-with-trusted-types-enforced.html b/Tests/LibWeb/Text/input/Editing/execCommand-insertHTML-with-trusted-types-enforced.html
new file mode 100644
index 00000000000..c28df4e1cf4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/execCommand-insertHTML-with-trusted-types-enforced.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
+<script src="../include.js"></script>
+<div id="editor" contenteditable="true">ab</div>
+<script>
+ test(() => {
+ const selection = getSelection();
+ const reset = () => {
+ editor.textContent = "ab";
+ selection.collapse(editor.firstChild, 1);
+ };
+
+ reset();
+ try {
+ document.execCommand("insertHTML", false, "<b>string</b>");
+ println("string: no exception");
+ } catch (error) {
+ println(`string: ${error.name}`);
+ }
+ println(`after string: ${editor.innerHTML}`);
+
+ const policy = trustedTypes.createPolicy("policy", { createHTML: html => html });
+ reset();
+ println(`TrustedHTML returned: ${document.execCommand("insertHTML", false, policy.createHTML("<b>trusted</b>"))}`);
+ println(`after TrustedHTML: ${editor.innerHTML}`);
+
+ const sinks = [];
+ let nestedResult;
+ trustedTypes.createPolicy("default", { createHTML: (html, _, sink) => {
+ sinks.push(sink);
+ nestedResult = document.execCommand("insertHTML", false, "<i>nested</i>");
+ return html;
+ } });
+ reset();
+ println(`default policy returned: ${document.execCommand("insertHTML", false, "<b>default</b>")}`);
+ println(`after default policy: ${editor.innerHTML}`);
+ println(`default policy sinks: ${JSON.stringify(sinks)}`);
+ println(`nested insertHTML from the default policy returned: ${nestedResult}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/Document-execCommand.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/Document-execCommand.html
new file mode 100644
index 00000000000..9a5df50530a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/Document-execCommand.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<link rel="author" title="Daniel Vogelheim" href="mailto:[email protected]">
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<body>
+<script>
+ // Test that execCommand continues to work if Trusted Types is not enabled.
+ const commands = [ "insertHTML", "paste" ];
+ for (const command of commands) {
+ test(t => {
+ document.execCommand(command, false, "<em>Hello World</em>");
+ }, `Document.execCommand("${command}") works as usual.`);
+ }
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/block-Document-execCommand.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/block-Document-execCommand.html
new file mode 100644
index 00000000000..d094b0dd563
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/block-Document-execCommand.html
@@ -0,0 +1,48 @@
+<!DOCTYPE html>
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
+<link rel="author" title="Daniel Vogelheim" href="mailto:[email protected]">
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<body>
+<script>
+ // Tests that certain execCommand commands will observe Trusted Types if
+ // it's enforced.
+ const commands = [ "insertHTML", "paste" ];
+ const tt_commands = [ "insertHTML" ];
+
+ // A pass-through policy for testing.
+ const a_policy = trustedTypes.createPolicy("a policy", {"createHTML": x => x});
+
+ for (const command of commands) {
+ const requires_tt = tt_commands.includes(command);
+
+ // Test that execCommand with String throws, but only for commands that
+ // require TT.
+ if (requires_tt) {
+ test(t => {
+ assert_throws_js(TypeError, _ => document.execCommand(command, false, "<em>Hello World</em>"));
+ }, `Document.execCommand("${command}") throws.`);
+ } else {
+ test(t => {
+ document.execCommand(command, false, "<em>Hello World</em>");
+ }, `Document.execCommand("${command}") works as usual."`);
+ }
+ // Test that execCommand succeeds with a TrustedHTML argument.
+ test(t => {
+ document.execCommand(command, false, a_policy.createHTML("<em>Hello World</em>"));
+ }, `Document.execCommand("${command}") works with a TrustedHTML argument.`);
+ }
+
+ // Test that with a default policy, all comamnds will work again.
+ trustedTypes.createPolicy("default", {"createHTML": (x, _, sink) => {
+ assert_equals(sink, 'Document execCommand');
+ return x;
+ }});
+
+ for (const command of commands) {
+ test(t => {
+ document.execCommand(command, false, "<em>Hello World</em>");
+ }, `Document.execCommand("${command}") works as usual with a default policy.`);
+ }
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/trusted-types-secondary-document.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/trusted-types-secondary-document.html
new file mode 100644
index 00000000000..dd309fbbef2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/trusted-types-secondary-document.html
@@ -0,0 +1,340 @@
+<!DOCTYPE html>
+<head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="support/namespaces.js"></script>
+ <meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
+</head>
+<body>
+<script>
+const policyWithoutModification =
+ window.trustedTypes.createPolicy('policyWithoutModification', {
+ createHTML: s => s,
+ createScript: s => s,
+ createScriptURL: s => s,
+ });
+
+function createTrustedOutput(type, input) {
+ return type ?
+ policyWithoutModification[type.replace("Trusted", "create")](input) : input;
+}
+
+const secondaryDocument = document.implementation.createHTMLDocument("");
+const testData = [
+ {
+ name: "HTMLElement innerHTML",
+ subject: () => secondaryDocument.createElement("div"),
+ property: "innerHTML",
+ type: "TrustedHTML",
+ },
+ {
+ name: "HTMLElement setHTMLUnsafe",
+ subject: () => secondaryDocument.createElement("div"),
+ method: "setHTMLUnsafe",
+ type: "TrustedHTML",
+ },
+ {
+ name: "ShadowRoot innerHTML",
+ subject: () => {
+ const div = secondaryDocument.createElement("div");
+ return div.attachShadow({mode: 'open'});
+ },
+ property: "innerHTML",
+ type: "TrustedHTML",
+ },
+ {
+ name: "ShadowRoot setHTMLUnsafe",
+ subject: () => {
+ const div = secondaryDocument.createElement("div");
+ return div.attachShadow({mode: 'open'});
+ },
+ method: "setHTMLUnsafe",
+ type: "TrustedHTML",
+ },
+ {
+ name: "HTMLIFrameElement srcdoc",
+ subject: () => secondaryDocument.createElement("iframe"),
+ property: "srcdoc",
+ type: "TrustedHTML",
+ },
+ {
+ name: "HTMLScriptElement textContent",
+ subject: () => secondaryDocument.createElement("script"),
+ property: "textContent",
+ type: "TrustedScript",
+ },
+ {
+ name: "HTMLScriptElement innerText",
+ subject: () => secondaryDocument.createElement("script"),
+ property: "innerText",
+ type: "TrustedScript",
+ },
+ {
+ name: "HTMLScriptElement text",
+ subject: () => secondaryDocument.createElement("script"),
+ property: "text",
+ type: "TrustedScript",
+ },
+];
+
+for (let entry of testData) {
+ test(_ => {
+ const subject = entry.subject();
+ assert_throws_js(TypeError, _ => {
+ if (entry.property)
+ subject[entry.property] = "2+2";
+ else if (entry.method)
+ subject[entry.method]("2+2");
+ });
+ }, entry.name + " throws with a plain string");
+}
+
+test(_ => {
+ assert_throws_js(TypeError, _ => {
+ let element = secondaryDocument.createElement("div");
+ element.insertAdjacentHTML("afterbegin", "2+2");
+ });
+}, "Element insertAdjacentHTML throws with a plain string");
+
+test(_ => {
+ assert_throws_js(TypeError, _ => {
+ secondaryDocument.execCommand("insertHTML", false, "2+2");
+ });
+}, "Document execCommand throws with a plain string");
+
+test(_ => {
+ assert_throws_js(TypeError, _ => {
+ let range = secondaryDocument.createRange();
+ range.selectNodeContents(secondaryDocument.documentElement);
+ range.createContextualFragment("2+2");
+ });
+}, "Range createContextualFragment throws with a plain string");
+
+for (let entry of testData) {
+ test(_ => {
+ const subject = entry.subject();
+ let trustedInput = createTrustedOutput(entry.type, "somevalue");
+ if (entry.property)
+ subject[entry.property] = trustedInput;
+ else if (entry.method)
+ subject[entry.method](trustedInput);
+ }, entry.name + " works with a " + entry.type);
+}
+
+test(_ => {
+ let trustedInput = createTrustedOutput("TrustedHTML", "somevalue");
+ let element = secondaryDocument.createElement("div");
+ element.insertAdjacentHTML("afterbegin", trustedInput);
+}, "Element insertAdjacentHTML works with a TrustedHTML");
+
+test(_ => {
+ let trustedInput = createTrustedOutput("TrustedHTML", "somevalue");
+ secondaryDocument.execCommand("insertHTML", false, trustedInput);
+}, "Document execCommand works with a TrustedHTML");
+
+test(_ => {
+ assert_throws_js(TypeError, _ => {
+ let range = secondaryDocument.createRange();
+ range.selectNodeContents(secondaryDocument.documentElement);
+ range.createContextualFragment("1+1");
+ });
+}, "Trusted Type assignment required for Range createContextualFragment");
+
+const trustedTypeDataForAttribute = [
+ {
+ element: _ => secondaryDocument.createElement("div"),
+ attrNS: null,
+ attrName: "onclick",
+ sink: "Element onclick",
+ type: "TrustedScript"
+ },
+ {
+ element: _ => secondaryDocument.createElementNS(NSURI_SVG, "g"),
+ attrNS: null,
+ attrName: "ondblclick",
+ sink: "Element ondblclick",
+ type: "TrustedScript"
+ },
+ {
+ element: _ => secondaryDocument.createElementNS(NSURI_MATHML, "mrow"),
+ attrNS: null,
+ attrName: "onmousedown",
+ sink: "Element onmousedown",
+ type: "TrustedScript"
+ },
+ {
+ element: _ => secondaryDocument.createElement("iframe"),
+ attrNS: null,
+ attrName: "srcdoc",
+ sink: "HTMLIFrameElement srcdoc",
+ type: "TrustedHTML"
+ },
+ {
+ element: _ => secondaryDocument.createElement("script"),
+ attrNS: null,
+ attrName: "src",
+ sink: "HTMLScriptElement src",
+ type: "TrustedScriptURL"
+ },
+ {
+ element: _ => secondaryDocument.createElementNS(NSURI_SVG, "script"),
+ attrNS: null,
+ attrName: "href",
+ sink: "SVGScriptElement href",
+ type: "TrustedScriptURL"
+ },
+ {
+ element: _ => secondaryDocument.createElementNS(NSURI_SVG, "script"),
+ attrNS: NSURI_XLINK,
+ attrName: "href",
+ sink: "SVGScriptElement href",
+ type: "TrustedScriptURL"
+ },
+];
+
+function findAttribute(element, attrNS, attrName) {
+ for (let i = 0; i < element.attributes.length; i++) {
+ let attr = element.attributes[i];
+ if (attr.namespaceURI === attrNS &&
+ attr.localName === attrName) {
+ return attr;
+ }
+ }
+}
+
+const attributeSetterData = [
+ {
+ api: "Element.setAttribute",
+ acceptNS: false,
+ acceptTrustedTypeArgumentInIDL: true,
+ runSetter: function(element, attrNS, attrName, attrValue) {
+ assert_equals(attrNS, null);
+ this.lastAttributeNode = findAttribute(element, attrNS, attrName);
+ return element.setAttribute(attrName, attrValue);
+ },
+ },
+ {
+ api: "Element.setAttributeNS",
+ acceptNS: true,
+ acceptTrustedTypeArgumentInIDL: true,
+ runSetter: function(element, attrNS, attrName, attrValue) {
+ this.lastAttributeNode = findAttribute(element, attrNS, attrName);
+ return element.setAttributeNS(attrNS, attrName, attrValue);
+ },
+ },
+ {
+ api: "Element.setAttributeNode",
+ acceptNS: true,
+ setterClass: "setAttributeNode",
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ this.lastAttributeNode = secondaryDocument.createAttributeNS(attrNS, attrName);
+ this.lastAttributeNode.value = attrValue;
+ return element.setAttributeNode(this.lastAttributeNode);
+ },
+ },
+ {
+ api: "Element.setAttributeNodeNS",
+ acceptNS: true,
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ this.lastAttributeNode = document.createAttributeNS(attrNS, attrName);
+ this.lastAttributeNode.value = attrValue;
+ return element.setAttributeNodeNS(this.lastAttributeNode);
+ },
+ },
+ {
+ api: "NamedNodeMap.setNamedItem",
+ acceptNS: true,
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ const nodeMap = element.attributes;
+ this.lastAttributeNode = secondaryDocument.createAttributeNS(attrNS, attrName);
+ this.lastAttributeNode.value = attrValue;
+ return nodeMap.setNamedItem(this.lastAttributeNode);
+ },
+ },
+ {
+ api: "NamedNodeMap.setNamedItemNS",
+ acceptNS: true,
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ const nodeMap = element.attributes;
+ this.lastAttributeNode = secondaryDocument.createAttributeNS(attrNS, attrName);
+ this.lastAttributeNode.value = attrValue;
+ return nodeMap.setNamedItemNS(this.lastAttributeNode);
+ },
+ },
+ {
+ api:"Attr.value",
+ acceptNS: true,
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ element.setAttributeNS(attrNS, attrName, createTrustedOutput(type, ""));
+ this.lastAttributeNode = findAttribute(element, attrNS, attrName);
+ assert_true(!!this.lastAttributeNode);
+ return (this.lastAttributeNode.value = attrValue);
+ },
+ },
+ {
+ api: "Node.nodeValue",
+ acceptNS: true,
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ element.setAttributeNS(attrNS, attrName, createTrustedOutput(type, ""));
+ this.lastAttributeNode = findAttribute(element, attrNS, attrName);
+ assert_true(!!this.lastAttributeNode);
+ return (this.lastAttributeNode.nodeValue = attrValue);
+ },
+ },
+ {
+ api: "Node.textContent",
+ acceptNS: true,
+ runSetter: function(element, attrNS, attrName, attrValue, type) {
+ element.setAttributeNS(attrNS, attrName, createTrustedOutput(type, ""));
+ this.lastAttributeNode = findAttribute(element, attrNS, attrName);
+ assert_true(!!this.lastAttributeNode);
+ return (this.lastAttributeNode.textContent = attrValue);
+ },
+ },
+];
+
+// Set an attribute for each testcase of trustedTypeDataForAttribute. The CSP
+// rule and a null default policy will block those corresponding to trusted
+// type sinks.
+attributeSetterData.forEach(setterData => {
+ trustedTypeDataForAttribute.forEach(testData => {
+ if (testData.attrNS && !setterData.acceptNS) return;
+ test(() => {
+ let element = testData.element();
+ // This is a trusted type sink and should be blocked.
+ assert_throws_js(TypeError, () => {
+ setterData.runSetter(element, testData.attrNS, testData.attrName,
+ "neverset", testData.type);
+ });
+ }, `${setterData.api} throws for \
+elementNS=${testData.element().namespaceURI}, \
+element=${testData.element().tagName}, \
+${testData.attrNS ? 'attrNS='+testData.attrNS+', ' : ''} \
+attrName=${testData.attrName} with a plain string`);
+ });
+});
+
+
+ // For attributes that are trusted type sinks, try setting them to a value
+ // that has the expected trusted type.
+ attributeSetterData.filter(setterData => setterData.acceptTrustedTypeArgumentInIDL).forEach(setterData => {
+ trustedTypeDataForAttribute.forEach(testData => {
+ if (!testData.type) return;
+ if (testData.attrNS && !setterData.acceptNS) return;
+ test(() => {
+ let element = testData.element();
+ let trustedInput = createTrustedOutput(testData.type, "somevalue");
+ // Passing a trusted type should work normally.
+ setterData.runSetter(element, testData.attrNS, testData.attrName,
+ trustedInput, testData.type);
+ assert_equals(element.getAttributeNS(testData.attrNS,
+ testData.attrName), "somevalue");
+ }, `${setterData.api} works for \
+elementNS=${testData.element().namespaceURI}, \
+element=${testData.element().tagName}, \
+${testData.attrNS ? 'attrNS='+testData.attrNS+', ' : ''} \
+attrName=${testData.attrName} with a ${testData.type} input.`);
+ });
+ });
+</script>
+</body>