Truly independent web browser
LibWeb: Insert the sanitized clipboard fragment on paste
Shannon Boothc6e8828f2edd
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex b70de3695de..e29e47f9475 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1238,7 +1238,7 @@ public:Yes,};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> exec_command_internal(Utf16FlyString const& command, bool show_ui, Utf16View value, DispatchInputEvent, Optional<Utf16FlyString> const& user_input_type = {}, GC::Ptr<StaticRange> deletion_range = nullptr, GC::Ptr<DocumentFragment> pasted_fragment = nullptr);WebIDL::ExceptionOr<bool> query_command_enabled(Utf16FlyString const& command);WebIDL::ExceptionOr<bool> query_command_indeterm(Utf16FlyString const& command);WebIDL::ExceptionOr<bool> query_command_state(Utf16FlyString const& command);diff --git a/Libraries/LibWeb/DOM/EditingHostManager.cpp b/Libraries/LibWeb/DOM/EditingHostManager.cppindex 18a586cc8e0..c4ed08b2c03 100644--- a/Libraries/LibWeb/DOM/EditingHostManager.cpp+++ b/Libraries/LibWeb/DOM/EditingHostManager.cpp@@ -68,15 +68,17 @@ void EditingHostManager::handle_insert_from_clipboard(Utf16FlyString const& inpureturn;}- auto sanitized_html = Editing::sanitize_clipboard_html(*range, *html);- if (sanitized_html.is_exception() || sanitized_html.value().is_empty()) {+ auto fragment = Editing::sanitize_clipboard_html(*range, *html);+ if (fragment.is_exception() || !fragment.value()->has_children()) {handle_insert(input_type, plain_text);return;}// INTEROP: Rich editing hosts prefer text/html over text/plain when both clipboard representations are present.// Run insertHTML as one user edit so its DOM mutations and final selection form one undo unit.- auto editing_result = m_document->exec_command_internal(Editing::CommandNames::insertHTML, false, sanitized_html.value(), Document::DispatchInputEvent::Yes, input_type);+ // NB: insertHTML inserts the sanitized fragment itself. Serializing and reparsing it could produce a different+ // tree from the one the sanitizer inspected.+ auto editing_result = m_document->exec_command_internal(Editing::CommandNames::insertHTML, false, {}, Document::DispatchInputEvent::Yes, input_type, nullptr, fragment.value());if (editing_result.is_exception())dbgln("handle_insert_from_clipboard(): editing resulted in exception: {}", editing_result.exception());}diff --git a/Libraries/LibWeb/DOM/Range.cpp b/Libraries/LibWeb/DOM/Range.cppindex 85fd6772576..6c92cbd687b 100644--- a/Libraries/LibWeb/DOM/Range.cpp+++ b/Libraries/LibWeb/DOM/Range.cpp@@ -1473,7 +1473,7 @@ Gfx::DoubleRect Range::bounding_client_rect()// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-range-createcontextualfragment// NB: The steps after node, compliantString and compliantOptions have been determined.-static WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> create_contextual_fragment_for_node(GC::Ref<Node> node, StringView string, GC::Ptr<TrustedTypes::TrustedHTMLParserOptions> trusted_options)+static WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> create_contextual_fragment_for_node(GC::Ref<Node> node, StringView string, GC::Ptr<TrustedTypes::TrustedHTMLParserOptions> trusted_options, HTML::ParserScriptingMode scripting_mode){// 3. Let element be null.GC::Ptr<Element> element = nullptr;@@ -1499,7 +1499,7 @@ static WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> create_contextual_fragment// 7. Return the result of invoking the fragment parsing algorithm steps given element, compliantString,// compliantOptions, and Legacy.auto markup = Utf16String::from_utf8(string);- return Element::parse_fragment(Variant<GC::Ref<Element>, GC::Ref<DocumentFragment>> { *element }, markup.utf16_view(), HTML::ParserScriptingMode::Fragment, HTML::FragmentFastPath::Allow, trusted_options);+ return Element::parse_fragment(Variant<GC::Ref<Element>, GC::Ref<DocumentFragment>> { *element }, markup.utf16_view(), scripting_mode, HTML::FragmentFastPath::Allow, trusted_options);}// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-range-createcontextualfragment@@ -1516,14 +1516,14 @@ WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> Range::create_contextual_fragment// prevent scripts from executing when inserting the returned fragment.auto const [compliant_string, trusted_options] = TRY(HTML::get_trusted_type_compliant_input_for_legacy_sink(node, string, TrustedTypes::InjectionSink::Range_createContextualFragment, HTML::LegacySinkRunScripts::Yes));- return create_contextual_fragment_for_node(node, compliant_string.to_utf8_but_should_be_ported_to_utf16(), trusted_options);+ return create_contextual_fragment_for_node(node, compliant_string.to_utf8_but_should_be_ported_to_utf16(), trusted_options, HTML::ParserScriptingMode::Fragment);}// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-range-createcontextualfragment-WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> Range::create_contextual_fragment(StringView string, GC::Ptr<TrustedTypes::TrustedHTMLParserOptions> trusted_options)+WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> Range::create_contextual_fragment(StringView string, HTML::ParserScriptingMode scripting_mode){// 1. Let node be this's start node.- return create_contextual_fragment_for_node(*start_container(), string, trusted_options);+ return create_contextual_fragment_for_node(*start_container(), string, nullptr, scripting_mode);}}diff --git a/Libraries/LibWeb/DOM/Range.h b/Libraries/LibWeb/DOM/Range.hindex 63c2bbb4323..ab239d58d0f 100644--- a/Libraries/LibWeb/DOM/Range.h+++ b/Libraries/LibWeb/DOM/Range.h@@ -15,6 +15,7 @@#include <LibWeb/DOM/AbstractRange.h>#include <LibWeb/DOM/Node.h>#include <LibWeb/Export.h>+#include <LibWeb/HTML/Parser/ParserScriptingMode.h>#include <LibWeb/Selection/Selection.h>#include <LibWeb/TrustedTypes/TrustedHTML.h>#include <LibWebCommon/WebIDL/Types.h>@@ -106,7 +107,7 @@ public:void set_associated_selection(Badge<Selection::Selection>, GC::Ptr<Selection::Selection>);WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> create_contextual_fragment(TrustedTypes::TrustedHTMLOrString const&);- WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> create_contextual_fragment(StringView fragment, GC::Ptr<TrustedTypes::TrustedHTMLParserOptions> = nullptr);+ WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> create_contextual_fragment(StringView fragment, HTML::ParserScriptingMode = HTML::ParserScriptingMode::Fragment);template<typename Callback>void for_each_contained(Callback callback) constdiff --git a/Libraries/LibWeb/Editing/ClipboardSanitizer.cpp b/Libraries/LibWeb/Editing/ClipboardSanitizer.cppindex e8bdcdef979..dabf5b61d09 100644--- a/Libraries/LibWeb/Editing/ClipboardSanitizer.cpp+++ b/Libraries/LibWeb/Editing/ClipboardSanitizer.cpp@@ -14,7 +14,6 @@#include <LibWeb/HTML/AttributeNames.h>#include <LibWeb/HTML/Parser/ParserScriptingMode.h>#include <LibWeb/HTML/TagNames.h>-#include <LibWeb/HTML/XMLSerializer.h>namespace Web::Editing {@@ -56,12 +55,13 @@ static bool is_unsafe_attribute(DOM::Element const& element, DOM::Attr const& atreturn url.has_value() && url->scheme() == "javascript"sv;}-WebIDL::ExceptionOr<Utf16String> sanitize_clipboard_html(DOM::Range& range, Utf16View html)+WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> sanitize_clipboard_html(DOM::Range& range, Utf16View html){// INTEROP: Blink and WebKit parse native clipboard markup in a staging document with scripting disabled before// inserting it. Clipboard data is not TrustedHTML, even when it originated in another browser tab.+ // NB: Parse inert so that a script the checks below miss cannot run once the fragment is inserted.auto markup = Utf16String::from_utf16(html);- auto fragment = TRY(range.create_contextual_fragment(markup.to_utf8_but_should_be_ported_to_utf16()));+ auto fragment = TRY(range.create_contextual_fragment(markup.to_utf8_but_should_be_ported_to_utf16(), HTML::ParserScriptingMode::Inert));GC::RootVector<GC::Ref<DOM::Element>> active_elements;fragment->for_each_in_subtree([&](GC::Ref<DOM::Node> node) {auto* element = as_if<DOM::Element>(*node);@@ -84,7 +84,7 @@ WebIDL::ExceptionOr<Utf16String> sanitize_clipboard_html(DOM::Range& range, Utf1for (auto& element : active_elements.in_reverse())element->remove();- return fragment->serialize_fragment(HTML::RequireWellFormed::No);+ return fragment;}}diff --git a/Libraries/LibWeb/Editing/ClipboardSanitizer.h b/Libraries/LibWeb/Editing/ClipboardSanitizer.hindex 05bcab645f1..54f39836efc 100644--- a/Libraries/LibWeb/Editing/ClipboardSanitizer.h+++ b/Libraries/LibWeb/Editing/ClipboardSanitizer.h@@ -6,17 +6,13 @@#pragma once-#include <AK/Utf16String.h>+#include <AK/Utf16View.h>+#include <LibGC/Ptr.h>+#include <LibWeb/Forward.h>#include <LibWeb/WebIDL/ExceptionOr.h>-namespace Web::DOM {--class Range;--}-namespace Web::Editing {-WebIDL::ExceptionOr<Utf16String> sanitize_clipboard_html(DOM::Range&, Utf16View);+WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> sanitize_clipboard_html(DOM::Range&, Utf16View);}diff --git a/Libraries/LibWeb/Editing/Commands.cpp b/Libraries/LibWeb/Editing/Commands.cppindex 12f7dff9d3d..712cb45c506 100644--- a/Libraries/LibWeb/Editing/Commands.cpp+++ b/Libraries/LibWeb/Editing/Commands.cpp@@ -1559,7 +1559,7 @@ static Utf16String plain_text_of_fragment(DOM::DocumentFragment& fragment)}// https://w3c.github.io/editing/docs/execCommand/#the-inserthtml-command-bool command_insert_html_action(DOM::Document& document, Utf16View value)+static bool insert_html(DOM::Document& document, Variant<Utf16View, GC::Ref<DOM::DocumentFragment>> 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".@@ -1575,17 +1575,26 @@ bool command_insert_html_action(DOM::Document& document, Utf16View value)if (!range->start_container()->is_editable_or_editing_host())return true;+ // 4. Let frag be the result of calling createContextualFragment(value) on the active range.+ // NB: A user paste passes the fragment its sanitizer inspected, which is inserted as is.+ auto create_fragment = [&](DOM::Range& range) -> GC::Ptr<DOM::DocumentFragment> {+ return value.visit(+ [&](Utf16View html) -> GC::Ptr<DOM::DocumentFragment> {+ EditingHistory::ProxyMutationScope mutation_scope { *range.start_container() };+ auto result = range.create_contextual_fragment(html.to_utf8_but_should_be_ported_to_utf16());+ if (result.is_exception())+ return nullptr;+ return result.release_value();+ },+ [](GC::Ref<DOM::DocumentFragment> fragment) -> GC::Ptr<DOM::DocumentFragment> { return fragment; });+ };+// NB: See the INTEROP note at plain_text_of_fragment(). Insert the lines as text, separated by line breaks.if (auto editing_host = range->start_container()->editing_host(); is<HTML::HTMLElement>(editing_host.ptr())&& as<HTML::HTMLElement>(*editing_host).content_editable_state() == HTML::ContentEditableState::PlaintextOnly) {- GC::Ptr<DOM::DocumentFragment> fragment;- {- EditingHistory::ProxyMutationScope mutation_scope { *range->start_container() };- 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();- }+ auto fragment = create_fragment(*range);+ if (!fragment)+ return false;auto text = plain_text_of_fragment(*fragment);auto lines = text.utf16_view().split_view(u'\n', SplitBehavior::KeepEmpty);for (size_t i = 0; i < lines.size(); ++i) {@@ -1604,10 +1613,23 @@ 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, value);+ auto fragment = create_fragment(*range);+ if (!fragment)+ return false;+ replace_selection_with_fragment(document, *fragment);return true;}+bool command_insert_html_action(DOM::Document& document, Utf16View value)+{+ return insert_html(document, value);+}++bool insert_pasted_fragment(DOM::Document& document, DOM::DocumentFragment& fragment)+{+ return insert_html(document, GC::Ref { fragment });+}+// https://w3c.github.io/editing/docs/execCommand/#the-insertimage-commandbool command_insert_image_action(DOM::Document& document, Utf16View value){diff --git a/Libraries/LibWeb/Editing/Commands.h b/Libraries/LibWeb/Editing/Commands.hindex aad1bf5f80f..abf2cbca2aa 100644--- a/Libraries/LibWeb/Editing/Commands.h+++ b/Libraries/LibWeb/Editing/Commands.h@@ -52,6 +52,7 @@ bool command_forward_delete_action(DOM::Document&, Utf16View);bool command_indent_action(DOM::Document&, Utf16View);bool command_insert_horizontal_rule_action(DOM::Document&, Utf16View);bool command_insert_html_action(DOM::Document&, Utf16View);+bool insert_pasted_fragment(DOM::Document&, DOM::DocumentFragment&);bool command_insert_image_action(DOM::Document&, Utf16View);bool command_insert_linebreak_action(DOM::Document&, Utf16View);bool command_insert_ordered_list_action(DOM::Document&, Utf16View);diff --git a/Libraries/LibWeb/Editing/ExecCommand.cpp b/Libraries/LibWeb/Editing/ExecCommand.cppindex 32d13f097c9..1c50e32a3ab 100644--- a/Libraries/LibWeb/Editing/ExecCommand.cpp+++ b/Libraries/LibWeb/Editing/ExecCommand.cpp@@ -10,6 +10,7 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/ElementFactory.h>#include <LibWeb/DOM/Event.h>+#include <LibWeb/DOM/HTMLCollection.h>#include <LibWeb/DOM/Range.h>#include <LibWeb/DOM/StaticRange.h>#include <LibWeb/DOM/Text.h>@@ -219,7 +220,7 @@ WebIDL::ExceptionOr<bool> Document::exec_command(Utf16FlyString const& command,return exec_command_internal(command, show_ui, value, DispatchInputEvent::Yes);}-WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, Utf16View value, DispatchInputEvent dispatch_input_event, Optional<Utf16FlyString> const& user_input_type, GC::Ptr<StaticRange> deletion_range)+WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, Utf16View value, DispatchInputEvent dispatch_input_event, Optional<Utf16FlyString> const& user_input_type, GC::Ptr<StaticRange> deletion_range, GC::Ptr<DocumentFragment> pasted_fragment){// AD-HOC: This is not directly mentioned in the spec, but all major browsers limit editing API calls to HTML documentsif (!is_html_document())@@ -308,7 +309,8 @@ WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const&&& range_before_command && is<DOM::Text>(*range_before_command->start_container())// INTEROP: An Apple-interchange-newline represents an intentional paragraph boundary, not a fragment-ending// placeholder. Blink and WebKit preserve the destination paragraph's trailing break in this case.- && !value.contains(u"Apple-interchange-newline"sv);+ && !(pasted_fragment ? pasted_fragment->get_elements_by_class_name(u"Apple-interchange-newline"sv)->length() > 0+ : value.contains(u"Apple-interchange-newline"sv));GC::Root<DOM::Node> paste_start_block;if (paste_started_in_text_node)paste_start_block = Editing::block_node_of_node(*range_before_command->start_container());@@ -390,6 +392,10 @@ WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const&// 5. Take the action for command, passing value to the instructions as an argument.auto command_result = [&] {TemporaryChange running_action { m_running_editing_command_action, true };+ if (pasted_fragment) {+ VERIFY(command_definition.command == Editing::CommandNames::insertHTML);+ return Editing::insert_pasted_fragment(*this, *pasted_fragment);+ }return command_definition.action(*this, value);}();diff --git a/Libraries/LibWeb/Editing/ReplaceSelection.cpp b/Libraries/LibWeb/Editing/ReplaceSelection.cppindex f1c22559b65..2f832797ceb 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& readfix_disallowed_ancestors_of_node(descendant);}-void replace_selection_with_fragment(DOM::Document& document, Utf16View html)+void replace_selection_with_fragment(DOM::Document& document, DOM::DocumentFragment& fragment){Layout::ForcedReadScope read { document };auto range = active_range(document);VERIFY(range && range->collapsed());- ReplacementFragment replacement_fragment { *range, html };+ ReplacementFragment replacement_fragment { *range, fragment };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.hindex 04d42ba742b..4b67a0759c9 100644--- a/Libraries/LibWeb/Editing/ReplaceSelection.h+++ b/Libraries/LibWeb/Editing/ReplaceSelection.h@@ -6,11 +6,10 @@#pragma once-#include <AK/Utf16View.h>#include <LibWeb/Forward.h>namespace Web::Editing {-void replace_selection_with_fragment(DOM::Document&, Utf16View html);+void replace_selection_with_fragment(DOM::Document&, DOM::DocumentFragment&);}diff --git a/Libraries/LibWeb/Editing/ReplacementFragment.cpp b/Libraries/LibWeb/Editing/ReplacementFragment.cppindex ccf02ad9a54..fba16fc52c4 100644--- a/Libraries/LibWeb/Editing/ReplacementFragment.cpp+++ b/Libraries/LibWeb/Editing/ReplacementFragment.cpp@@ -119,12 +119,10 @@ static void remove_empty_inline_staging_wrappers(DOM::DocumentFragment& fragment}}-ReplacementFragment::ReplacementFragment(DOM::Range& range, Utf16View html)+ReplacementFragment::ReplacementFragment(DOM::Range& range, DOM::DocumentFragment& fragment)+ : m_fragment(fragment){EditingHistory::ProxyMutationScope mutation_scope { *range.start_container() };- // 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.hindex f8e5c345623..0016a683ffa 100644--- a/Libraries/LibWeb/Editing/ReplacementFragment.h+++ b/Libraries/LibWeb/Editing/ReplacementFragment.h@@ -6,7 +6,6 @@#pragma once-#include <AK/Utf16View.h>#include <LibGC/Root.h>#include <LibGC/RootVector.h>#include <LibWeb/Forward.h>@@ -19,7 +18,7 @@ class ReplacementFragment {AK_MAKE_NONCOPYABLE(ReplacementFragment);public:- ReplacementFragment(DOM::Range&, Utf16View html);+ ReplacementFragment(DOM::Range&, DOM::DocumentFragment&);ReplacementFragment(ReplacementFragment&&) = default;bool contains_block_content() const { return m_contains_block_content; }diff --git a/Tests/LibWeb/Text/expected/Editing/rich-paste-foreign-raw-text.txt b/Tests/LibWeb/Text/expected/Editing/rich-paste-foreign-raw-text.txtnew file mode 100644index 00000000000..2d9f56798f1--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/rich-paste-foreign-raw-text.txt@@ -0,0 +1,5 @@+input type: insertFromPaste+editor: seed<svg><noscript></svg><script>pastedScriptRan = true</script><img src=x onerror="pastedScriptRan = true"></noscript></svg>+script elements: 0+img elements: 0+pasted script ran: falsediff --git a/Tests/LibWeb/Text/input/Editing/rich-paste-foreign-raw-text.html b/Tests/LibWeb/Text/input/Editing/rich-paste-foreign-raw-text.htmlnew file mode 100644index 00000000000..7f72cce5014--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/rich-paste-foreign-raw-text.html@@ -0,0 +1,30 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<div id="editor" contenteditable="true">seed</div>+<script>+ asyncTest(async done => {+ const platformControl = internals.MOD_CTRL | internals.MOD_SUPER;+ const editor = document.getElementById("editor");+ window.pastedScriptRan = false;++ editor.focus();+ getSelection().selectAllChildren(editor);+ editor.addEventListener("copy", e => {+ e.preventDefault();+ e.clipboardData.setData("text/plain", "plain");+ e.clipboardData.setData("text/html", "<svg><noscript></svg><script>pastedScriptRan = true</script><img src=x onerror="pastedScriptRan = true"></noscript></svg>");+ }, { once: true });+ internals.sendKey(editor, "C", platformControl);++ getSelection().collapse(editor, 1);+ const inserted = new Promise(resolve => editor.addEventListener("input", resolve, { once: true }));+ internals.pasteFromClipboard();+ println(`input type: ${(await inserted).inputType}`);++ println(`editor: ${editor.innerHTML}`);+ println(`script elements: ${editor.querySelectorAll("script").length}`);+ println(`img elements: ${editor.querySelectorAll("img").length}`);+ println(`pasted script ran: ${pastedScriptRan}`);+ done();+ });+</script>