Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(renderer): block javascript URLs when scripting is disabled

ldm0c2d50f88852a
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs
index a42816f04..e93d82065 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs
@@ -447,10 +447,20 @@ impl JsContextHost {
dispatch_load_on_no_string_completion: bool,
navigation_load: crate::frame_owner_model::FrameDocumentNavigationLoadBinding,
) {
+ if !self.child_browsing_context_scripting_enabled(handle) {
+ let cancelled = self
+ .cancel_child_javascript_url_navigation_without_execution(handle, navigation_load);
+ tracing::debug!(
+ ?handle,
+ %url,
+ cancelled,
+ "blocked child javascript URL because scripting is disabled"
+ );
+ return;
+ }
let Some(snapshot) = self.frame_owner_store.current_child_owner_snapshot(handle) else {
- self.clear_child_browsing_context_pending_navigation(handle);
- let _ =
- self.finish_child_frame_navigation_without_load_dispatch(handle, navigation_load);
+ let _ = self
+ .cancel_child_javascript_url_navigation_without_execution(handle, navigation_load);
return;
};
let task_owner = FrameDocumentTaskOwner::new(
@@ -475,9 +485,8 @@ impl JsContextHost {
)
.is_none()
{
- let _ =
- self.finish_child_frame_navigation_without_load_dispatch(handle, navigation_load);
- let _ = self.clear_child_browsing_context_pending_navigation(handle);
+ let _ = self
+ .cancel_child_javascript_url_navigation_without_execution(handle, navigation_load);
return;
}
tracing::debug!(
@@ -488,6 +497,28 @@ impl JsContextHost {
);
}
+ fn cancel_child_javascript_url_navigation_without_execution(
+ &mut self,
+ handle: DomHandle,
+ navigation_load: crate::frame_owner_model::FrameDocumentNavigationLoadBinding,
+ ) -> bool {
+ if self.current_child_navigation_load(handle) != Some(navigation_load) {
+ return false;
+ }
+ let Some(entry) = self.child_browsing_contexts.get_mut(&handle) else {
+ return false;
+ };
+ entry.clear_pending_navigation();
+ entry.clear_pending_top_level_history_length_increment();
+ entry.restore_navigation_entry_seed_from_committed();
+ self.clear_pending_form_submission_child_target(handle);
+ self.reject_replaced_service_worker_child_client_navigation(
+ handle,
+ "Cannot navigate to URL.".to_owned(),
+ );
+ self.finish_child_frame_navigation_without_load_dispatch(handle, navigation_load)
+ }
+
pub(crate) fn drop_child_javascript_url_document_script(
&mut self,
work: &PendingChildJavascriptUrlDocumentScript,
@@ -495,14 +526,10 @@ impl JsContextHost {
if !self.frame_document_task_owner_is_current(work.child_handle, work.owner) {
return false;
}
- if !self.finish_child_frame_navigation_without_load_dispatch(
+ self.cancel_child_javascript_url_navigation_without_execution(
work.child_handle,
work.navigation_load,
- ) {
- return false;
- }
- let _ = self.clear_child_browsing_context_pending_navigation(work.child_handle);
- true
+ )
}
pub(crate) fn frame_document_task_owner_is_current(
@@ -526,6 +553,7 @@ impl JsContextHost {
) -> Option<FrameDocumentJavascriptUrlScriptExecutionAction> {
if !self.frame_document_task_owner_is_current(work.child_handle, work.owner)
|| self.current_child_navigation_load(work.child_handle) != Some(work.navigation_load)
+ || !self.child_browsing_context_scripting_enabled(work.child_handle)
{
return None;
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs
index f0fc5ffd5..8dc214457 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs
@@ -307,14 +307,21 @@ impl JsContextHost {
}
pub(in crate::native_bridge::context_host::child_frame_snapshots) fn detached_child_document_scripting_enabled(
- document: &crate::dom::native::NativeDom,
- owner: DomHandle,
+ snapshot_document: &crate::dom::native::NativeDom,
+ synthetic_owner: DomHandle,
parent_scripting_enabled: bool,
snapshot: &ChildBrowsingContextSnapshot,
) -> bool {
+ // Live child Documents do not reach this helper: their snapshot path uses the
+ // sandbox policy captured in `ChildBrowsingContextEntry` at commit time. This
+ // owner belongs to immutable navigation markup that was reparsed only to
+ // discover a synthetic nested frame, so its sandbox attribute is the policy
+ // input for that synthetic Document rather than a mutable live owner attribute.
parent_scripting_enabled
&& super::super::child_frames::document_sandbox_policy_from_attribute(
- document.get_attribute(owner, "sandbox").as_deref(),
+ snapshot_document
+ .get_attribute(synthetic_owner, "sandbox")
+ .as_deref(),
)
.allows_scripts
&& snapshot.policy_container.sandbox.allows_scripts
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 14cda9969..2c8ccc2d0 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
@@ -9322,6 +9322,55 @@ async fn iframe_javascript_url_non_string_completion_does_not_replace_child_docu
assert_eq!(result, "true|text/html||false|1");
}
+#[tokio::test]
+async fn queued_iframe_javascript_url_does_not_execute_after_scripting_is_disabled() {
+ let mut vm = new_storage_test_vm("https://iframe-javascript-url-disabled.test/");
+
+ vm.eval(
+ r#"
+(() => {
+ const frame = document.createElement('iframe');
+ frame.id = 'disabled-javascript-url-frame';
+ frame.src = "javascript:document.documentElement.setAttribute('data-javascript-url-ran', 'yes')";
+ (document.body || document.documentElement || document).appendChild(frame);
+})()
+"#,
+ )
+ .expect("disabled iframe javascript URL setup should evaluate as automation");
+ let child_handle = vm
+ .document_runtime
+ .dom_host()
+ .element_handle_by_id("disabled-javascript-url-frame")
+ .expect("disabled javascript URL iframe owner");
+
+ assert!(
+ vm.run_child_frame_task_source_once_for_test(ChildFrameSemanticTurnKind::NavigationCommit)
+ .await,
+ "NavigationCommit must publish the javascript URL work before scripting is disabled"
+ );
+ vm.set_script_execution_disabled(true);
+ expect_child_frame_task_source_after_realm_prerequisite(
+ &mut vm,
+ ChildFrameSemanticTurnKind::DocumentScriptReady,
+ "the already-queued javascript URL work must be consumed as disabled",
+ )
+ .await;
+ assert_eq!(
+ vm.eval(
+ "String(document.getElementById('disabled-javascript-url-frame').contentDocument.documentElement.getAttribute('data-javascript-url-ran'))"
+ )
+ .expect("disabled child document should remain observable to automation"),
+ "null"
+ );
+ assert!(
+ vm._context_host
+ .borrow()
+ .child_browsing_context_pending_live_navigation_for_test(child_handle)
+ .is_none(),
+ "disabled javascript URL work must settle its exact pending navigation"
+ );
+}
+
#[tokio::test]
async fn iframe_javascript_url_exception_does_not_replace_child_document_or_load() {
let mut vm = new_storage_test_vm("https://iframe-javascript-url-exception.test/");
@@ -12207,6 +12256,9 @@ async fn detached_frame_tree_snapshot_reuses_each_child_document_scripting_polic
"enabled srcdoc commit",
)
.await;
+ enabled_vm
+ .eval("document.getElementById('enabled').setAttribute('sandbox', 'allow-same-origin')")
+ .expect("tightening the owner sandbox after commit should evaluate");
let enabled_handle = enabled_vm
.document_runtime
@@ -12253,6 +12305,9 @@ async fn detached_frame_tree_snapshot_reuses_each_child_document_scripting_polic
"sandboxed srcdoc commit",
)
.await;
+ sandboxed_vm
+ .eval("document.getElementById('sandboxed').removeAttribute('sandbox')")
+ .expect("loosening the owner sandbox after commit should evaluate");
let sandboxed_handle = sandboxed_vm
.document_runtime
diff --git a/moli/tests/fetch_cli/disable_js.rs b/moli/tests/fetch_cli/disable_js.rs
index 80cd8f933..b948fe22e 100644
--- a/moli/tests/fetch_cli/disable_js.rs
+++ b/moli/tests/fetch_cli/disable_js.rs
@@ -154,6 +154,12 @@ const GRANDCHILD_PAGE: &str = r#"<!doctype html>
<body><noscript><main id="grandchild-fallback">grandchild fallback</main></noscript></body>
</html>"#;
+const JAVASCRIPT_URL_PAGE: &str = r#"<!doctype html>
+<iframe
+ id="javascript-url-child"
+ src="javascript:document.documentElement.setAttribute('data-javascript-url-ran', 'yes')"
+></iframe>"#;
+
struct DisableJsFixtureServer {
base_url: String,
requests: Arc<Mutex<Vec<String>>>,
@@ -169,6 +175,10 @@ impl DisableJsFixtureServer {
.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(
+ "/javascript-url.html",
+ get(|| async { Html(JAVASCRIPT_URL_PAGE) }),
+ )
.route("/redirect.html", get(redirect_to_page))
.route("/meta-refresh.html", get(meta_refresh_page))
.route("/document-write.html", get(document_write_page))
@@ -454,6 +464,80 @@ fn blocks_dynamic_scripts_and_event_handlers() -> Result<()> {
Ok(())
}
+#[test]
+fn blocks_child_javascript_url_execution() -> Result<()> {
+ const READY_SCRIPT: &str = r#"(() => {
+ const child = document.getElementById('javascript-url-child')?.contentDocument;
+ if (!child?.documentElement) {
+ return false;
+ }
+ if (!globalThis.__disableJsJavascriptUrlProbeStarted) {
+ globalThis.__disableJsJavascriptUrlProbeStarted = Date.now();
+ return false;
+ }
+ if (Date.now() - globalThis.__disableJsJavascriptUrlProbeStarted < 150) {
+ return false;
+ }
+ document.documentElement.setAttribute('data-javascript-url-disable-js-probe', 'ready');
+ return true;
+ })()"#;
+
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled_until(&server, "/javascript-url.html", READY_SCRIPT, &[])?;
+
+ assert!(
+ output.status.success(),
+ "script-disabled javascript URL fixture failed: stdout={}\nstderr={}",
+ clean_output(&output.stdout),
+ clean_output(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("data-javascript-url-disable-js-probe=\"ready\""),
+ "automation probe did not observe the child long enough: {stdout}"
+ );
+ assert!(
+ !stdout.contains("data-javascript-url-ran=&quot;yes&quot;"),
+ "a child javascript: URL executed despite --disable-js: {stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn child_javascript_url_fixture_executes_by_default() -> Result<()> {
+ const READY_SCRIPT: &str = r#"(() => {
+ const child = document.getElementById('javascript-url-child')?.contentDocument;
+ return child?.documentElement?.getAttribute('data-javascript-url-ran') === 'yes';
+ })()"#;
+
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = run_fetch_cli_with_args(
+ &server.url("/javascript-url.html"),
+ &[
+ "--with-frames",
+ "--timeout",
+ "5000",
+ "--wait-script",
+ READY_SCRIPT,
+ ],
+ )?;
+
+ assert!(
+ output.status.success(),
+ "default javascript URL control failed: stdout={}\nstderr={}",
+ clean_output(&output.stdout),
+ clean_output(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("data-javascript-url-ran=&quot;yes&quot;"),
+ "default control did not execute the child javascript: URL: {stdout}"
+ );
+ Ok(())
+}
+
#[test]
fn fragment_parsers_use_the_disabled_document_policy() -> Result<()> {
let ready_script = r#"(() => {