Truly independent web browser
LibWeb: Don't let a response's CSP break its own image document
Andreas Klingd7e7ae9f28f5
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cppindex 50b88d36da5..ba733bc93a8 100644--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp@@ -20,6 +20,7 @@#include <LibTextCodec/Decoder.h>#include <LibURL/URL.h>#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibWeb/CSS/CSSStyleProperties.h>#include <LibWeb/DOM/CustomEvent.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/DocumentLoading.h>@@ -28,6 +29,7 @@#include <LibWeb/Fetch/Response.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/HTMLHeadElement.h>+#include <LibWeb/HTML/HTMLImageElement.h>#include <LibWeb/HTML/HTMLLinkElement.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/NavigationParams.h>@@ -35,6 +37,7 @@#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWeb/HTML/Parser/IncrementalDocumentParser.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/SharedResourceRequest.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Loader/GeneratedPagesLoader.h>@@ -370,34 +373,30 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::Navreturn {};};- auto style_element = TRY(DOM::create_element(document, HTML::TagNames::style, Namespace::HTML));- style_element->string_replace_all(R"~~~(- :root {- background-color: #222;- }- img, video, audio {- position: absolute;- inset: 0;- max-width: 100vw;- max-height: 100vh;- margin: auto;- }- img {- background-color: #fff;- }- )~~~"_utf16);- TRY(document->head()->append_child(style_element));+ // NB: The Content-Security-Policy of the response applies to document, but must not block the user agent's own+ // styles. So set these declarations directly, not through a style element or attribute.+ auto set_host_element_style = [](DOM::Element& element, Utf16View declarations) {+ auto style = CSS::CSSStyleProperties::create_element_inline_style({ element });+ style->set_declarations_from_text(declarations);+ element.set_inline_style(style);+ };+ set_host_element_style(*document->document_element(), u"background-color: #222;"sv);+ auto host_element_style = u"position: absolute; inset: 0; max-width: 100vw; max-height: 100vh; margin: auto;"sv;auto url_string = document->url().to_string();auto url_utf16 = utf16_string_from_url_ascii(url_string);+ GC::Ptr<HTML::HTMLImageElement> image_element;if (type.is_image()) {auto img_element = TRY(DOM::create_element(document, HTML::TagNames::img, Namespace::HTML));+ image_element = as<HTML::HTMLImageElement>(*img_element);+ set_host_element_style(img_element, Utf16String::formatted("{} background-color: #fff;", host_element_style));img_element->set_attribute_value(HTML::AttributeNames::src, url_utf16);TRY(document->body()->append_child(img_element));TRY(insert_title(document, url_string));} else if (type.type() == "video"sv) {auto video_element = TRY(DOM::create_element(document, HTML::TagNames::video, Namespace::HTML));+ set_host_element_style(video_element, host_element_style);video_element->set_attribute_value(HTML::AttributeNames::src, url_utf16);video_element->set_attribute_value(HTML::AttributeNames::autoplay, Utf16String {});video_element->set_attribute_value(HTML::AttributeNames::controls, Utf16String {});@@ -406,6 +405,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::Nav} else if (type.type() == "audio"sv) {auto audio_element = TRY(DOM::create_element(document, HTML::TagNames::audio, Namespace::HTML));+ set_host_element_style(audio_element, host_element_style);audio_element->set_attribute_value(HTML::AttributeNames::src, url_utf16);audio_element->set_attribute_value(HTML::AttributeNames::autoplay, Utf16String {});audio_element->set_attribute_value(HTML::AttributeNames::controls, Utf16String {});@@ -432,11 +432,18 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::Nav// FIXME: We should not need to force the media file to load before saying that parsing has completed!// However, if we don't, then we get stuck in HTMLParser::the_end() waiting for the media file to load, which// never happens.- navigation_params.response->body()->fully_read(- realm,- GC::create_function(GC::Heap::the(), [document](ByteBuffer) { HTML::HTMLParser::the_end(document, nullptr); }),- GC::create_function(GC::Heap::the(), [](JS::Value) { }),- GC::Ref { realm.global_object() });+ auto stop_parsing = GC::create_function(GC::Heap::the(), [document] { HTML::HTMLParser::the_end(document, nullptr); });+ if (image_element) {+ // INTEROP: All major engines present the image from the response that was navigated to rather than fetching it+ // again. A second fetch would be subject to the Content-Security-Policy of that same response.+ image_element->set_resource_from_navigation_response(HTML::SharedResourceRequest::create_from_navigation_response_body(document, *navigation_params.response->body(), stop_parsing));+ } else {+ navigation_params.response->body()->fully_read(+ realm,+ GC::create_function(GC::Heap::the(), [stop_parsing](ByteBuffer) { stop_parsing->function()(); }),+ GC::create_function(GC::Heap::the(), [](JS::Value) { }),+ GC::Ref { realm.global_object() });+ }// 9. Return document.return document;diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Libraries/LibWeb/HTML/HTMLImageElement.cppindex 1f99b407379..bc7368f12d4 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLImageElement.cpp@@ -233,9 +233,15 @@ void HTMLImageElement::removed_from(IsSubtreeRoot is_subtree_root, DOM::Node* olm_last_auto_sizes_width = {};}+void HTMLImageElement::set_resource_from_navigation_response(GC::Ref<SharedResourceRequest> resource)+{+ m_resource_from_navigation_response = resource;+}+void HTMLImageElement::visit_edges(Cell::Visitor& visitor){Base::visit_edges(visitor);+ visitor.visit(m_resource_from_navigation_response);visitor.visit(m_current_request);visitor.visit(m_pending_request);visitor.visit(m_alt_text_node);@@ -1228,7 +1234,10 @@ after_step_7:// 17. Set image request to a new image request whose current URL is urlString.auto image_request = ImageRequest::create();- image_request->set_current_url(document(), *url_string, m_cors_setting);+ if (auto resource = exchange(m_resource_from_navigation_response, nullptr))+ image_request->set_current_url(*url_string, *resource);+ else+ image_request->set_current_url(document(), *url_string, m_cors_setting);image_request->set_current_pixel_density(pixel_density.value_or(1.0f));// 18. If the current request's state is unavailable or broken, then set the current request to image request.@@ -1363,7 +1372,10 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imagimage_request->set_state(ImageRequest::State::CompletelyAvailable);// 3. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.- originating_document->list_of_available_images().add(cache_key, *image_data, true);+ // NB: An image from a navigation response was not checked against the policies of the document, so other+ // elements must not get it from this list.+ if (image_request->shared_resource_request()->can_be_shared())+ originating_document->list_of_available_images().add(cache_key, *image_data, true);originating_document->prune_image_resource_caches();set_needs_layout_update_or_repaint_after_image_data_change();diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.h b/Libraries/LibWeb/HTML/HTMLImageElement.hindex 07dc82c45e0..e67850cb585 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.h+++ b/Libraries/LibWeb/HTML/HTMLImageElement.h@@ -97,6 +97,9 @@ public:void set_source_set(SourceSet);+ // NB: The next update of the image data presents this resource instead of fetching the image.+ void set_resource_from_navigation_response(GC::Ref<SharedResourceRequest>);+// https://html.spec.whatwg.org/multipage/embedded-content.html#the-img-element:dimension-attribute-sourceDOM::Element const& dimension_attribute_source() const;void set_dimension_attribute_source(DOM::Element const*);@@ -189,6 +192,7 @@ private:Optional<Utf16String> m_last_selected_source;// https://html.spec.whatwg.org/multipage/images.html#current-request+ GC::Ptr<SharedResourceRequest> m_resource_from_navigation_response;GC::Ptr<ImageRequest> m_current_request;// https://html.spec.whatwg.org/multipage/images.html#pending-requestdiff --git a/Libraries/LibWeb/HTML/ImageRequest.cpp b/Libraries/LibWeb/HTML/ImageRequest.cppindex eb05444d43b..827ac4893a9 100644--- a/Libraries/LibWeb/HTML/ImageRequest.cpp+++ b/Libraries/LibWeb/HTML/ImageRequest.cpp@@ -82,6 +82,13 @@ void ImageRequest::set_current_url(DOM::Document& document, Utf16String url, CORset_current_url(document, url.to_utf8(), cors_setting);}+void ImageRequest::set_current_url(Utf16String url, GC::Ref<SharedResourceRequest> shared_resource_request)+{+ m_current_url = move(url);+ stop_waiting_for_fetch();+ m_shared_resource_request = shared_resource_request;+}+// https://html.spec.whatwg.org/multipage/images.html#abort-the-image-requestvoid abort_the_image_request(GC::Ptr<ImageRequest> image_request){diff --git a/Libraries/LibWeb/HTML/ImageRequest.h b/Libraries/LibWeb/HTML/ImageRequest.hindex 721ed905af2..912585d62a9 100644--- a/Libraries/LibWeb/HTML/ImageRequest.h+++ b/Libraries/LibWeb/HTML/ImageRequest.h@@ -45,6 +45,7 @@ public:Utf16String const& current_url() const { return m_current_url; }void set_current_url(DOM::Document&, String, CORSSettingAttribute);void set_current_url(DOM::Document&, Utf16String, CORSSettingAttribute);+ void set_current_url(Utf16String, GC::Ref<SharedResourceRequest>);[[nodiscard]] GC::Ptr<DecodedImageData> image_data() const;void set_image_data(GC::Ptr<DecodedImageData>);diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp b/Libraries/LibWeb/HTML/SharedResourceRequest.cppindex c8b526ffe91..52752d0835e 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp@@ -63,6 +63,32 @@ GC::Ref<SharedResourceRequest> SharedResourceRequest::get_or_create(DOM::Documenreturn get_or_create(document, { request.url(), cors_setting, request.integrity_metadata(), request.referrer_policy() });}+GC::Ref<SharedResourceRequest> SharedResourceRequest::create_from_navigation_response_body(DOM::Document& document, Fetch::Infrastructure::Body const& body, GC::Ref<GC::Function<void()>> on_body_read)+{+ auto request = GC::Heap::the().allocate<SharedResourceRequest>(document.page(), Key { document.url(), CORSSettingAttribute::NoCORS, {}, ReferrerPolicy::ReferrerPolicy::EmptyString }, document);+ request->m_can_be_shared = false;+ request->m_state = State::Fetching;+ // NB: The element that presents the image may start to wait for it only after the body has been read.+ request->m_load_event_delayer.emplace(document);++ GC::Weak weak_request { *request };+ auto process_body = GC::create_function(GC::Heap::the(), [weak_request, on_body_read](ByteBuffer data) {+ // NB: A document for an SVG image is an XML document, so this is never an SVG image.+ if (auto request = weak_request.ptr())+ request->handle_successful_fetch(request->url(), IsSVGImage::No, move(data), false);+ on_body_read->function()();+ });+ auto process_body_error = GC::create_function(GC::Heap::the(), [weak_request, on_body_read](JS::Value) {+ if (auto request = weak_request.ptr())+ request->handle_failed_fetch();+ on_body_read->function()();+ });++ auto& realm = HTML::relevant_realm(document);+ body.fully_read(realm, process_body, process_body_error, GC::Ref { realm.global_object() });+ return request;+}+SharedResourceRequest::SharedResourceRequest(GC::Ref<Page> page, Key key, GC::Ref<DOM::Document> document): m_page(page), m_key(move(key))diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.h b/Libraries/LibWeb/HTML/SharedResourceRequest.hindex 845b1329f18..b163fbbb2a1 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.h+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.h@@ -37,9 +37,16 @@ public:[[nodiscard]] static GC::Ref<SharedResourceRequest> get_or_create(DOM::Document&, URL::URL const&, CORSSettingAttribute);[[nodiscard]] static GC::Ref<SharedResourceRequest> get_or_create(DOM::Document&, Fetch::Infrastructure::Request const&);+ // Creates a request that loads the resource from the body of the response that the document was navigated to,+ // instead of fetching it. No fetch checks this resource against the policies of the document, so it is only for+ // the element that presents it, and get_or_create() never returns it.+ // Calls on_body_read once reading the body has ended, whether or not that succeeded.+ [[nodiscard]] static GC::Ref<SharedResourceRequest> create_from_navigation_response_body(DOM::Document&, Fetch::Infrastructure::Body const&, GC::Ref<GC::Function<void()>> on_body_read);+virtual ~SharedResourceRequest() override;URL::URL const& url() const { return m_key.url; }+ [[nodiscard]] bool can_be_shared() const { return m_can_be_shared; }[[nodiscard]] GC::Ptr<DecodedImageData> image_data() const;[[nodiscard]] bool can_be_pruned_from_memory_cache() const;@@ -114,6 +121,7 @@ private:bool m_fetch_has_user_without_callbacks { false };Key m_key;+ bool m_can_be_shared { true };GC::Ptr<DecodedImageData> m_image_data;GC::Ptr<Fetch::Infrastructure::FetchController> m_fetch_controller;u64 m_cache_touch_serial { 0 };diff --git a/Tests/LibWeb/Text/expected/HTML/image-document-content-security-policy.txt b/Tests/LibWeb/Text/expected/HTML/image-document-content-security-policy.txtindex 195cc7cc1e8..2fd441da380 100644--- a/Tests/LibWeb/Text/expected/HTML/image-document-content-security-policy.txt+++ b/Tests/LibWeb/Text/expected/HTML/image-document-content-security-policy.txt@@ -1,4 +1,5 @@-Image size: 0x0-Root background: rgba(0, 0, 0, 0)-Image position: static+Image size: 120x120+Root background: rgb(34, 34, 34)+Image position: absoluteOther image: blocked by img-src+Same image: blocked by img-srcdiff --git a/Tests/LibWeb/Text/input/HTML/image-document-content-security-policy.html b/Tests/LibWeb/Text/input/HTML/image-document-content-security-policy.htmlindex 402d3be8a93..9d793a6e950 100644--- a/Tests/LibWeb/Text/input/HTML/image-document-content-security-policy.html+++ b/Tests/LibWeb/Text/input/HTML/image-document-content-security-policy.html@@ -15,13 +15,14 @@println(`Root background: ${getComputedStyle(imageDocument.documentElement).backgroundColor}`);println(`Image position: ${getComputedStyle(image).position}`);- const otherImage = imageDocument.createElement("img");- const otherImageResult = await new Promise(resolve => {- imageDocument.addEventListener("securitypolicyviolation", event => resolve(`blocked by ${event.effectiveDirective}`));- otherImage.onload = () => resolve("loaded");- otherImage.src = "../../Assets/120.png";- imageDocument.body.appendChild(otherImage);+ const loadImage = url => new Promise(resolve => {+ imageDocument.addEventListener("securitypolicyviolation", event => resolve(`blocked by ${event.effectiveDirective}`), { once: true });+ const newImage = imageDocument.createElement("img");+ newImage.onload = () => resolve("loaded");+ newImage.src = url;+ imageDocument.body.appendChild(newImage);});- println(`Other image: ${otherImageResult}`);+ println(`Other image: ${await loadImage("../../Assets/120.png")}`);+ println(`Same image: ${await loadImage(imageDocument.URL)}`);});</script>