Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(preload): share destination validation before load admission

ldm0d86a023c3577
diff --git a/moli-core/tests/fetch_behaviors.rs b/moli-core/tests/fetch_behaviors.rs
index a01845a1a..27f28a3dd 100644
--- a/moli-core/tests/fetch_behaviors.rs
+++ b/moli-core/tests/fetch_behaviors.rs
@@ -12,6 +12,9 @@ use tokio::time::Duration;
#[path = "fetch_behaviors/preload_lifecycle.rs"]
mod preload_lifecycle;
+#[path = "fetch_behaviors/preload_as.rs"]
+mod preload_as;
+
fn diagnostic_global<'a>(page: &'a Page, name: &str) -> Option<&'a JsValueSnapshot> {
page.script_execution().global(name)
}
diff --git a/moli-core/tests/fetch_behaviors/preload_as.rs b/moli-core/tests/fetch_behaviors/preload_as.rs
new file mode 100644
index 000000000..3ab6a9ab8
--- /dev/null
+++ b/moli-core/tests/fetch_behaviors/preload_as.rs
@@ -0,0 +1,40 @@
+use super::*;
+
+#[tokio::test(flavor = "multi_thread")]
+async fn preload_as_admission_matches_parser_and_dynamic_links() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let mut config = AppConfig::default();
+ config.set_optional_resource_fetch_mask(moli_page_types::OptionalResourceFetchMask::ALL);
+ let browser = Browser::new(config)?;
+ let mut page = browser.fetch(&server.url("/static")).await?;
+ for context in ["top-dynamic", "top-parser"] {
+ let result = tokio::time::timeout(
+ Duration::from_secs(15),
+ page.evaluate_runtime_expression_with_await_async(
+ &format!(
+ "({}).then(JSON.stringify)",
+ include_str!("../fixtures/preload-as.js")
+ ),
+ true,
+ ),
+ )
+ .await??;
+ let observed: serde_json::Value = serde_json::from_str(
+ result["value"]
+ .as_str()
+ .expect("preload destination observations"),
+ )?;
+ assert_eq!(observed["context"], context, "{observed}");
+ assert_eq!(observed["observations"].as_array().unwrap().len(), 36);
+ assert_eq!(observed["failures"], serde_json::json!([]), "{observed}");
+ assert_eq!(observed["recovered"], true, "{observed}");
+ if context == "top-dynamic" {
+ let mut url = url::Url::parse(&server.url("/compat/child-dynamic-markup-document"))?;
+ url.query_pairs_mut()
+ .append_pair("markup", observed["parserMarkup"].as_str().unwrap());
+ page = browser.fetch(url.as_str()).await?;
+ }
+ }
+ server.shutdown().await;
+ Ok(())
+}
diff --git a/moli-core/tests/fixtures/preload-as.js b/moli-core/tests/fixtures/preload-as.js
new file mode 100644
index 000000000..40a35efcb
--- /dev/null
+++ b/moli-core/tests/fixtures/preload-as.js
@@ -0,0 +1,75 @@
+(async () => {
+ const failures = [];
+ const observations = [];
+ const resource = new URL(globalThis.preloadProbeResourcePath || '/static', location.href);
+ const cases = [
+ [null, false], ['', false], [' ', false],
+ ['garbagefoobar', false], ['audio', false], ['video', false],
+ ['object', false], ['iframe', false], ['worklet', false],
+ ['json', false], ['text', false], ['worker', false],
+ ['audioworklet', false], ['paintworklet', false], ['serviceworker', false],
+ ['sharedworker', false], ['document', false], ['embed', false],
+ ['frame', false], ['manifest', false], ['report', false],
+ ['webidentity', false], ['xslt', false],
+ [' fetch', false], ['fetch ', false], ['\tfetch\n', false],
+ ['\u00a0fetch', false], [' style ', false], [' script ', false],
+ ['fetch', true], ['FETCH', true], ['script', true],
+ ['style', true], ['image', true], ['font', true], ['track', true]
+ ];
+ const href = (context, index) => {
+ const url = new URL(resource);
+ url.searchParams.set('preload_probe', context + '-' + index);
+ return url.href;
+ };
+ const escape = value => value.replaceAll('&', '&amp;').replaceAll('"', '&quot;');
+ const install = (doc, context) => cases.map(([value], index) => {
+ const link = doc.createElement('link');
+ link.rel = 'preload';
+ if (value !== null) link.setAttribute('as', value);
+ link.href = href(context, index);
+ const events = [];
+ link.onload = event => events.push(event.type);
+ link.onerror = event => events.push(event.type);
+ doc.head.append(link);
+ return {link, events};
+ });
+
+ const parsed = Array.from(document.querySelectorAll('link[data-preload-probe]'));
+ const context = parsed.length ? 'top-parser' : 'top-dynamic';
+ const topLinks = parsed.length
+ ? parsed.map((link, index) => ({link, events: window.preloadEvents[index]}))
+ : install(document, context);
+ const parserMarkup = '<!doctype html><head><script>window.preloadEvents = ' +
+ JSON.stringify(cases.map(() => [])) + ';<' + '/script>' +
+ cases.map(([value], index) => '<link data-preload-probe rel="preload" ' +
+ (value === null ? '' : 'as="' + escape(value) + '" ') +
+ 'href="' + escape(href('top-parser', index)) + '" ' +
+ 'onload="preloadEvents[' + index + '].push(event.type)" ' +
+ 'onerror="preloadEvents[' + index + '].push(event.type)">').join('') +
+ '</head><body>parser';
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ for (let index = 0; index < cases.length; ++index) {
+ const [value, supported] = cases[index];
+ const {link, events} = topLinks[index];
+ const count = performance.getEntriesByName(link.href).length;
+ observations.push({context, value, count, events});
+ if (count !== Number(supported))
+ failures.push([context, value, 'resource entries', count]);
+ if (events.length !== Number(supported))
+ failures.push([context, value, 'terminal events', events]);
+ }
+
+ // Unsupported input must not permanently mark a link as already processed.
+ const recovery = topLinks[0];
+ const recovered = await new Promise(resolve => {
+ recovery.link.onload = () => resolve(true);
+ recovery.link.onerror = () => resolve(false);
+ recovery.link.as = 'FETCH';
+ setTimeout(() => resolve(false), 2000);
+ });
+ if (!recovered || performance.getEntriesByName(recovery.link.href).length !== 1)
+ failures.push(['missing-to-fetch', 'did not fetch exactly once']);
+ for (const {link} of topLinks) link.remove();
+ return {context, recovered, failures, observations, parserMarkup};
+})()
diff --git a/moli-renderer-v8/src/link_as.rs b/moli-renderer-v8/src/link_as.rs
index f9d36f8df..f7f0efc3a 100644
--- a/moli-renderer-v8/src/link_as.rs
+++ b/moli-renderer-v8/src/link_as.rs
@@ -28,6 +28,15 @@ pub(crate) enum LinkAsDestination {
}
impl LinkAsDestination {
+ pub(crate) fn is_preload_destination(self) -> bool {
+ // HTML's preload destinations are a subset of the enumerated `as`
+ // keywords. Missing and unknown values have no preload default.
+ matches!(
+ self,
+ Self::Fetch | Self::Font | Self::Image | Self::Script | Self::Style | Self::Track
+ )
+ }
+
pub(crate) fn reflected_value(self) -> &'static str {
match self {
Self::None => "",
@@ -60,7 +69,7 @@ impl LinkAsDestination {
}
pub(crate) fn link_as_destination(value: Option<&str>) -> LinkAsDestination {
- let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
+ let Some(value) = value else {
return LinkAsDestination::None;
};
match value.to_ascii_lowercase().as_str() {
diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rs
index f6d5f880d..67f5667ae 100644
--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs
@@ -3027,6 +3027,9 @@ document.body.setAttribute('data-error-state', [
fetchpriority="high">
<link rel="preload" as="STYLE" href="/preload.css">
<link rel="preload" as="script" href="/not-style.css">
+ <link rel="preload" as=" style " href="/padded.css">
+ <link rel="preload" as="&#9;style&#10;" href="/ascii-space.css">
+ <link rel="preload" as="&#160;style" href="/unicode-space.css">
<link rel="stylesheet" disabled href="/disabled.css">
<link rel="stylesheet" type="text/plain" href="/wrong-type.css">
<link rel="stylesheet" href="data:text/css,body{}">
diff --git a/moli-renderer-v8/src/runtime/script_preloads.rs b/moli-renderer-v8/src/runtime/script_preloads.rs
index 99bef912a..2e5584e7f 100644
--- a/moli-renderer-v8/src/runtime/script_preloads.rs
+++ b/moli-renderer-v8/src/runtime/script_preloads.rs
@@ -1431,7 +1431,7 @@ impl HtmlPreloadScannerSink {
let is_style_preload = link_rel_includes_token(&rel, "preload")
&& html_attr_value(&tag.attrs, "as")
.as_deref()
- .is_some_and(|value| value.trim().eq_ignore_ascii_case("style"));
+ .is_some_and(|value| value.eq_ignore_ascii_case("style"));
if !is_stylesheet && !is_style_preload {
return;
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
index 998181fe7..21de0ec80 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
@@ -13679,6 +13679,7 @@ async fn navigator_service_worker_intercepts_preload_link_destinations() {
"/app/worker.js",
"text/javascript; charset=utf-8",
r#"
+ const requests = [];
self.addEventListener("install", event => {
event.waitUntil(Promise.resolve());
});
@@ -13687,6 +13688,11 @@ async fn navigator_service_worker_intercepts_preload_link_destinations() {
});
self.addEventListener("fetch", event => {
const path = new URL(event.request.url).pathname;
+ if (path.endsWith("/preload-requests")) {
+ event.respondWith(new Response(requests.sort().join("|")));
+ return;
+ }
+ requests.push(path.split("/").pop() + ":" + event.request.destination);
const expected = path.endsWith("/style.css") ? "style" :
path.endsWith("/font.woff2") ? "font" :
path.endsWith("/image.png") ? "image" :
@@ -13753,15 +13759,17 @@ async fn navigator_service_worker_intercepts_preload_link_destinations() {
};
parent.appendChild(link);
});
+ // These must produce neither a fetch event nor a terminal link event.
+ preload("audio", "clip.ogg");
+ preload("video", "clip.mp4");
await Promise.all([
preload("style", "style.css"),
preload("font", "font.woff2"),
- preload("image", "image.png"),
- preload("audio", "clip.ogg"),
- preload("video", "clip.mp4")
+ preload("image", "image.png")
]);
+ const requests = await (await fetch("preload-requests")).text();
globalThis.__serviceWorkerPreloadDestinationProbe =
- seen.sort().join("|");
+ seen.sort().join("|") + ";" + requests;
})().catch((error) => {
globalThis.__serviceWorkerPreloadDestinationProbe =
"error:" + String(error && error.message);
@@ -13776,7 +13784,7 @@ async fn navigator_service_worker_intercepts_preload_link_destinations() {
&browser_context_runtime,
&loader,
"String(globalThis.__serviceWorkerPreloadDestinationProbe)",
- "audio:load|font:load|image:load|style:load|video:load",
+ "font:load|image:load|style:load;font.woff2:font|image.png:image|style.css:style",
)
.await;
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
index 4fe88bccb..fc499d015 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
@@ -8586,6 +8586,30 @@ fn html_link_as_reflects_attribute() {
);
}
+#[test]
+fn html_link_as_does_not_trim_enumerated_keywords() {
+ let mut vm = new_storage_test_vm("https://link-as.test/");
+ let result = vm
+ .eval(
+ r#"(() => {
+ for (const doc of [document, document.implementation.createHTMLDocument('')]) {
+ const link = doc.createElement('link');
+ for (const value of [' fetch', 'fetch ', '\tscript\n', '\u00a0style', 'image\u00a0']) {
+ link.as = value;
+ if (link.as !== '' || link.getAttribute('as') !== value)
+ throw new Error('invalid enumerated keyword: ' + JSON.stringify(value));
+ }
+ link.as = 'sCrIpT';
+ if (link.as !== 'script' || link.getAttribute('as') !== 'sCrIpT')
+ throw new Error('ASCII case folding must preserve the content attribute');
+ }
+ return 'pass';
+ })()"#,
+ )
+ .expect("link as keyword reflection should evaluate");
+ assert_eq!(result, "pass");
+}
+
#[test]
fn html_link_integrity_reflects_attribute_on_live_and_detached_documents() {
let mut vm = new_storage_test_vm("https://link-integrity.test/");
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index dab861f1a..e4a58dea6 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -729,6 +729,22 @@ impl DocumentRuntime {
self.invalidate_stylesheet_owner_operations(handle);
return result;
}
+ if self
+ .dom_host
+ .node(handle)
+ .and_then(Node::as_element)
+ .is_some_and(|element| {
+ element.is_html_element("link") && !link_rel_starts_resource_load(element)
+ })
+ {
+ self.settle_connected_style_load_admission(
+ host_ptr,
+ event_admission,
+ "link no longer has a supported resource destination",
+ );
+ self.invalidate_stylesheet_owner_operations(handle);
+ return result;
+ }
if let Some(admission) = event_admission {
let expects_non_blocking_identity =
self.connected_owner_uses_non_blocking_link_identity(handle);
@@ -1849,13 +1865,8 @@ fn connected_style_owner_kind(
return None;
}
match (element.attribute("rel"), element.attribute("href")) {
- (Some(rel), Some(href))
- if !href.trim().is_empty()
- && (link_rel_includes_token(rel, "stylesheet")
- || link_rel_includes_token(rel, "preload")
- || link_rel_includes_token(rel, "modulepreload")
- || link_rel_includes_token(rel, "prefetch")
- || link_rel_includes_token(rel, "compression-dictionary")) =>
+ (Some(_), Some(href))
+ if !href.trim().is_empty() && link_rel_starts_resource_load(element) =>
{
Some(ConnectedStyleOwnerKind::Link)
}
@@ -1863,6 +1874,16 @@ fn connected_style_owner_kind(
}
}
+fn link_rel_starts_resource_load(element: &crate::dom::native::Element) -> bool {
+ let rel = element.attribute("rel").unwrap_or_default();
+ link_rel_includes_token(rel, "stylesheet")
+ || link_rel_includes_token(rel, "modulepreload")
+ || link_rel_includes_token(rel, "prefetch")
+ || link_rel_includes_token(rel, "compression-dictionary")
+ || (link_rel_includes_token(rel, "preload")
+ && link_as_destination(element.attribute("as")).is_preload_destination())
+}
+
fn preload_like_link_resource_type(
element: &crate::dom::native::Element,
) -> SubresourceResourceType {
@@ -3428,6 +3449,56 @@ mod tests {
Ok(())
}
+ #[test]
+ fn preload_destinations_are_checked_before_load_event_admission() {
+ let parser = HtmlParser::SCRIPTING_ENABLED;
+ let document = parser.parse(
+ Url::parse("https://example.test/page").unwrap(),
+ concat!(
+ "<!doctype html><html><head>",
+ "<link rel=preload href='/missing.js'>",
+ "<link rel=preload as='' href='/empty.js'>",
+ "<link rel=preload as=garbage href='/unknown.js'>",
+ "<link rel=preload as=video href='/video'>",
+ "<link rel=preload as=worker href='/worker.js'>",
+ "<link rel=preload as=' style ' href='/padded.css'>",
+ "</head><body></body></html>"
+ )
+ .to_owned(),
+ );
+ let link = first_link_handle(&document);
+ let mut runtime = DocumentRuntime::new(&document);
+ assert!(runtime.prepare_initial_connected_style_loads().is_empty());
+ assert!(!runtime.has_pending_style_loads());
+ assert!(runtime.pop_ready_connected_style_load().is_none());
+
+ assert!(runtime.dom_host_mut().set_attribute(link, "as", "FETCH"));
+ let prepared = runtime.prepare_connected_style_loads(link, false);
+ assert_eq!(
+ prepared.len(),
+ 1,
+ "a rejected link can become a valid preload"
+ );
+ assert_eq!(prepared[0].owner(), link);
+ }
+
+ #[test]
+ fn preload_destination_is_rechecked_after_owner_admission() {
+ let parser = HtmlParser::SCRIPTING_ENABLED;
+ let document = parser.parse(
+ Url::parse("https://example.test/page").unwrap(),
+ "<!doctype html><link rel=preload as=fetch href='data:text/plain,preload'>".to_owned(),
+ );
+ let link = first_link_handle(&document);
+ let mut runtime = DocumentRuntime::new(&document);
+ runtime.queue_initial_connected_style_loads();
+ assert!(runtime.has_pending_style_loads());
+ assert!(runtime.dom_host_mut().set_attribute(link, "as", "video"));
+ runtime.prime_pending_connected_style_loads();
+ assert!(!runtime.has_pending_style_loads());
+ assert!(runtime.pop_ready_connected_style_load().is_none());
+ }
+
#[test]
fn modulepreload_link_readiness_uses_module_script_credentials() {
let parser = HtmlParser::SCRIPTING_ENABLED;
diff --git a/moli-stylesheet-blocking/src/discovery.rs b/moli-stylesheet-blocking/src/discovery.rs
index db622361b..d7b4373c4 100644
--- a/moli-stylesheet-blocking/src/discovery.rs
+++ b/moli-stylesheet-blocking/src/discovery.rs
@@ -368,7 +368,7 @@ pub fn stylesheet_preload_link_request(
|| !element
.as_attr
.as_deref()
- .is_some_and(|value| value.trim().eq_ignore_ascii_case("style"))
+ .is_some_and(|value| value.eq_ignore_ascii_case("style"))
{
return None;
}
@@ -467,9 +467,7 @@ pub fn connected_preload_like_link_url(
pub fn preload_like_link_loads_stylesheet(rel: &str, as_attr: Option<&str>, href: &str) -> bool {
if link_rel_includes_token(rel, "preload") {
- return as_attr
- .map(str::trim)
- .is_some_and(|value| value.eq_ignore_ascii_case("style"));
+ return as_attr.is_some_and(|value| value.eq_ignore_ascii_case("style"));
}
if !link_rel_includes_token(rel, "modulepreload") {
return false;
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs
index 663aca3f5..a6519b3b8 100644
--- a/moli/tests/fetch_cli.rs
+++ b/moli/tests/fetch_cli.rs
@@ -392,13 +392,32 @@ const OPTIONAL_RESOURCE_PATHS: [&str; 5] = [
"/optional-track.vtt",
"/optional-video.mp4",
];
-const OPTIONAL_RESOURCE_FLAG_CASES: [(&str, Option<&str>); 6] = [
- ("--image", Some("/optional-image.png")),
- ("--font", Some("/optional-font.woff2")),
- ("--audio", Some("/optional-audio.mp3")),
- ("--video", Some("/optional-video.mp4")),
- ("--media", None),
- ("--text-track", Some("/optional-track.vtt")),
+const OPTIONAL_PRELOAD_RESOURCE_PATHS: [&str; 3] = [
+ "/optional-font.woff2",
+ "/optional-image.png",
+ "/optional-track.vtt",
+];
+// Resource flags permit element requests, but cannot enable unsupported `as`
+// destinations on a preload link.
+const OPTIONAL_RESOURCE_FLAG_CASES: [(&str, Option<&str>, Option<&str>); 6] = [
+ (
+ "--image",
+ Some("/optional-image.png"),
+ Some("/optional-image.png"),
+ ),
+ (
+ "--font",
+ Some("/optional-font.woff2"),
+ Some("/optional-font.woff2"),
+ ),
+ ("--audio", None, Some("/optional-audio.mp3")),
+ ("--video", None, Some("/optional-video.mp4")),
+ ("--media", None, None),
+ (
+ "--text-track",
+ Some("/optional-track.vtt"),
+ Some("/optional-track.vtt"),
+ ),
];
const TRACK_TERMINAL_WAIT_SCRIPT: &str = "document.getElementById('track').readyState === 2";
@@ -906,8 +925,11 @@ fn fetch_cli_individual_flags_send_only_matching_real_preload_and_element_reques
let runtime = tokio::runtime::Runtime::new()?;
let server = runtime.block_on(OptionalResourceFixtureServer::spawn())?;
- for page_path in ["/preloads.html", "/elements.html"] {
- for (flag, expected_path) in OPTIONAL_RESOURCE_FLAG_CASES {
+ for (flag, preload_path, element_path) in OPTIONAL_RESOURCE_FLAG_CASES {
+ for (page_path, expected_path) in [
+ ("/preloads.html", preload_path),
+ ("/elements.html", element_path),
+ ] {
let expected = expected_path.map_or_else(Vec::new, |path| vec![path]);
assert_optional_resource_request_case(
&server,
@@ -927,25 +949,29 @@ fn fetch_cli_individual_flags_send_only_matching_real_preload_and_element_reques
fn fetch_cli_representative_flag_subsets_send_exact_real_request_unions() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let server = runtime.block_on(OptionalResourceFixtureServer::spawn())?;
- let cases: [(&str, &[&str], &[&str]); 4] = [
+ let cases: [(&str, &[&str], &[&str], &[&str]); 4] = [
(
"image+font",
&["--image", "--font"],
&["/optional-image.png", "/optional-font.woff2"],
+ &["/optional-image.png", "/optional-font.woff2"],
),
(
"audio+video",
&["--audio", "--video"],
+ &[],
&["/optional-audio.mp3", "/optional-video.mp4"],
),
(
"font+media+track",
&["--font", "--media", "--text-track"],
&["/optional-font.woff2", "/optional-track.vtt"],
+ &["/optional-font.woff2", "/optional-track.vtt"],
),
(
"image+audio+video+track",
&["--image", "--audio", "--video", "--text-track"],
+ &["/optional-image.png", "/optional-track.vtt"],
&[
"/optional-image.png",
"/optional-audio.mp3",
@@ -955,8 +981,11 @@ fn fetch_cli_representative_flag_subsets_send_exact_real_request_unions() -> Res
),
];
- for page_path in ["/preloads.html", "/elements.html"] {
- for (name, flags, expected_paths) in cases {
+ for (name, flags, preload_paths, element_paths) in cases {
+ for (page_path, expected_paths) in [
+ ("/preloads.html", preload_paths),
+ ("/elements.html", element_paths),
+ ] {
assert_optional_resource_request_case(
&server,
page_path,
@@ -976,12 +1005,15 @@ fn fetch_cli_all_resource_flag_enables_real_preload_and_element_resource_paths()
let runtime = tokio::runtime::Runtime::new()?;
let server = runtime.block_on(OptionalResourceFixtureServer::spawn())?;
- for page_path in ["/preloads.html", "/elements.html"] {
+ for (page_path, expected_paths) in [
+ ("/preloads.html", OPTIONAL_PRELOAD_RESOURCE_PATHS.as_slice()),
+ ("/elements.html", OPTIONAL_RESOURCE_PATHS.as_slice()),
+ ] {
assert_optional_resource_request_case(
&server,
page_path,
&["--resource"],
- &OPTIONAL_RESOURCE_PATHS,
+ expected_paths,
&format!("all-resource {page_path}"),
)?;
}