Skip to content

Truly independent web browser

LibWeb/SVG: Fetch external scripts with HTML's fetch a classic script

Luke Wilde4907f9d3b4a1
diff --git a/Libraries/LibWeb/SVG/SVGScriptElement.cpp b/Libraries/LibWeb/SVG/SVGScriptElement.cpp
index 5664bf475f4..0f3e8145227 100644
--- a/Libraries/LibWeb/SVG/SVGScriptElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGScriptElement.cpp
@@ -7,17 +7,13 @@
#include <AK/ScopeGuard.h>
#include <AK/Utf16String.h>
-#include <LibCore/ImmutableBytes.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/Fetch/Fetching/Fetching.h>
-#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
-#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
-#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>
#include <LibWeb/HTML/AttributeNames.h>
#include <LibWeb/HTML/CORSSettingAttribute.h>
-#include <LibWeb/HTML/PotentialCORSRequest.h>
+#include <LibWeb/HTML/HTMLScriptElement.h>
#include <LibWeb/HTML/Scripting/ClassicScript.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/Fetching.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/SVG/AttributeNames.h>
#include <LibWeb/SVG/SVGScriptElement.h>
@@ -36,6 +32,7 @@ void SVGScriptElement::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
SVGURIReferenceMixin::visit_edges(visitor);
+ visitor.visit(m_preparation_time_document);
visitor.visit(m_script);
}
@@ -98,6 +95,10 @@ void SVGScriptElement::process_the_script_element()
}
}
+ // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
+ // 16. Set el's preparation-time document to its node document.
+ m_preparation_time_document = document();
+
// 2. If the 'script' element references external script content, then the external script content
// using the current value of the 'xlink:href' attribute is fetched. Further processing of the
// 'script' element is dependent on the external script content, and will block here until the
@@ -112,20 +113,30 @@ void SVGScriptElement::process_the_script_element()
}
auto script_url = maybe_script_url.release_value();
- // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
- // 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.
+ // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
+ // 23. If el has a charset attribute, then let encoding be the result of getting an encoding from the value of
+ // the charset attribute. If el does not have a charset attribute, or if getting an encoding failed, then
+ // let encoding be el's node document's encoding.
+ // NB: An SVG script element has no charset attribute.
+ auto encoding = document().encoding_or_default();
+
+ // 24. Let classic script CORS setting be the current state of el's crossorigin content attribute.
auto crossorigin = get_attribute(HTML::AttributeNames::crossorigin);
auto cors_setting = HTML::cors_setting_attribute_from_keyword(crossorigin.map([](auto const& value) { return value.utf16_view(); }));
- auto request = HTML::create_potential_CORS_request(script_url, Fetch::Infrastructure::Request::Destination::Script, cors_setting);
- // 2. Set request's client to settings object.
- request->set_client(document().relevant_settings_object().address());
+ // 25-31. Let options be a script fetch options for el.
+ // NB: An SVG script element has no integrity or fetchpriority attribute.
+ auto referrer_policy_attribute = get_attribute(HTML::AttributeNames::referrerpolicy).value_or({});
+ auto referrer_policy = ReferrerPolicy::from_string(referrer_policy_attribute).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);
+ auto options = HTML::script_element_fetch_options({
+ .crossorigin = cors_setting,
+ .cryptographic_nonce = nonce(),
+ .referrer_policy = referrer_policy,
+ .parser_inserted = is_parser_inserted(),
+ });
- // FIXME: 3. Set request's initiator type to "script".
- // FIXME: 4. Set up the classic script request given request and options.
- request->set_parser_metadata(m_parser_inserted
- ? Fetch::Infrastructure::Request::ParserMetadata::ParserInserted
- : Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);
+ // 32. Let settings object be el's node document's relevant settings object.
+ auto& settings_object = document().relevant_settings_object();
// 3. The 'script' element's "already processed" flag is set to true.
// We set this before dispatching the fetch so that re-entrant calls (e.g. from attribute_changed
@@ -133,29 +144,20 @@ void SVGScriptElement::process_the_script_element()
// semantics. The in-flight fetch is allowed to finish.
m_already_processed = true;
- m_document_load_event_delayer.emplace(*m_document);
+ // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
+ // 33.8. Set el's delaying the load event to true.
+ m_document_load_event_delayer.emplace(*m_preparation_time_document);
+
+ // 33.11. Switch on el's type: "classic": Fetch a classic script given url, settings object, options, classic
+ // script CORS setting, encoding, and onComplete.
+ auto on_complete = HTML::create_on_fetch_script_complete(heap(), [self = GC::Ref { *this }](GC::Ptr<HTML::Script> script) {
+ self->finish_external_script_fetch(as<HTML::ClassicScript>(script.ptr()));
+ });
+ HTML::fetch_classic_script(HTML::relevant_realm(*this), script_url, settings_object, move(options), cors_setting, move(encoding), on_complete);
+ // 35.5.1. Set el's parser document's pending parsing-blocking script to el.
if (m_parser_inserted)
m_document->set_pending_parsing_blocking_svg_script(this);
-
- Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };
- fetch_algorithms_input.process_response_consume_body
- = [self = GC::Ref { *this }, script_url](auto response, auto body_bytes) {
- // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
- // 6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.
- auto muted_errors = response->is_cors_cross_origin() ? HTML::ClassicScript::MutedErrors::Yes : HTML::ClassicScript::MutedErrors::No;
- if (response->is_network_error()) {
- self->finish_external_script_fetch(script_url, {}, muted_errors);
- return;
- }
-
- body_bytes.visit(
- [&](Core::ImmutableBytes& bytes) { self->finish_external_script_fetch(script_url, bytes.bytes(), muted_errors); },
- [&](auto) { self->finish_external_script_fetch(script_url, {}, muted_errors); });
- };
-
- (void)Fetch::Fetching::fetch(HTML::relevant_realm(*this), request,
- Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
return;
}
@@ -174,20 +176,19 @@ void SVGScriptElement::process_the_script_element()
execute_script();
}
-void SVGScriptElement::finish_external_script_fetch(URL::URL const& script_url, ReadonlyBytes body, HTML::ClassicScript::MutedErrors muted_errors)
+void SVGScriptElement::finish_external_script_fetch(GC::Ptr<HTML::ClassicScript> script)
{
- if (!body.is_empty() && in_a_document_tree() && !is_scripting_disabled()) {
- auto script_content = Utf16String::try_from_utf8({ body });
- if (script_content.is_error())
- dbgln("Failed to decode SVG external script as UTF-8");
- else
- m_script = HTML::ClassicScript::create(script_url.basename(), script_content.release_value(),
- HTML::relevant_settings_object(*this), m_document->base_url(), m_source_line_number, muted_errors);
- }
+ if (in_a_document_tree() && !is_scripting_disabled())
+ m_script = script;
if (m_parser_inserted) {
+ // https://html.spec.whatwg.org/multipage/scripting.html#mark-as-ready
+ // 4. Set el's delaying the load event to false.
+ m_document_load_event_delayer.clear();
+
+ // NB: The parser that waits for a parser-inserted script is its preparation-time document's.
m_ready_to_be_parser_executed = true;
- m_document->schedule_html_parser_end_check();
+ m_preparation_time_document->schedule_html_parser_end_check();
return;
}
@@ -199,7 +200,6 @@ void SVGScriptElement::execute_pending_parser_blocking_script(Badge<HTML::HTMLPa
{
VERIFY(m_ready_to_be_parser_executed);
m_ready_to_be_parser_executed = false;
- ScopeGuard clear_delayer { [&] { m_document_load_event_delayer.clear(); } };
execute_script();
}
@@ -209,6 +209,12 @@ void SVGScriptElement::execute_script()
// script is executed. Note that at this point, these steps may be re-entrant if the execution
// of the script results in further 'script' elements being inserted into the document.
+ // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-element
+ // 1. Let document be el's node document.
+ // 2. If el's preparation-time document is not equal to document, then return.
+ if (m_preparation_time_document.ptr() != &document())
+ return;
+
// m_script is null when the external fetch failed; the parser-blocking slot still needs to be drained
// so the parser can resume, but there's no script to run.
if (!m_script)
diff --git a/Libraries/LibWeb/SVG/SVGScriptElement.h b/Libraries/LibWeb/SVG/SVGScriptElement.h
index 820b2347e61..df9530809c5 100644
--- a/Libraries/LibWeb/SVG/SVGScriptElement.h
+++ b/Libraries/LibWeb/SVG/SVGScriptElement.h
@@ -47,9 +47,12 @@ private:
virtual void visit_edges(Cell::Visitor&) override;
virtual void adopted_from(DOM::Document&) override;
- void finish_external_script_fetch(URL::URL const& script_url, ReadonlyBytes body, HTML::ClassicScript::MutedErrors);
+ void finish_external_script_fetch(GC::Ptr<HTML::ClassicScript>);
void execute_script();
+ // https://html.spec.whatwg.org/multipage/scripting.html#preparation-time-document
+ GC::Ptr<DOM::Document> m_preparation_time_document;
+
bool m_already_processed { false };
bool m_parser_inserted { false };
bool m_ready_to_be_parser_executed { false };
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/svg-script-nonce.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/svg-script-nonce.txt
new file mode 100644
index 00000000000..65028863499
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/svg-script-nonce.txt
@@ -0,0 +1 @@
+executed: matching-nonce
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-decoding.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-decoding.txt
new file mode 100644
index 00000000000..17f1f46933d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-decoding.txt
@@ -0,0 +1,4 @@
+header charset: e9
+document encoding: c3 a9
+byte order mark: e9
+malformed byte: fffd
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-moved-to-another-document.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-moved-to-another-document.txt
new file mode 100644
index 00000000000..3f3ec1ee57a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-moved-to-another-document.txt
@@ -0,0 +1,3 @@
+ran in the original document: false
+ran in the document it moved to: false
+ran in the test's document: false
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-moved-while-parser-waits.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-moved-while-parser-waits.txt
new file mode 100644
index 00000000000..9e0f5722cfa
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-moved-while-parser-waits.txt
@@ -0,0 +1,3 @@
+parser: parser went on
+ran in the original document: false
+ran in the document it moved to: false
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-parser-order.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-parser-order.txt
new file mode 100644
index 00000000000..4b51d2531a7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-parser-order.txt
@@ -0,0 +1 @@
+executed: before, first, second, after
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-redirect.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-redirect.txt
new file mode 100644
index 00000000000..5c326f8caf7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-redirect.txt
@@ -0,0 +1,3 @@
+error filename: the request's URL
+error line: 3
+import resolved against: the response's URL
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-request-setup.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-request-setup.txt
new file mode 100644
index 00000000000..5b408264587
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-request-setup.txt
@@ -0,0 +1,3 @@
+initiator type: script
+referrer without referrerpolicy: sent
+referrer with referrerpolicy="no-referrer": none
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/svg-script-nonce.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/svg-script-nonce.html
new file mode 100644
index 00000000000..9b1e4ea306b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/svg-script-nonce.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // An SVG script element's request carries the element's nonce, so a policy that allows the nonce allows its script.
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const createScript = name =>
+ server.createEcho("GET", `/svg-script-nonce-${name}.js`, {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: `globalThis.executedScripts.push(${JSON.stringify(name)});`,
+ });
+ const matchingNonceURL = await createScript("matching-nonce");
+ const otherNonceURL = await createScript("other-nonce");
+
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageBody = `<!DOCTYPE html>
+ ${scriptStartTag} nonce="fixed">globalThis.executedScripts = [];${scriptEndTag}
+ <svg xmlns="http://www.w3.org/2000/svg">
+ ${scriptStartTag} nonce="fixed" href="${matchingNonceURL}">${scriptEndTag}
+ ${scriptStartTag} nonce="other" href="${otherNonceURL}">${scriptEndTag}
+ </svg>
+ ${scriptStartTag} nonce="fixed">parent.postMessage(executedScripts.join(", ") || "none", "*");${scriptEndTag}`;
+ const pageURL = await server.createEcho("GET", "/svg-script-nonce.html", {
+ status: 200,
+ headers: {
+ "Content-Type": "text/html",
+ "Content-Security-Policy": "script-src 'nonce-fixed'",
+ },
+ body: pageBody,
+ });
+
+ window.addEventListener(
+ "message",
+ event => {
+ println(`executed: ${event.data}`);
+ done();
+ },
+ { once: true }
+ );
+
+ const frame = document.createElement("iframe");
+ frame.src = pageURL;
+ document.body.appendChild(frame);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-decoding.html b/Tests/LibWeb/Text/input/SVG/svg-script-decoding.html
new file mode 100644
index 00000000000..0b29432dbc3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-decoding.html
@@ -0,0 +1,59 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // An SVG script is decoded with the charset of its Content-Type, or else its document's encoding, unless it starts
+ // with a byte order mark, and a malformed byte decodes to U+FFFD.
+ asyncTest(async done => {
+ const server = httpTestServer();
+
+ // The body pushes the case's name and a string literal holding the given bytes, given as a binary string.
+ const createScript = (name, contentType, bytes, prefix = "") =>
+ server.createEcho("GET", `/svg-script-decoding-${name.replaceAll(" ", "-")}.js`, {
+ status: 200,
+ headers: { "Content-Type": contentType },
+ body: btoa(`${prefix}results.push([${JSON.stringify(name)}, "${bytes}"]);`),
+ body_encoding: "base64",
+ });
+ const headerCharsetURL = await createScript("header charset", "text/javascript; charset=utf-8", "\xC3\xA9");
+ const documentEncodingURL = await createScript("document encoding", "text/javascript", "\xC3\xA9");
+ const byteOrderMarkURL = await createScript(
+ "byte order mark",
+ "text/javascript; charset=windows-1252",
+ "\xC3\xA9",
+ "\xEF\xBB\xBF"
+ );
+ const malformedByteURL = await createScript("malformed byte", "text/javascript; charset=utf-8", "\xFF");
+
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageURL = await server.createEcho("GET", "/svg-script-decoding.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html; charset=windows-1252" },
+ body: `<!DOCTYPE html>
+ ${scriptStartTag}>globalThis.results = [];${scriptEndTag}
+ <svg xmlns="http://www.w3.org/2000/svg">
+ ${scriptStartTag} href="${headerCharsetURL}">${scriptEndTag}
+ ${scriptStartTag} href="${documentEncodingURL}">${scriptEndTag}
+ ${scriptStartTag} href="${byteOrderMarkURL}">${scriptEndTag}
+ ${scriptStartTag} href="${malformedByteURL}">${scriptEndTag}
+ </svg>
+ ${scriptStartTag}>
+ const codePoints = text => [...text].map(code => code.codePointAt(0).toString(16)).join(" ");
+ parent.postMessage(results.map(([name, text]) => name + ": " + codePoints(text)).join("\\n"), "*");
+ ${scriptEndTag}`,
+ });
+
+ window.addEventListener(
+ "message",
+ event => {
+ println(event.data);
+ done();
+ },
+ { once: true }
+ );
+
+ const frame = document.createElement("iframe");
+ frame.src = pageURL;
+ document.body.appendChild(frame);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-moved-to-another-document.html b/Tests/LibWeb/Text/input/SVG/svg-script-moved-to-another-document.html
new file mode 100644
index 00000000000..af90c78eb35
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-moved-to-another-document.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // An SVG script moved to another document while its script is fetched runs in neither document. Both documents
+ // stay active, and both finish loading.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const scriptToken = `svg-script-moved-script-${crypto.randomUUID()}`;
+
+ // Each response's first byte arrives at once, and the rest once its token is unblocked.
+ const heldURL = async (path, contentType, body, token) =>
+ (await server.createEcho("GET", path, {
+ status: 200,
+ headers: { "Content-Type": contentType, "Cache-Control": "no-store" },
+ body,
+ })) + `?chunks=1&chunk_unblock_tokens=${token}`;
+ const scriptURL = await heldURL(
+ "/svg-script-moved-to-another-document.js",
+ "text/javascript",
+ "self.svgScriptRan = true;",
+ scriptToken
+ );
+
+ // Each document keeps loading until its image arrives, and the script's fetch delays the load event of one of
+ // them, so that both have loaded only once the script is fetched.
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const openFrame = async name => {
+ const imageToken = `svg-script-moved-${name}-image-${crypto.randomUUID()}`;
+ const imageURL = await heldURL(`/svg-script-moved-${name}.png`, "image/png", "xx", imageToken);
+ const pageURL = await server.createEcho("GET", `/svg-script-moved-${name}.html`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html>
+ <svg xmlns="http://www.w3.org/2000/svg"></svg>
+ ${scriptStartTag}>parent.postMessage("${name} parsed", "*");${scriptEndTag}
+ <img src="${imageURL}">`,
+ });
+ const frame = document.createElement("iframe");
+ const parsed = new Promise(resolve => {
+ const listener = event => {
+ if (event.data !== `${name} parsed`)
+ return;
+ window.removeEventListener("message", listener);
+ resolve();
+ };
+ window.addEventListener("message", listener);
+ });
+ const loaded = new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+ frame.src = pageURL;
+ document.body.append(frame);
+ await parsed;
+ return { frame, imageToken, loaded };
+ };
+ const original = await openFrame("original");
+ const destination = await openFrame("destination");
+
+ const originalDocument = original.frame.contentDocument;
+ const script = originalDocument.createElementNS("http://www.w3.org/2000/svg", "script");
+ script.setAttribute("href", scriptURL);
+ originalDocument.querySelector("svg").append(script);
+ await server.waitForRequest(scriptURL);
+
+ destination.frame.contentDocument.querySelector("svg").append(script);
+ await fetch(`${server.baseURL}/unblock/${original.imageToken}`);
+ await fetch(`${server.baseURL}/unblock/${destination.imageToken}`);
+ await fetch(`${server.baseURL}/unblock/${scriptToken}`);
+ await Promise.all([original.loaded, destination.loaded]);
+
+ println(`ran in the original document: ${original.frame.contentWindow.svgScriptRan === true}`);
+ println(`ran in the document it moved to: ${destination.frame.contentWindow.svgScriptRan === true}`);
+ println(`ran in the test's document: ${window.svgScriptRan === true}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-moved-to-another-document.html.headers b/Tests/LibWeb/Text/input/SVG/svg-script-moved-to-another-document.html.headers
new file mode 100644
index 00000000000..156209f9c81
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-moved-to-another-document.html.headers
@@ -0,0 +1 @@
+Content-Type: text/html
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-moved-while-parser-waits.html b/Tests/LibWeb/Text/input/SVG/svg-script-moved-while-parser-waits.html
new file mode 100644
index 00000000000..f7878afef70
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-moved-while-parser-waits.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A parser-inserted SVG script moved to another document while its parser waits for its script runs in neither
+ // document, and its parser goes on.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const token = `svg-script-moved-while-parser-waits-${crypto.randomUUID()}`;
+
+ // The response's first byte arrives at once, and the rest once the token is unblocked.
+ const scriptURL =
+ (await server.createEcho("GET", "/svg-script-moved-while-parser-waits.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript", "Cache-Control": "no-store" },
+ body: "self.svgScriptRan = true;",
+ })) + `?chunks=1&chunk_unblock_tokens=${token}`;
+
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageURL = await server.createEcho("GET", "/svg-script-moved-while-parser-waits.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html>
+ <svg xmlns="http://www.w3.org/2000/svg">${scriptStartTag} href="${scriptURL}">${scriptEndTag}</svg>
+ ${scriptStartTag}>parent.postMessage("parser went on", "*");${scriptEndTag}`,
+ });
+
+ const frame = document.createElement("iframe");
+ const parserWentOn = new Promise(resolve => window.addEventListener("message", resolve, { once: true }));
+ frame.src = pageURL;
+ document.body.append(frame);
+ await server.waitForRequest(scriptURL);
+
+ const destination = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ document.body.append(destination);
+ destination.append(frame.contentDocument.querySelector("svg script"));
+ await fetch(`${server.baseURL}/unblock/${token}`);
+
+ println(`parser: ${(await parserWentOn).data}`);
+ println(`ran in the original document: ${frame.contentWindow.svgScriptRan === true}`);
+ println(`ran in the document it moved to: ${window.svgScriptRan === true}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-moved-while-parser-waits.html.headers b/Tests/LibWeb/Text/input/SVG/svg-script-moved-while-parser-waits.html.headers
new file mode 100644
index 00000000000..156209f9c81
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-moved-while-parser-waits.html.headers
@@ -0,0 +1 @@
+Content-Type: text/html
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-parser-order.html b/Tests/LibWeb/Text/input/SVG/svg-script-parser-order.html
new file mode 100644
index 00000000000..73a6590e56d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-parser-order.html
@@ -0,0 +1,46 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A parser-inserted SVG script blocks the parser until it has run, or until its fetch has failed, as it does for a
+ // response whose status is not ok, whose body does not run.
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const createScript = (name, status) =>
+ server.createEcho("GET", `/svg-script-parser-order-${name}.js`, {
+ status,
+ headers: { "Content-Type": "text/javascript" },
+ body: `executed.push(${JSON.stringify(name)});`,
+ });
+ const notFoundURL = await createScript("not-found", 404);
+ const firstURL = await createScript("first", 200);
+ const secondURL = await createScript("second", 200);
+
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageURL = await server.createEcho("GET", "/svg-script-parser-order.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html>
+ ${scriptStartTag}>globalThis.executed = ["before"];${scriptEndTag}
+ <svg xmlns="http://www.w3.org/2000/svg">
+ ${scriptStartTag} href="${notFoundURL}">${scriptEndTag}
+ ${scriptStartTag} href="${firstURL}">${scriptEndTag}
+ ${scriptStartTag} href="${secondURL}">${scriptEndTag}
+ </svg>
+ ${scriptStartTag}>executed.push("after"); parent.postMessage(executed.join(", "), "*");${scriptEndTag}`,
+ });
+
+ window.addEventListener(
+ "message",
+ event => {
+ println(`executed: ${event.data}`);
+ done();
+ },
+ { once: true }
+ );
+
+ const frame = document.createElement("iframe");
+ frame.src = pageURL;
+ document.body.appendChild(frame);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-redirect.html b/Tests/LibWeb/Text/input/SVG/svg-script-redirect.html
new file mode 100644
index 00000000000..905ad2fb108
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-redirect.html
@@ -0,0 +1,76 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A redirected SVG script resolves its relative imports against the response's URL, and reports its errors with
+ // the request's URL and their line in the script.
+ asyncTest(async done => {
+ const server = httpTestServer();
+ await server.createEcho("GET", "/svg-script-redirect/target/module.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: `export const resolvedAgainst = "the response's URL";`,
+ });
+ const targetURL = await server.createEcho("GET", "/svg-script-redirect/target/script.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: [
+ `import("./module.js").then(module => importSettled(module.resolvedAgainst),`,
+ ` () => importSettled("failed"));`,
+ `throw new Error("thrown on line 3");`,
+ ].join("\n"),
+ });
+ const requestURL = await server.createEcho("GET", "/svg-script-redirect-source.js", {
+ status: 302,
+ headers: { "Location": targetURL },
+ body: "",
+ });
+
+ // The page reports the script's error and the result of its import once it has both. Its SVG script is below
+ // the page's first lines, so the script's lines are not the page's.
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageURL = await server.createEcho("GET", "/svg-script-redirect.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html>
+ ${scriptStartTag}>
+ const results = {};
+ const reportOnceSettled = () => {
+ if ("filename" in results && "importResult" in results)
+ parent.postMessage(results, "*");
+ };
+ addEventListener("error", event => {
+ results.filename = event.filename;
+ results.line = event.lineno;
+ reportOnceSettled();
+ });
+ globalThis.importSettled = result => {
+ results.importResult = result;
+ reportOnceSettled();
+ };
+ ${scriptEndTag}
+ <svg xmlns="http://www.w3.org/2000/svg">
+ ${scriptStartTag} href="${requestURL}">${scriptEndTag}
+ </svg>`,
+ });
+
+ window.addEventListener(
+ "message",
+ event => {
+ const urlNames = new Map([
+ [requestURL, "the request's URL"],
+ [targetURL, "the response's URL"],
+ ]);
+ println(`error filename: ${urlNames.get(event.data.filename) ?? event.data.filename}`);
+ println(`error line: ${event.data.line}`);
+ println(`import resolved against: ${event.data.importResult}`);
+ done();
+ },
+ { once: true }
+ );
+
+ const frame = document.createElement("iframe");
+ frame.src = pageURL;
+ document.body.appendChild(frame);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-request-setup.html b/Tests/LibWeb/Text/input/SVG/svg-script-request-setup.html
new file mode 100644
index 00000000000..754e2154675
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-request-setup.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<svg xmlns="http://www.w3.org/2000/svg"></svg>
+<script>
+ // An SVG script element's request has "script" as its initiator type, and the referrer policy of the element's
+ // referrerpolicy attribute.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const svg = document.querySelector("svg");
+
+ const ranScripts = new Map();
+ window.scriptRan = name => ranScripts.get(name)();
+
+ const runScript = async (name, referrerPolicy) => {
+ const url = await server.createEcho("GET", `/svg-script-request-setup-${name}.js`, {
+ status: 200,
+ headers: { "Content-Type": "text/javascript", "Cache-Control": "no-store" },
+ body: `scriptRan(${JSON.stringify(name)});`,
+ });
+ const ran = new Promise(resolve => ranScripts.set(name, resolve));
+ const script = document.createElementNS("http://www.w3.org/2000/svg", "script");
+ if (referrerPolicy !== null)
+ script.setAttribute("referrerpolicy", referrerPolicy);
+ script.setAttribute("href", url);
+ svg.append(script);
+ await ran;
+ return url;
+ };
+
+ const resourceTimingEntry = url =>
+ new Promise(resolve => {
+ const observer = new PerformanceObserver(list => {
+ const entry = list.getEntriesByName(url)[0];
+ if (entry) {
+ observer.disconnect();
+ resolve(entry);
+ }
+ });
+ observer.observe({ type: "resource", buffered: true });
+ });
+
+ const referrerSent = async url => {
+ const headers = await (await fetch(server.recordedRequestHeadersURL(url))).json();
+ return headers["Referer"] !== undefined ? "sent" : "none";
+ };
+
+ const defaultURL = await runScript("default", null);
+ const noReferrerURL = await runScript("no-referrer", "no-referrer");
+
+ const entry = await resourceTimingEntry(defaultURL);
+ println(`initiator type: ${entry.initiatorType}`);
+ println(`referrer without referrerpolicy: ${await referrerSent(defaultURL)}`);
+ println(`referrer with referrerpolicy="no-referrer": ${await referrerSent(noReferrerURL)}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-request-setup.html.headers b/Tests/LibWeb/Text/input/SVG/svg-script-request-setup.html.headers
new file mode 100644
index 00000000000..156209f9c81
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-request-setup.html.headers
@@ -0,0 +1 @@
+Content-Type: text/html