Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(xhr): resolve open URLs with credentials

ldm019eacf16b3ac
diff --git a/moli-renderer-v8/src/network_host/xhr/bindings/open.rs b/moli-renderer-v8/src/network_host/xhr/bindings/open.rs
index f22fdb390..2b05c7a45 100644
--- a/moli-renderer-v8/src/network_host/xhr/bindings/open.rs
+++ b/moli-renderer-v8/src/network_host/xhr/bindings/open.rs
@@ -32,9 +32,15 @@ pub(super) fn xhr_open_callback<'s>(
return;
}
};
- // Keep username/password WebIDL conversion side effects even though request
- // auth plumbing is not modeled by the current XHR transport state yet.
- let _ = (&parsed.username, &parsed.password);
+ let Some(request_url) = xhr_open_request_url(
+ scope,
+ xhr,
+ &parsed.url,
+ parsed.username.as_deref(),
+ parsed.password.as_deref(),
+ ) else {
+ return;
+ };
let timeout = xhr_state_number_property(scope, xhr, XHR_TIMEOUT_SLOT).unwrap_or(0.0);
if timeout != 0.0 && xhr_is_synchronous_document_request(scope, parsed.async_request) {
xhr_throw_invalid_access(
@@ -65,7 +71,7 @@ pub(super) fn xhr_open_callback<'s>(
xhr_state_number_property(scope, xhr, XHR_OPEN_GENERATION_SLOT).unwrap_or(0.0);
set_xhr_state_number(scope, xhr, XHR_OPEN_GENERATION_SLOT, open_generation + 1.0);
set_xhr_state_string(scope, xhr, XHR_METHOD_SLOT, &method);
- set_xhr_state_string(scope, xhr, XHR_URL_SLOT, &parsed.url);
+ set_xhr_state_string(scope, xhr, XHR_URL_SLOT, request_url.as_str());
set_xhr_state_string(scope, xhr, XHR_REQUEST_HEADERS_SLOT, "[]");
set_xhr_state_bool(scope, xhr, XHR_ASYNC_SLOT, parsed.async_request);
set_xhr_state_number(scope, xhr, XHR_READY_STATE_SLOT, 1.0);
@@ -97,3 +103,77 @@ pub(super) fn xhr_open_callback<'s>(
xhr_fire_readystatechange(scope, xhr, 1);
}
}
+
+fn xhr_open_request_url(
+ scope: &mut v8::PinScope<'_, '_>,
+ xhr: v8::Local<'_, v8::Object>,
+ input: &str,
+ username: Option<&str>,
+ password: Option<&str>,
+) -> Option<url::Url> {
+ let base_url = if xhr_current_context_is_worker_global(scope) {
+ crate::worker::worker_current_script_url(scope)
+ } else {
+ let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
+ xhr_open_throw_invalid_state(
+ scope,
+ "Failed to execute 'open' on 'XMLHttpRequest': The object's document is not fully active.",
+ );
+ return None;
+ };
+ let host = unsafe { &*host_ptr };
+ let Some(execution_context) = xhr_execution_context_binding(scope, host, xhr) else {
+ xhr_open_throw_invalid_state(
+ scope,
+ "Failed to execute 'open' on 'XMLHttpRequest': The object's document is not fully active.",
+ );
+ return None;
+ };
+ match execution_context.dispatch_scope() {
+ crate::native_bridge::OwnerDispatchScope::Top => {
+ Some(host.document_base_url_for_handle(host.document_handle()))
+ }
+ crate::native_bridge::OwnerDispatchScope::Child(handle) => {
+ host.child_browsing_context_base_url(handle)
+ }
+ crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id) => {
+ host.lightweight_popup_request_base_url(scope, popup_id)
+ }
+ }
+ };
+ let Some(base_url) = base_url else {
+ xhr_open_throw_invalid_state(
+ scope,
+ "Failed to execute 'open' on 'XMLHttpRequest': The object's execution context is unavailable.",
+ );
+ return None;
+ };
+ let mut request_url = match resolve_context_url(&base_url, input, None) {
+ Ok(url) => url,
+ Err(_) => {
+ throw_dom_exception(
+ scope,
+ "SyntaxError",
+ 12,
+ "Failed to execute 'open' on 'XMLHttpRequest': The URL is invalid.",
+ );
+ return None;
+ }
+ };
+ if request_url.host().is_some() {
+ if let Some(username) = username {
+ let _ = request_url.set_username(username);
+ }
+ if let Some(password) = password {
+ let _ = request_url.set_password(Some(password));
+ }
+ }
+ Some(request_url)
+}
+
+fn xhr_open_throw_invalid_state(scope: &mut v8::PinScope<'_, '_>, message: &'static str) {
+ let current_context = scope.get_current_context();
+ let incumbent_context = scope.get_incumbent_context().unwrap_or(current_context);
+ let incumbent_scope = &mut v8::ContextScope::new(scope, incumbent_context);
+ xhr_throw_invalid_state(incumbent_scope, message);
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs
index 4ec1fd547..217504838 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs
@@ -3205,3 +3205,57 @@ async fn streaming_xhr_materialization_failure_errors_body_source_before_close()
vec![crate::types::PendingSubresourceContinueEvent::Completed { internal_id }]
);
}
+
+#[tokio::test(flavor = "current_thread")]
+async fn window_xhr_open_freezes_base_url_and_applies_url_credentials() {
+ let server = StaticHttpServer::spawn(1).await;
+ let base_url = server.base_url();
+ let loader = static_http_loader(std::iter::empty::<String>());
+ let mut vm = new_page_task_executor_test_vm_with_loader(
+ base_url
+ .join("page.html")
+ .expect("page fixture URL")
+ .as_str(),
+ &loader,
+ );
+ let first_base = base_url.join("first/").expect("first base URL");
+ let second_base = base_url.join("second/").expect("second base URL");
+
+ vm.eval(&format!(
+ r#"
+(() => {{
+ globalThis.__xhrOpenUrlProbe = "pending";
+ const base = document.createElement("base");
+ base.href = {};
+ document.head.append(base);
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "resource", true, "alice", "secret");
+ base.href = {};
+ xhr.onload = () => {{ globalThis.__xhrOpenUrlProbe = "done"; }};
+ xhr.onerror = () => {{ globalThis.__xhrOpenUrlProbe = "error"; }};
+ xhr.send();
+ return "started";
+}})()
+"#,
+ serde_json::to_string(first_base.as_str()).expect("serialize first base URL"),
+ serde_json::to_string(second_base.as_str()).expect("serialize second base URL"),
+ ))
+ .expect("XHR open URL probe should evaluate");
+
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "String(globalThis.__xhrOpenUrlProbe)",
+ "done",
+ "XHR open URL probe",
+ )
+ .await;
+
+ let requests = server.finish().await;
+ assert_eq!(requests.len(), 1);
+ assert_eq!(requests[0].target, "/first/resource");
+ assert_eq!(
+ requests[0].header_value("authorization"),
+ Some("Basic YWxpY2U6c2VjcmV0")
+ );
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index 36e26bb2f..21e895ec6 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2365,17 +2365,24 @@ async fn child_navigation_retires_local_window_owned_xhr() {
result: Err("stale retired XHR completion".to_owned()),
})
.expect("late completion for retired XHR should be harmless");
- vm.eval(
- r#"
- __retiredChildXhrWrapper.open(
- "GET",
- "https://xhr-execution-context.test/after-navigation"
- );
- __retiredChildXhrWrapper.send();
- "attempted"
+ let stale_open = vm
+ .eval(
+ r#"
+ (() => {
+ try {
+ __retiredChildXhrWrapper.open(
+ "GET",
+ "https://xhr-execution-context.test/after-navigation"
+ );
+ return "no-error";
+ } catch (error) {
+ return [error.name, error.code, error instanceof DOMException].join("|");
+ }
+ })()
"#,
- )
- .expect("calling send on a retained old-child XHR wrapper should fail closed");
+ )
+ .expect("calling open on a retained old-child XHR wrapper should fail closed");
+ assert_eq!(stale_open, "InvalidStateError|11|true");
assert!(
vm._context_host
.borrow()