Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(css): preserve blocked stylesheet error lifecycle

ldm02323fedeb120
diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
index c210f8fff..c2168c36f 100644
--- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs
+++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
@@ -1824,9 +1824,6 @@ pub(super) fn finish_runtime_mutation_effects(
);
}
for prepared_owner_change in prepared_owner_changes {
- if runtime.author_styles_disabled() {
- continue;
- }
let owner = prepared_owner_change.owner();
if let Some(url) = prepared_owner_change.cached_linked_stylesheet_url() {
let _ = unsafe { &mut *host_ptr }
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index aba82235e..01920fd9c 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -1520,7 +1520,6 @@ impl PageVmRuntimeHooks {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ScannedStylesheetAdmission {
Admitted,
- SuppressedByPagePolicy,
DeferredToParser(ScannedStylesheetDeferral),
}
@@ -4452,9 +4451,6 @@ impl PageVm {
request_resource_type: moli_fetch::RequestResourceType,
link_preload: bool,
) -> ScannedStylesheetAdmission {
- if self.vm().document_runtime.author_styles_disabled() {
- return ScannedStylesheetAdmission::SuppressedByPagePolicy;
- }
if self.vm().fetch_subresource_interception_matches(
crate::types::SubresourceResourceType::Stylesheet,
) {
@@ -4494,9 +4490,6 @@ impl PageVm {
link_preload,
) {
Ok(_) => ScannedStylesheetAdmission::Admitted,
- Err(
- crate::document_runtime::OwnerlessStylesheetAdmissionError::AuthorStylesDisabled,
- ) => ScannedStylesheetAdmission::SuppressedByPagePolicy,
Err(
crate::document_runtime::OwnerlessStylesheetAdmissionError::ContentSecurityPolicy,
) => ScannedStylesheetAdmission::DeferredToParser(
diff --git a/moli-renderer-v8/src/runtime/script_preloads.rs b/moli-renderer-v8/src/runtime/script_preloads.rs
index af49c7ea5..d7b19e3d8 100644
--- a/moli-renderer-v8/src/runtime/script_preloads.rs
+++ b/moli-renderer-v8/src/runtime/script_preloads.rs
@@ -868,7 +868,6 @@ pub(super) fn admit_stylesheet_preloads(
let timing_started = moli_trace::cdp_nav_timing_enabled().then(std::time::Instant::now);
let discovered_count = requests.len();
let mut admitted_count = 0_usize;
- let mut page_policy_suppressed_count = 0_usize;
let mut fetch_interception_count = 0_usize;
let mut media_mismatch_count = 0_usize;
let mut content_security_policy_count = 0_usize;
@@ -881,9 +880,6 @@ pub(super) fn admit_stylesheet_preloads(
request.link_preload,
) {
ScannedStylesheetAdmission::Admitted => admitted_count += 1,
- ScannedStylesheetAdmission::SuppressedByPagePolicy => {
- page_policy_suppressed_count += 1;
- }
ScannedStylesheetAdmission::DeferredToParser(
ScannedStylesheetDeferral::FetchInterception,
) => fetch_interception_count += 1,
@@ -902,7 +898,6 @@ pub(super) fn admit_stylesheet_preloads(
target: "moli_cdp_nav_timing",
discovered_count,
admitted_count,
- page_policy_suppressed_count,
fetch_interception_count,
media_mismatch_count,
content_security_policy_count,
diff --git a/moli-renderer-v8/src/stylesheet_blocking.rs b/moli-renderer-v8/src/stylesheet_blocking.rs
index 400e5e3ae..e45ee1e7c 100644
--- a/moli-renderer-v8/src/stylesheet_blocking.rs
+++ b/moli-renderer-v8/src/stylesheet_blocking.rs
@@ -83,6 +83,13 @@ impl StylesheetFetcher for RendererStylesheetFetcher {
url: Url,
options: StylesheetFetchOptions,
) -> Pin<Box<dyn Future<Output = StylesheetFetchTerminal> + Send + 'static>> {
+ if self.loader.author_styles_disabled() {
+ return Box::pin(async move {
+ StylesheetFetchTerminal::network_error(format!(
+ "failed to fetch stylesheet `{url}`: net::ERR_BLOCKED_BY_CLIENT"
+ ))
+ });
+ }
let loader = self.loader.clone();
let resource_task_runner = self.task_runner.clone();
let service_worker_context = self.service_worker_context.clone();
diff --git a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs
index d73f8258a..883bea07c 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs
@@ -17,7 +17,6 @@ use crate::types::SubresourceResourceType;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OwnerlessStylesheetAdmissionError {
- AuthorStylesDisabled,
ContentSecurityPolicy,
}
@@ -44,9 +43,6 @@ impl DocumentRuntime {
request_resource_type: moli_fetch::RequestResourceType,
link_preload: bool,
) -> Result<StylesheetFetch, OwnerlessStylesheetAdmissionError> {
- if self.author_styles_disabled() {
- return Err(OwnerlessStylesheetAdmissionError::AuthorStylesDisabled);
- }
let (_, enforced_violation) = self
.response_style_element_request_csp_check(
&request_url,
@@ -146,9 +142,6 @@ impl DocumentRuntime {
document_url: &url::Url,
inputs: impl IntoIterator<Item = DocumentOwnedBlockingStylesheetDiscoveryInput>,
) -> Vec<DocumentOwnedBlockingStylesheetDiscoveryInput> {
- if self.author_styles_disabled() {
- return Vec::new();
- }
let inputs = inputs
.into_iter()
.filter(|input| {
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index a3959425c..f03337b4e 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -228,15 +228,9 @@ impl DocumentRuntime {
if self.initial_connected_style_loads_queued {
return Vec::new();
}
- self.initial_connected_style_loads_queued = true;
- if self.author_styles_disabled() {
- self.stylesheet_lifecycle
- .pre_initial_scan_processed_owners
- .clear();
- return Vec::new();
- }
self.late_preload_stylesheet_handles =
self.collect_late_preload_stylesheet_handles_for_initial_scan(self.document_handle());
+ self.initial_connected_style_loads_queued = true;
let prepared = self.prepare_connected_style_loads(self.document_handle(), true);
self.stylesheet_lifecycle
.pre_initial_scan_processed_owners
@@ -315,7 +309,7 @@ impl DocumentRuntime {
root: DomHandle,
skip_existing: bool,
) -> Vec<PreparedConnectedStyleLoad> {
- if self.author_styles_disabled() || !self.dom_host.is_connected(root) {
+ if !self.dom_host.is_connected(root) {
return Vec::new();
}
let load_handles = if self.dom_host.node(root).is_some_and(Node::is_document)
@@ -1437,9 +1431,6 @@ impl DocumentRuntime {
host_ptr: *mut JsContextHost,
owner: DomHandle,
) {
- if self.author_styles_disabled() {
- return;
- }
self.queue_stylesheet_source_css_projection(owner);
if let Some(stylesheet) = unsafe { &*host_ptr }.owner_live_stylesheet(owner) {
self.prime_live_stylesheet_import_loads(owner, stylesheet, false, host_ptr);
@@ -1451,9 +1442,6 @@ impl DocumentRuntime {
host_ptr: *mut JsContextHost,
owner: DomHandle,
) {
- if self.author_styles_disabled() {
- return;
- }
self.queue_stylesheet_source_css_projection(owner);
if let Some(stylesheet) = unsafe { &*host_ptr }.linked_live_stylesheet(owner) {
self.prime_live_stylesheet_import_loads(owner, stylesheet, true, host_ptr);
@@ -1475,10 +1463,6 @@ impl DocumentRuntime {
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut JsContextHost,
) {
- if self.author_styles_disabled() {
- self.pending_stylesheet_source_css_projection_owners.clear();
- return;
- }
let owners = std::mem::take(&mut self.pending_stylesheet_source_css_projection_owners);
for owner in owners {
crate::native_bridge::document::apply_stylesheet_source_css_projection(
diff --git a/moli/tests/fetch_cli/disable_css.rs b/moli/tests/fetch_cli/disable_css.rs
index f4fd3c9d1..bbd3be935 100644
--- a/moli/tests/fetch_cli/disable_css.rs
+++ b/moli/tests/fetch_cli/disable_css.rs
@@ -11,7 +11,7 @@ use parking_lot::Mutex;
use std::sync::Arc;
use tokio::{net::TcpListener, task::JoinHandle};
-const CSS_PATHS: [&str; 12] = [
+const CSS_PATHS: [&str; 15] = [
"/external.css",
"/external-import.css",
"/preload.css",
@@ -24,6 +24,9 @@ const CSS_PATHS: [&str; 12] = [
"/srcdoc.css",
"/rewrite.css",
"/rewrite-import.css",
+ "/event-static.css",
+ "/event-preload.css",
+ "/event-dynamic.css",
];
const MAIN_PAGE: &str = r#"<!doctype html>
@@ -82,6 +85,60 @@ const GRANDCHILD_PAGE: &str = r#"<!doctype html>
<div id="grandchild-target" style="display:none; color:rgb(14,15,16)">grandchild</div>
<script>document.documentElement.setAttribute('data-script-ran', 'yes')</script>"#;
+const LINK_EVENT_PAGE: &str = r#"<!doctype html>
+<script>globalThis.stylesheetEvents = [];</script>
+<link id="event-static" rel="stylesheet" href="/event-static.css"
+ onload="stylesheetEvents.push('static-load')"
+ onerror="stylesheetEvents.push('static-error')">
+<link id="event-preload" rel="preload" as="style" href="/event-preload.css"
+ onload="stylesheetEvents.push('preload-load')"
+ onerror="stylesheetEvents.push('preload-error')">
+<style id="event-inline">#event-target { display: none; color: red; }</style>
+<div id="event-target" style="display:none">event target</div>
+<script>
+ const dynamic = document.createElement('link');
+ dynamic.id = 'event-dynamic';
+ dynamic.rel = 'stylesheet';
+ dynamic.href = '/event-dynamic.css';
+ dynamic.onload = () => stylesheetEvents.push('dynamic-load');
+ dynamic.onerror = () => stylesheetEvents.push('dynamic-error');
+ document.head.appendChild(dynamic);
+</script>"#;
+
+const LINK_EVENT_READY_SCRIPT: &str = r#"(() => {
+ const events = globalThis.stylesheetEvents;
+ if (!Array.isArray(events)) return false;
+ const expected = ['static-error', 'preload-error', 'dynamic-error'];
+ if (!expected.every(event => events.includes(event))) return false;
+ if (events.some(event => event.endsWith('-load'))) return false;
+
+ const staticLink = document.getElementById('event-static');
+ const preloadLink = document.getElementById('event-preload');
+ const dynamicLink = document.getElementById('event-dynamic');
+ const inlineStyle = document.getElementById('event-inline');
+ const target = document.getElementById('event-target');
+ const failedLinksExposeSheets =
+ staticLink.sheet instanceof CSSStyleSheet &&
+ staticLink.sheet.ownerNode === staticLink &&
+ dynamicLink.sheet instanceof CSSStyleSheet &&
+ dynamicLink.sheet.ownerNode === dynamicLink;
+ const nonStylesheetPreloadHasNoSheet = preloadLink.sheet === null;
+ const inlineCssomRemainsAvailable =
+ inlineStyle.sheet instanceof CSSStyleSheet && inlineStyle.sheet.cssRules.length === 1;
+ const authorRulesRemainInactive =
+ getComputedStyle(target).display === 'block' &&
+ getComputedStyle(target).color === 'rgb(0, 0, 0)';
+ if (!failedLinksExposeSheets || !nonStylesheetPreloadHasNoSheet ||
+ !inlineCssomRemainsAvailable || !authorRulesRemainInactive) {
+ return false;
+ }
+ document.documentElement.setAttribute(
+ 'data-link-event-probe',
+ events.slice().sort().join(',')
+ );
+ return true;
+})()"#;
+
const DISABLED_READY_SCRIPT: &str = r#"(() => {
const child = document.getElementById('child')?.contentDocument;
const grandchild = child?.getElementById('grandchild')?.contentDocument;
@@ -136,6 +193,7 @@ impl DisableCssFixtureServer {
.route("/page.html", get(|| async { Html(MAIN_PAGE) }))
.route("/child.html", get(|| async { Html(CHILD_PAGE) }))
.route("/grandchild.html", get(|| async { Html(GRANDCHILD_PAGE) }))
+ .route("/link-events.html", get(|| async { Html(LINK_EVENT_PAGE) }))
.route("/baseline.html", get(baseline_page))
.route("/redirect.html", get(redirect_to_page))
.route("/document-open.html", get(document_open_page))
@@ -320,6 +378,35 @@ fn survives_http_redirect_without_losing_the_page_policy() -> Result<()> {
Ok(())
}
+#[test]
+fn blocked_stylesheet_links_dispatch_error_and_preserve_cssom() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableCssFixtureServer::spawn())?;
+ let output = run_fetch_cli_with_args(
+ &server.url("/link-events.html"),
+ &[
+ "--disable-css",
+ "--timeout",
+ "5000",
+ "--wait-script",
+ LINK_EVENT_READY_SCRIPT,
+ ],
+ )?;
+ let stdout = assert_success(
+ &output,
+ server.requests.lock().as_slice(),
+ "disabled stylesheet link events",
+ );
+
+ assert!(
+ stdout.contains("data-link-event-probe=\"dynamic-error,preload-error,static-error\""),
+ "blocked stylesheet resources must report error without reporting load: {stdout}"
+ );
+ assert!(stdout.contains("id=\"event-inline\""));
+ assert_no_css_requests(&server, "disabled stylesheet link events");
+ Ok(())
+}
+
#[test]
fn survives_document_open_replacement() -> Result<()> {
const READY_SCRIPT: &str = r#"(() => {