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): preserve upload-listener preflight requirements

ldm0af8613437680
diff --git a/moli-fetch/src/request.rs b/moli-fetch/src/request.rs
index 16cc65e9e..696cefc40 100644
--- a/moli-fetch/src/request.rs
+++ b/moli-fetch/src/request.rs
@@ -44,6 +44,7 @@ pub struct Request {
pub use_page_network_policy: bool,
pub follow_redirects: bool,
pub request_mode: RequestMode,
+ use_cors_preflight: bool,
pub redirect_mode: RequestRedirectMode,
pub credentials_mode: RequestCredentialsMode,
pub(crate) redirect_chain: Vec<RedirectInfo>,
@@ -442,6 +443,7 @@ impl Request {
use_page_network_policy: false,
follow_redirects: true,
request_mode: RequestMode::Navigate,
+ use_cors_preflight: false,
redirect_mode: RequestRedirectMode::Follow,
credentials_mode: RequestCredentialsMode::Include,
redirect_chain: Vec::new(),
@@ -474,6 +476,7 @@ impl Request {
use_page_network_policy: false,
follow_redirects: true,
request_mode: RequestMode::Navigate,
+ use_cors_preflight: false,
redirect_mode: RequestRedirectMode::Follow,
credentials_mode: RequestCredentialsMode::Include,
redirect_chain: Vec::new(),
@@ -539,6 +542,7 @@ impl Request {
use_page_network_policy: false,
follow_redirects: true,
request_mode: RequestMode::Cors,
+ use_cors_preflight: false,
redirect_mode: RequestRedirectMode::Follow,
credentials_mode: RequestCredentialsMode::Include,
redirect_chain: Vec::new(),
@@ -674,6 +678,16 @@ impl Request {
self.browser_request_metadata
}
+ /// Require a CORS preflight even for a safelisted method and header list.
+ pub fn with_use_cors_preflight(mut self, use_cors_preflight: bool) -> Self {
+ self.use_cors_preflight = use_cors_preflight;
+ self
+ }
+
+ pub fn use_cors_preflight(&self) -> bool {
+ self.use_cors_preflight
+ }
+
pub fn with_browser_navigation_kind(mut self, kind: BrowserNavigationRequestKind) -> Self {
self.browser_navigation_kind = kind;
self
diff --git a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
index bc781f462..7a3f0975a 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
@@ -1418,6 +1418,7 @@ impl JsContextHost {
&mut self,
execution_context: super::WindowExecutionContextBinding,
xhr: v8::Global<v8::Object>,
+ use_cors_preflight: bool,
credentials_mode: moli_fetch::RequestCredentialsMode,
network_partition_key: Option<String>,
policy_context: crate::types::SubresourcePolicyContext,
@@ -1444,7 +1445,10 @@ impl JsContextHost {
request_mode: moli_fetch::RequestMode::Cors,
network_partition_key,
policy_context,
- continuation: PendingSubresourceContinuation::Xhr(xhr),
+ continuation: PendingSubresourceContinuation::Xhr {
+ xhr,
+ use_cors_preflight,
+ },
deferred_request_started: false,
},
);
@@ -1492,6 +1496,7 @@ impl JsContextHost {
&mut self,
execution_context: super::WindowExecutionContextBinding,
xhr: v8::Global<v8::Object>,
+ use_cors_preflight: bool,
cancel_handle: Option<moli_fetch::FetchCancelHandle>,
credentials_mode: moli_fetch::RequestCredentialsMode,
network_partition_key: Option<String>,
@@ -1519,7 +1524,10 @@ impl JsContextHost {
request_mode: moli_fetch::RequestMode::Cors,
network_partition_key,
policy_context,
- continuation: PendingSubresourceContinuation::Xhr(xhr),
+ continuation: PendingSubresourceContinuation::Xhr {
+ xhr,
+ use_cors_preflight,
+ },
deferred_request_started: false,
},
);
@@ -1803,7 +1811,8 @@ impl JsContextHost {
.streaming_subresource_fetches
.values_mut()
.find(|state| state.body_source_id == body_source_id)?;
- let PendingSubresourceContinuation::Xhr(xhr) = &state.pending.continuation else {
+ let PendingSubresourceContinuation::Xhr { xhr, .. } = &state.pending.continuation
+ else {
return None;
};
let context = v8::Local::new(scope, state.pending.execution_context.context_global()?);
@@ -1954,7 +1963,8 @@ impl JsContextHost {
fn record_observable_abort_before_response(&mut self, pending: &PendingSubresourceFetchState) {
if !matches!(
&pending.continuation,
- PendingSubresourceContinuation::EventSource(_) | PendingSubresourceContinuation::Xhr(_)
+ PendingSubresourceContinuation::EventSource(_)
+ | PendingSubresourceContinuation::Xhr { .. }
) {
return;
}
@@ -1986,7 +1996,8 @@ impl JsContextHost {
) {
if !matches!(
&pending.pending.continuation,
- PendingSubresourceContinuation::EventSource(_) | PendingSubresourceContinuation::Xhr(_)
+ PendingSubresourceContinuation::EventSource(_)
+ | PendingSubresourceContinuation::Xhr { .. }
) {
return;
}
@@ -2037,7 +2048,8 @@ impl JsContextHost {
fn record_observable_stream_abort(&mut self, streaming: StreamingSubresourceFetchState) {
if !matches!(
&streaming.pending.continuation,
- PendingSubresourceContinuation::EventSource(_) | PendingSubresourceContinuation::Xhr(_)
+ PendingSubresourceContinuation::EventSource(_)
+ | PendingSubresourceContinuation::Xhr { .. }
) {
return;
}
diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs
index 523cc2cb6..201402295 100644
--- a/moli-renderer-v8/src/network_host.rs
+++ b/moli-renderer-v8/src/network_host.rs
@@ -181,6 +181,7 @@ pub(in crate::network_host) use self::url_helpers::merge_subresource_request_hea
pub(crate) use self::url_helpers::{ResolveContextUrlError, resolve_context_url};
#[cfg(test)]
pub(crate) use self::xhr::prepare_xhr_send_body;
+pub(crate) use self::xhr::xhr_has_upload_listeners;
pub(crate) use self::xhr::{
PreparedXhrSendBody, XHR_ABORTED_SLOT, XHR_ACTIVE_INTERNAL_ID_SLOT, XHR_ASYNC_SLOT,
XHR_METHOD_SLOT, XHR_OPEN_GENERATION_SLOT, XHR_READY_STATE_SLOT, XHR_SEND_FLAG_SLOT,
diff --git a/moli-renderer-v8/src/network_host/async_fetch.rs b/moli-renderer-v8/src/network_host/async_fetch.rs
index 43983ee4a..aef9a5bff 100644
--- a/moli-renderer-v8/src/network_host/async_fetch.rs
+++ b/moli-renderer-v8/src/network_host/async_fetch.rs
@@ -110,7 +110,8 @@ pub(crate) fn browser_request_needs_manual_preflight_redirects(
)
) && request.request_mode == RequestMode::Cors
&& request.cookie_context.initiator_url.is_some()
- && (!is_cors_safelisted_method(&request.method)
+ && (request.use_cors_preflight()
+ || !is_cors_safelisted_method(&request.method)
|| !moli_fetch::cors_unsafe_request_header_names(preflight_request_headers).is_empty())
}
@@ -409,6 +410,7 @@ async fn run_cors_preflight_if_needed(
&request.url,
&request.method,
preflight_request_headers,
+ request.use_cors_preflight(),
)
{
let observable_preflight_headers = preflight_headers.clone();
@@ -473,6 +475,7 @@ async fn run_cors_preflight_if_needed(
preflight_request_headers,
preflight_response.status,
&preflight_response.headers,
+ request.use_cors_preflight(),
)?;
}
Ok(())
diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs b/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs
index 05a90ee66..345d1bc93 100644
--- a/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs
+++ b/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs
@@ -249,6 +249,7 @@ pub(super) fn spawn_network_fetch(
&prepared.resolved_url,
&prepared.method,
&prepared.cors_preflight_request_headers,
+ false,
)
.is_some();
let internal_id = host.record_async_subresource_fetch(
diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs b/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs
index 30952ecf0..ce016c29f 100644
--- a/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs
+++ b/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs
@@ -45,6 +45,7 @@ pub(super) fn dispatch_service_worker_fetch(
&prepared.resolved_url,
&prepared.method,
&prepared.cors_preflight_request_headers,
+ false,
)
.is_some();
let request_body_text = request_body_text(&prepared.body);
@@ -93,6 +94,7 @@ pub(super) fn dispatch_service_worker_fetch(
referrer_policy: prepared.referrer_policy.clone(),
integrity: prepared.integrity.clone(),
keepalive: prepared.keepalive,
+ use_cors_preflight: false,
},
);
let dispatch = ServiceWorkerFetchDispatch {
diff --git a/moli-renderer-v8/src/network_host/response/cors.rs b/moli-renderer-v8/src/network_host/response/cors.rs
index 1a852ee09..05312024b 100644
--- a/moli-renderer-v8/src/network_host/response/cors.rs
+++ b/moli-renderer-v8/src/network_host/response/cors.rs
@@ -360,6 +360,7 @@ pub(crate) fn cors_preflight_request_headers(
request_url: &url::Url,
method: &str,
request_headers: &[(String, String)],
+ use_cors_preflight: bool,
) -> Option<Vec<(String, String)>> {
if !cors_tainted {
return None;
@@ -370,7 +371,7 @@ pub(crate) fn cors_preflight_request_headers(
let unsafe_header_names = moli_fetch::cors_unsafe_request_header_names(request_headers);
let method_requires_preflight = !moli_fetch::is_cors_safelisted_method(method);
- if !method_requires_preflight && unsafe_header_names.is_empty() {
+ if !use_cors_preflight && !method_requires_preflight && unsafe_header_names.is_empty() {
return None;
}
@@ -394,6 +395,7 @@ pub(crate) fn validate_cors_preflight_response(
request_headers: &[(String, String)],
response_status: u16,
response_headers: &[(String, Vec<u8>)],
+ use_cors_preflight: bool,
) -> Result<(), String> {
if !(200..300).contains(&response_status) {
return Err(format!(
@@ -404,10 +406,13 @@ pub(crate) fn validate_cors_preflight_response(
// Parse both complete lists before checking permissions, including for
// safelisted methods and requests without unsafe header names.
- let allow_methods =
+ let mut allow_methods =
parse_cors_preflight_allowlist(response_headers, "Access-Control-Allow-Methods")?;
let allow_headers =
parse_cors_preflight_allowlist(response_headers, "Access-Control-Allow-Headers")?;
+ if allow_methods.is_none() && use_cors_preflight {
+ allow_methods = Some(vec![requested_method.to_owned()]);
+ }
let wildcard_allowed = credentials_mode != RequestCredentialsMode::Include;
if !moli_fetch::is_cors_safelisted_method(requested_method) {
@@ -627,8 +632,13 @@ mod tests {
("X-Other".to_owned(), "ok".to_owned()),
];
- let preflight =
- cors_preflight_request_headers(true, &url("http://other.test/data"), "PUT", &headers);
+ let preflight = cors_preflight_request_headers(
+ true,
+ &url("http://other.test/data"),
+ "PUT",
+ &headers,
+ false,
+ );
assert_eq!(
preflight,
@@ -654,7 +664,13 @@ mod tests {
];
assert_eq!(
- cors_preflight_request_headers(true, &url("http://other.test/data"), "POST", &headers,),
+ cors_preflight_request_headers(
+ true,
+ &url("http://other.test/data"),
+ "POST",
+ &headers,
+ false
+ ),
None
);
}
@@ -716,6 +732,7 @@ mod tests {
&request_headers,
204,
&response_headers,
+ false,
),
Ok(())
);
@@ -740,6 +757,7 @@ mod tests {
&[("Content-Type".to_owned(), "custom/type".to_owned())],
200,
&response_headers,
+ false,
)
.unwrap_or_else(|error| {
panic!(
@@ -767,6 +785,7 @@ mod tests {
&[("Content-Type".to_owned(), "custom/type".to_owned())],
200,
&response_headers,
+ false,
)
.expect_err("unsafelisted PUT preflight should require Access-Control-Allow-Methods");
assert!(error.contains("no Access-Control-Allow-Methods for PUT"));
@@ -806,6 +825,7 @@ mod tests {
&request_headers,
204,
&response_headers,
+ false,
)
}
diff --git a/moli-renderer-v8/src/network_host/xhr.rs b/moli-renderer-v8/src/network_host/xhr.rs
index f87b42166..14d5b0772 100644
--- a/moli-renderer-v8/src/network_host/xhr.rs
+++ b/moli-renderer-v8/src/network_host/xhr.rs
@@ -60,6 +60,7 @@ pub(crate) use self::delivery::{
reset_xhr_response_for_request_error, throw_synchronous_xhr_failure,
};
pub(crate) use self::events::xhr_dispatch_progress_event;
+pub(crate) use self::instance_state::xhr_has_upload_listeners;
pub(crate) use self::instance_state::{
XHR_METHOD_SLOT, XHR_OPEN_GENERATION_SLOT, XHR_READY_STATE_SLOT, XHR_REQUEST_HEADERS_SLOT,
XHR_RESPONSE_URL_SLOT, XHR_RESPONSE_XML_SLOT, XHR_STATUS_SLOT, XHR_STATUS_TEXT_SLOT,
diff --git a/moli-renderer-v8/src/network_host/xhr/instance_state.rs b/moli-renderer-v8/src/network_host/xhr/instance_state.rs
index 02f988957..72c42847f 100644
--- a/moli-renderer-v8/src/network_host/xhr/instance_state.rs
+++ b/moli-renderer-v8/src/network_host/xhr/instance_state.rs
@@ -389,6 +389,19 @@ pub(crate) fn set_xhr_state_value(
set_private_value(scope, state, key, value);
}
+pub(crate) fn xhr_has_upload_listeners(
+ scope: &mut v8::PinScope<'_, '_>,
+ xhr: v8::Local<'_, v8::Object>,
+) -> bool {
+ xhr_upload_object(scope, xhr).is_some_and(|upload| {
+ crate::context_bootstrap::simple_object_has_event_listeners(
+ scope,
+ upload,
+ super::XHR_SIMPLE_EVENT_TARGET_LISTENERS_SLOT,
+ )
+ })
+}
+
pub(crate) fn xhr_upload_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
xhr: v8::Local<'_, v8::Object>,
diff --git a/moli-renderer-v8/src/network_host/xhr/send.rs b/moli-renderer-v8/src/network_host/xhr/send.rs
index 174bf75e8..969abdc65 100644
--- a/moli-renderer-v8/src/network_host/xhr/send.rs
+++ b/moli-renderer-v8/src/network_host/xhr/send.rs
@@ -325,6 +325,7 @@ fn send_synchronous_network_xhr(
.with_initiator_url(&prepared.document_url)
.with_request_origin(prepared.request_origin.clone())
.with_credentials_mode(prepared.credentials_mode)
+ .with_use_cors_preflight(prepared.use_cors_preflight)
.with_network_partition_key(prepared.network_partition_key.clone())
.with_browser_request_metadata(BrowserRequestMetadata::Xhr);
diff --git a/moli-renderer-v8/src/network_host/xhr/send/paths.rs b/moli-renderer-v8/src/network_host/xhr/send/paths.rs
index 68de82b65..70f156def 100644
--- a/moli-renderer-v8/src/network_host/xhr/send/paths.rs
+++ b/moli-renderer-v8/src/network_host/xhr/send/paths.rs
@@ -26,6 +26,7 @@ pub(super) fn record_intercepted_xhr(
host.record_pending_subresource_xhr(
prepared.execution_context,
v8::Global::new(scope, xhr),
+ prepared.use_cors_preflight,
prepared.credentials_mode,
prepared.network_partition_key,
prepared.policy_context,
@@ -82,6 +83,7 @@ pub(super) fn dispatch_service_worker_xhr(
let internal_id = host.record_async_subresource_xhr(
prepared.execution_context.duplicate(scope),
v8::Global::new(scope, xhr),
+ prepared.use_cors_preflight,
Some(cancel_handle.clone()),
prepared.credentials_mode,
prepared.network_partition_key.clone(),
@@ -112,7 +114,10 @@ pub(super) fn dispatch_service_worker_xhr(
prepared.credentials_mode,
RequestRedirectMode::Follow,
None,
- ServiceWorkerFetchRequestMetadata::default(),
+ ServiceWorkerFetchRequestMetadata {
+ use_cors_preflight: prepared.use_cors_preflight,
+ ..ServiceWorkerFetchRequestMetadata::default()
+ },
);
let dispatch = ServiceWorkerFetchDispatch {
internal_id,
@@ -309,6 +314,7 @@ pub(super) fn spawn_network_xhr_fetch(
.with_credentials_mode(prepared.credentials_mode)
.with_network_partition_key(prepared.network_partition_key.clone())
.with_browser_request_metadata(BrowserRequestMetadata::Xhr)
+ .with_use_cors_preflight(prepared.use_cors_preflight)
.with_subframe_context(prepared.frame_id.is_some());
let request_cookie_report = observe_subresource_request_cookie_report(
@@ -330,6 +336,7 @@ pub(super) fn spawn_network_xhr_fetch(
let internal_id = host.record_async_subresource_xhr(
prepared.execution_context,
v8::Global::new(scope, xhr),
+ prepared.use_cors_preflight,
Some(cancel_handle.clone()),
prepared.credentials_mode,
prepared.network_partition_key.clone(),
diff --git a/moli-renderer-v8/src/network_host/xhr/send/request.rs b/moli-renderer-v8/src/network_host/xhr/send/request.rs
index 49f987c74..58d7c02e7 100644
--- a/moli-renderer-v8/src/network_host/xhr/send/request.rs
+++ b/moli-renderer-v8/src/network_host/xhr/send/request.rs
@@ -27,6 +27,7 @@ pub(super) struct PreparedXhrSendRequest {
pub(super) cors_preflight_request_headers: Vec<(String, String)>,
pub(super) send_body: Option<Vec<u8>>,
pub(super) credentials_mode: moli_fetch::RequestCredentialsMode,
+ pub(super) use_cors_preflight: bool,
}
pub(super) enum XhrSendPrepareError {
@@ -105,6 +106,7 @@ pub(super) fn prepare_xhr_send_request<'s>(
cors_preflight_request_headers,
send_body: prepared_body.body,
credentials_mode,
+ use_cors_preflight: super::xhr_has_upload_listeners(scope, xhr),
})
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr.rs b/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr.rs
index 695fc600c..89b8709e8 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr.rs
@@ -213,7 +213,9 @@ fn spawn_blocking_redirect_loop_http_server(
) -> (String, std::thread::JoinHandle<()>) {
use std::io::Write;
- const REDIRECT_LOOP_REQUESTS: usize = 11;
+ // Upload listeners keep synchronous XHR on the CORS redirect path, which
+ // follows at most 20 redirects before rejecting the next redirect response.
+ const REDIRECT_LOOP_REQUESTS: usize = 21;
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.expect("bind blocking redirect-loop HTTP server");
let addr = listener
@@ -222,10 +224,27 @@ fn spawn_blocking_redirect_loop_http_server(
let server = std::thread::Builder::new()
.name("sync-xhr-redirect-loop-server".to_owned())
.spawn(move || {
- for _ in 0..REDIRECT_LOOP_REQUESTS {
- let (mut stream, _) = listener
- .accept()
- .expect("accept blocking redirect-loop request");
+ listener
+ .set_nonblocking(true)
+ .expect("bound redirect-loop fixture acceptance");
+ let deadline = Instant::now() + Duration::from_secs(10);
+ for received in 0..REDIRECT_LOOP_REQUESTS {
+ let (mut stream, _) = loop {
+ match listener.accept() {
+ Ok(connection) => break connection,
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ assert!(
+ Instant::now() < deadline,
+ "redirect loop stopped after {received} of {REDIRECT_LOOP_REQUESTS} requests"
+ );
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ Err(error) => panic!("accept blocking redirect-loop request: {error}"),
+ }
+ };
+ stream
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .expect("bound redirect-loop request headers");
let request = read_blocking_http_request_head(&mut stream);
assert!(request.starts_with(&format!("GET {path} HTTP/1.1\r\n")));
let response = format!(
@@ -258,7 +277,24 @@ fn spawn_blocking_xhr_response_server(
let (mut stream, _) = listener
.accept()
.expect("accept blocking XHR response request");
- let request = read_blocking_http_request_head(&mut stream);
+ let mut request = read_blocking_http_request_head(&mut stream);
+ if request.starts_with(&format!("OPTIONS {path} HTTP/1.1\r\n")) {
+ // The failure probes observe upload events too. Authorize their
+ // preflight so each test still checks the actual GET response.
+ let lower = request.to_ascii_lowercase();
+ assert!(lower.contains("origin: http://source.test\r\n"));
+ assert!(lower.contains("access-control-request-method: get\r\n"));
+ assert!(!lower.contains("access-control-request-headers:"));
+ stream.write_all(concat!(
+ "HTTP/1.1 204 No Content\r\n",
+ "Access-Control-Allow-Origin: http://source.test\r\n",
+ "Access-Control-Allow-Credentials: true\r\n",
+ "Content-Length: 0\r\nConnection: close\r\n\r\n",
+ ).as_bytes()).expect("authorize blocking XHR preflight");
+ drop(stream);
+ (stream, _) = listener.accept().expect("accept preflighted GET request");
+ request = read_blocking_http_request_head(&mut stream);
+ }
assert!(request.starts_with(&format!("GET {path} HTTP/1.1\r\n")));
let response_headers = response_headers
.into_iter()
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch.rs
index 76667852b..c380863ce 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch.rs
@@ -740,7 +740,7 @@ fn pending_subresource_continuation_kind(
PendingSubresourceContinuation::StylesheetSubresource { .. } => "stylesheet_subresource",
PendingSubresourceContinuation::Beacon => "beacon",
PendingSubresourceContinuation::CspReport { .. } => "csp_report",
- PendingSubresourceContinuation::Xhr(_) => "xhr",
+ PendingSubresourceContinuation::Xhr { .. } => "xhr",
PendingSubresourceContinuation::WebSocket(_) => "websocket",
PendingSubresourceContinuation::WorkerFetch { .. } => "worker_fetch",
PendingSubresourceContinuation::WorkerXhr { .. } => "worker_xhr",
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs
index 554ff9600..007b0a198 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs
@@ -692,7 +692,7 @@ impl ScriptVm {
}
resolver.resolve(scope, response_obj.into());
}
- PendingSubresourceContinuation::Xhr(xhr) => {
+ PendingSubresourceContinuation::Xhr { xhr, .. } => {
crate::context_bootstrap::record_resource_performance_entry(
scope,
crate::context_bootstrap::ResourcePerformanceEntry::from_network_response(
@@ -863,7 +863,7 @@ impl ScriptVm {
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, exception);
}
- PendingSubresourceContinuation::Xhr(xhr) => {
+ PendingSubresourceContinuation::Xhr { xhr, .. } => {
let xhr = v8::Local::new(scope, &xhr);
crate::network_host::apply_xhr_failure(scope, xhr);
}
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs
index f1be593df..716f12134 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs
@@ -341,6 +341,7 @@ impl ScriptVm {
.with_initiator_url(&pending.info.document_url)
.with_request_origin(pending.request_origin.clone())
.with_request_mode(pending.request_mode)
+ .with_use_cors_preflight(pending.continuation.use_cors_preflight())
.with_credentials_mode(pending.credentials_mode)
.with_network_partition_key(pending.network_partition_key.clone())
.with_subframe_context(pending.info.frame_id.is_some());
@@ -612,6 +613,7 @@ impl ScriptVm {
.with_initiator_url(&pending_fetch.info.document_url)
.with_request_origin(pending_fetch.request_origin.clone())
.with_request_mode(pending_fetch.request_mode)
+ .with_use_cors_preflight(pending_fetch.continuation.use_cors_preflight())
.with_credentials_mode(pending_fetch.credentials_mode)
.with_auth(auth.into())
.with_subframe_context(pending_fetch.info.frame_id.is_some());
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs
index 2d2cf09e5..202415197 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs
@@ -665,7 +665,7 @@ impl ScriptVm {
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, exception);
}
- PendingSubresourceContinuation::Xhr(xhr) => {
+ PendingSubresourceContinuation::Xhr { xhr, .. } => {
let xhr = v8::Local::new(scope, xhr);
crate::network_host::apply_xhr_failure(scope, xhr);
}
@@ -816,7 +816,7 @@ impl ScriptVm {
);
}
- if matches!(&pending.continuation, PendingSubresourceContinuation::Xhr(_))
+ if matches!(&pending.continuation, PendingSubresourceContinuation::Xhr { .. })
&& let Some(handle) = pending.info.network_request_handle
{
self._context_host
@@ -842,7 +842,7 @@ impl ScriptVm {
);
}
- if let PendingSubresourceContinuation::Xhr(xhr) = &pending.continuation {
+ if let PendingSubresourceContinuation::Xhr { xhr, .. } = &pending.continuation {
let xhr = v8::Local::new(scope, xhr);
let pending_owner = pending.execution_context.dispatch_scope();
let disk_pool = pending.load.request_client().disk_pool();
@@ -994,7 +994,7 @@ impl ScriptVm {
}
PendingSubresourceContinuation::Beacon
| PendingSubresourceContinuation::CspReport { .. }
- | PendingSubresourceContinuation::Xhr(_)
+ | PendingSubresourceContinuation::Xhr { .. }
| PendingSubresourceContinuation::WebSocket(_)
| PendingSubresourceContinuation::WorkerFetch { .. }
| PendingSubresourceContinuation::WorkerXhr { .. }
@@ -1576,7 +1576,7 @@ impl ScriptVm {
);
let xhr_delivery_body = if matches!(
&streaming.pending.continuation,
- PendingSubresourceContinuation::Xhr(_)
+ PendingSubresourceContinuation::Xhr { .. }
) {
let materialize_started =
moli_trace::cdp_runtime_trace_enabled().then(Instant::now);
@@ -1620,7 +1620,7 @@ impl ScriptVm {
context_host
.borrow_mut()
.record_subresource_network(network_record);
- if let PendingSubresourceContinuation::Xhr(xhr) =
+ if let PendingSubresourceContinuation::Xhr { xhr, .. } =
streaming.pending.continuation
{
let xhr = v8::Local::new(scope, &xhr);
@@ -1663,7 +1663,7 @@ impl ScriptVm {
let request_handle = streaming.pending.info.network_request_handle;
if matches!(
&streaming.pending.continuation,
- PendingSubresourceContinuation::Xhr(_)
+ PendingSubresourceContinuation::Xhr { .. }
) && let Some(handle) = request_handle
{
context_host.borrow_mut().record_subresource_body_finished(
@@ -1718,7 +1718,7 @@ impl ScriptVm {
trace_fields,
record_started,
);
- if let PendingSubresourceContinuation::Xhr(xhr) =
+ if let PendingSubresourceContinuation::Xhr { xhr, .. } =
streaming.pending.continuation
&& let Some(response_body) = xhr_delivery_body
{
@@ -1778,7 +1778,7 @@ impl ScriptVm {
let partial_body = streaming.body_writer.finish();
if !matches!(
&streaming.pending.continuation,
- PendingSubresourceContinuation::Xhr(_)
+ PendingSubresourceContinuation::Xhr { .. }
) {
context_host
.borrow_mut()
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cors_preflight.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cors_preflight.rs
index cc4a18905..47ce18c65 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cors_preflight.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cors_preflight.rs
@@ -7,6 +7,7 @@ struct PreflightCase {
headers: &'static [(&'static str, &'static str)],
permissions: &'static [(&'static str, &'static str)],
credentials: bool,
+ upload_listener: bool,
allowed: bool,
}
@@ -17,6 +18,7 @@ fn permission_cases() -> Vec<PreflightCase> {
headers: &[("X-Test", "1")],
permissions: &[],
credentials: false,
+ upload_listener: false,
allowed: true,
};
vec![
@@ -176,12 +178,52 @@ fn permission_cases() -> Vec<PreflightCase> {
allowed: false,
..DEFAULT
},
+ PreflightCase {
+ label: "upload-flag-with-missing-method-list",
+ headers: &[],
+ upload_listener: true,
+ ..DEFAULT
+ },
+ PreflightCase {
+ label: "upload-flag-with-empty-method-list",
+ headers: &[],
+ permissions: &[("Access-Control-Allow-Methods", "")],
+ upload_listener: true,
+ allowed: false,
+ ..DEFAULT
+ },
+ PreflightCase {
+ label: "credentialed-upload-with-missing-method-list",
+ headers: &[],
+ upload_listener: true,
+ credentials: true,
+ ..DEFAULT
+ },
+ PreflightCase {
+ label: "upload-flag-still-requires-header-permission",
+ upload_listener: true,
+ allowed: false,
+ ..DEFAULT
+ },
+ PreflightCase {
+ label: "upload-flag-with-different-method-list",
+ headers: &[],
+ permissions: &[("Access-Control-Allow-Methods", "GET")],
+ upload_listener: true,
+ allowed: false,
+ ..DEFAULT
+ },
]
}
async fn check_preflight_permissions(worker: bool, apis: &[&str]) {
- for api in apis {
- let cases = std::sync::Arc::new(permission_cases());
+ for &api in apis {
+ let cases = std::sync::Arc::new(
+ permission_cases()
+ .into_iter()
+ .filter(|case| api != "fetch" || !case.upload_listener)
+ .collect::<Vec<_>>(),
+ );
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/", listener.local_addr().unwrap());
let server_cases = cases.clone();
@@ -248,7 +290,7 @@ async fn check_preflight_permissions(worker: bool, apis: &[&str]) {
.map(|case| {
serde_json::json!({
"label": case.label, "method": case.method, "headers": case.headers,
- "credentials": case.credentials,
+ "credentials": case.credentials, "upload": case.upload_listener,
})
})
.collect::<Vec<_>>();
@@ -271,6 +313,7 @@ async fn check_preflight_permissions(worker: bool, apis: &[&str]) {
xhr.open(item.method, url, api !== 'sync-xhr');
xhr.withCredentials = item.credentials;
for (const [name, value] of item.headers) xhr.setRequestHeader(name, value);
+ if (item.upload) xhr.upload.onprogress = () => {{}};
try {{
xhr.send('payload');
if (api !== 'sync-xhr') await done;
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs
index 9ff7293a4..42fb03b40 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs
@@ -15,6 +15,7 @@ mod response_headers;
mod send_body;
mod shadow_dom;
mod style_invalidation;
+mod upload_preflight;
mod xhr;
mod response_type;
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/upload_preflight.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/upload_preflight.rs
new file mode 100644
index 000000000..a0c0a9040
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/upload_preflight.rs
@@ -0,0 +1,194 @@
+use super::*;
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+#[tokio::test(flavor = "multi_thread")]
+async fn xhr_upload_listener_preflight_reaches_transport_in_page_realms() {
+ for asynchronous in [false, true] {
+ for mode in [
+ "none",
+ "removed",
+ "late",
+ "clear",
+ "custom",
+ "get",
+ "same",
+ "redirect",
+ "deny",
+ "credentials",
+ "credentials-allow",
+ "intercept",
+ ] {
+ if mode == "intercept" && !asynchronous {
+ continue;
+ }
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let same_origin = matches!(mode, "same" | "redirect");
+ let document_url = if same_origin {
+ format!("http://{addr}/page")
+ } else {
+ "http://origin.test/page".to_owned()
+ };
+ let path = if mode == "redirect" {
+ "/redirect"
+ } else {
+ "/actual"
+ };
+ let url = format!("http://{addr}{path}");
+ let target_url = format!("http://localhost:{}/actual", addr.port());
+ let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel::<()>();
+ let server = tokio::spawn(async move {
+ let mut observed = Vec::new();
+ loop {
+ let mut socket = tokio::select! {
+ accepted = listener.accept() => accepted.unwrap().0,
+ _ = &mut stop_rx => break,
+ };
+ let mut head = Vec::new();
+ let mut byte = [0; 1];
+ while !head.ends_with(b"\r\n\r\n") {
+ assert_eq!(socket.read(&mut byte).await.unwrap(), 1);
+ head.push(byte[0]);
+ }
+ let head = String::from_utf8(head).unwrap();
+ let length = head
+ .lines()
+ .find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length")
+ .then(|| value.trim().parse::<usize>().unwrap())
+ })
+ .unwrap_or(0);
+ let mut body = vec![0; length];
+ socket.read_exact(&mut body).await.unwrap();
+ observed.push(head.clone());
+ let response = if head.starts_with("POST /redirect ") {
+ format!(
+ "HTTP/1.1 307 Temporary Redirect\r\nLocation: {target_url}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ )
+ } else if head.starts_with("OPTIONS ") && mode == "deny" {
+ "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ .to_owned()
+ } else if mode == "credentials-allow" {
+ "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: http://origin.test\r\nAccess-Control-Allow-Credentials: true\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_owned()
+ } else {
+ // Deliberately omit Allow-Methods: safelisted methods do not
+ // need to appear there, even when upload listeners force OPTIONS.
+ "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_owned()
+ };
+ socket.write_all(response.as_bytes()).await.unwrap();
+ }
+ observed
+ });
+ let mut config = moli_fetch::FetchConfig::default();
+ config.set_http_no_proxy(Some("*".to_owned()));
+ let loader = ResourceRequestClient::new(&config).unwrap();
+ let (mut vm, mut completions) =
+ new_storage_test_vm_with_loader_and_resource_completion_queue(
+ &document_url,
+ &loader,
+ );
+ if mode == "intercept" {
+ vm.set_fetch_subresource_interception(
+ true,
+ Some(crate::types::SubresourceResourceType::Xhr),
+ );
+ }
+ vm.eval(&format!(
+ r#"
+ globalThis.result = null;
+ const xhr = new XMLHttpRequest();
+ const mode = {mode:?};
+ const listener = () => {{}};
+ if (mode !== "none" && mode !== "late") {{
+ xhr.upload.addEventListener("custom", listener);
+ }}
+ if (mode === "removed") xhr.upload.removeEventListener("custom", listener);
+ xhr.onloadstart = () => {{
+ if (mode === "late") xhr.upload.onprogress = listener;
+ if (mode === "clear") xhr.upload.removeEventListener("custom", listener);
+ }};
+ xhr.onloadend = () => {{ result = xhr.status; }};
+ xhr.open(mode === "get" ? "GET" : "POST", {url:?}, {asynchronous});
+ xhr.withCredentials = mode.startsWith("credentials");
+ try {{
+ xhr.send("payload");
+ if (!{asynchronous}) result = xhr.status;
+ }} catch (error) {{ result = error.name; }}
+ "#
+ ))
+ .unwrap();
+ if mode == "intercept" {
+ let pending = vm.take_pending_subresource_fetch_infos();
+ assert_eq!(pending.len(), 1);
+ vm.eval("xhr.upload.removeEventListener('custom', listener)")
+ .unwrap();
+ vm.continue_pending_subresource_fetch(
+ pending[0].internal_id,
+ None,
+ None,
+ None,
+ None,
+ false,
+ false,
+ )
+ .unwrap();
+ }
+ if asynchronous {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while vm.eval("result === null").unwrap() == "true" {
+ assert!(completions.wait_for_arrival_without_timeout().await);
+ while let Some(event) = completions.pop_next_async_subresource_event() {
+ let activity = vm
+ .complete_async_subresource_fetch_event_body(event)
+ .unwrap();
+ vm.finish_async_subresource_body_checkpoint_for_test(activity)
+ .unwrap();
+ }
+ }
+ })
+ .await
+ .expect("XHR should finish");
+ }
+ let rejected = matches!(mode, "deny" | "credentials");
+ let expected_result = if rejected && !asynchronous {
+ "NetworkError"
+ } else if rejected {
+ "0"
+ } else {
+ "200"
+ };
+ assert_eq!(
+ vm.eval("String(result)").unwrap(),
+ expected_result,
+ "{mode}, async={asynchronous}"
+ );
+ stop_tx.send(()).unwrap();
+ let observed = server.await.unwrap();
+ let request_lines: Vec<_> = observed
+ .iter()
+ .map(|head| head.lines().next().unwrap())
+ .collect();
+ let expected: &[&str] = match mode {
+ "none" | "removed" | "late" | "same" => &["POST /actual HTTP/1.1"],
+ "get" => &["OPTIONS /actual HTTP/1.1", "GET /actual HTTP/1.1"],
+ "redirect" => &[
+ "POST /redirect HTTP/1.1",
+ "OPTIONS /actual HTTP/1.1",
+ "POST /actual HTTP/1.1",
+ ],
+ "deny" | "credentials" => &["OPTIONS /actual HTTP/1.1"],
+ _ => &["OPTIONS /actual HTTP/1.1", "POST /actual HTTP/1.1"],
+ };
+ assert_eq!(request_lines, expected, "{mode}, async={asynchronous}");
+ for head in observed.iter().filter(|head| head.starts_with("OPTIONS ")) {
+ let lower = head.to_ascii_lowercase();
+ let method = if mode == "get" { "get" } else { "post" };
+ assert!(lower.contains(&format!("access-control-request-method: {method}\r\n")));
+ assert!(!lower.contains("access-control-request-headers:"));
+ assert!(!lower.contains("cookie:"));
+ }
+ }
+ }
+}
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 c0d406f66..c55cd9deb 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
@@ -2186,9 +2186,10 @@ async fn streaming_subresource_finish_preserves_response_head_cache_state() {
request_mode: moli_fetch::RequestMode::Cors,
network_partition_key: None,
policy_context: Default::default(),
- continuation: super::PendingSubresourceContinuation::Xhr(
- v8::Global::new(scope, xhr),
- ),
+ continuation: super::PendingSubresourceContinuation::Xhr {
+ xhr: v8::Global::new(scope, xhr),
+ use_cors_preflight: false,
+ },
load: crate::network::loads::resource_load_lease_for_test(
load_client,
None,
@@ -3379,9 +3380,10 @@ async fn streaming_xhr_materialization_failure_errors_body_source_before_close()
request_mode: moli_fetch::RequestMode::Cors,
network_partition_key: None,
policy_context: Default::default(),
- continuation: super::PendingSubresourceContinuation::Xhr(v8::Global::new(
- scope, xhr,
- )),
+ continuation: super::PendingSubresourceContinuation::Xhr {
+ xhr: v8::Global::new(scope, xhr),
+ use_cors_preflight: false,
+ },
load: crate::network::loads::resource_load_lease_for_test(
load_client,
None,
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index e940556e8..162c5fcb7 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -240,6 +240,7 @@ fn register_pending_window_xhr_for_test(
let internal_id = host.record_async_subresource_xhr(
execution_context,
v8::Global::new(scope, v8::Object::new(scope)),
+ false,
Some(cancel_handle),
moli_fetch::RequestCredentialsMode::SameOrigin,
None,
diff --git a/moli-renderer-v8/src/service_worker_runtime/events.rs b/moli-renderer-v8/src/service_worker_runtime/events.rs
index 826ceff3f..bcd6d6694 100644
--- a/moli-renderer-v8/src/service_worker_runtime/events.rs
+++ b/moli-renderer-v8/src/service_worker_runtime/events.rs
@@ -489,6 +489,7 @@ pub(crate) struct ServiceWorkerFetchRequestMetadata {
pub(crate) referrer_policy: String,
pub(crate) integrity: String,
pub(crate) keepalive: bool,
+ pub(crate) use_cors_preflight: bool,
}
impl Default for ServiceWorkerFetchRequestMetadata {
@@ -499,6 +500,7 @@ impl Default for ServiceWorkerFetchRequestMetadata {
referrer_policy: String::new(),
integrity: String::new(),
keepalive: false,
+ use_cors_preflight: false,
}
}
}
@@ -521,6 +523,7 @@ pub(crate) fn service_worker_fetch_request_metadata(
.and_then(|metadata| metadata.integrity.clone())
.unwrap_or_default(),
keepalive: false,
+ use_cors_preflight: request.use_cors_preflight(),
}
}
diff --git a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs
index e373a74c1..97098cff5 100644
--- a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs
+++ b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs
@@ -73,6 +73,7 @@ pub(super) fn service_worker_network_fallback_request_for_job(
let mut request = job
.request
.clone()
+ .with_use_cors_preflight(job.metadata.use_cors_preflight)
.with_browser_request_metadata(service_worker_fetch_browser_metadata(
job.network_context.resource_type,
))
@@ -1285,6 +1286,49 @@ mod tests {
assert_eq!(response.body_text(), "service-worker-body");
}
+ #[test]
+ fn xhr_upload_listener_preflight_survives_service_worker_network_fallback() {
+ let service = new_service_worker_runtime_service();
+ let event_id = ServiceWorkerEventId(211);
+ let completion_queue = crate::page_task_queue::RendererResourceCompletionTestHarness::new();
+ insert_active_fetch_job(
+ &service,
+ event_id,
+ ServiceWorkerVersionId(1),
+ &RendererServiceWorkerRunIdentity::fresh(),
+ 311,
+ completion_queue.sender(),
+ );
+ let mut job = service
+ .inner
+ .state
+ .lock()
+ .pending_fetch_jobs
+ .remove(&event_id)
+ .unwrap();
+ job.network_context.resource_type = crate::types::SubresourceResourceType::Xhr;
+ job.metadata.use_cors_preflight = true;
+ let request = service_worker_network_fallback_request_for_job(&job);
+ assert!(request.use_cors_preflight());
+ let request_origin = moli_url::WebOrigin::from_url(&job.network_context.document_url);
+ let request_url = url("https://other.test/upload");
+ let preflight_headers = crate::network_host::cors_preflight_request_headers(
+ !request_origin.same_origin(&moli_url::WebOrigin::from_url(&request_url)),
+ &request_url,
+ "POST",
+ &[],
+ request.use_cors_preflight(),
+ )
+ .expect("upload listener should force the fallback's simple POST through OPTIONS");
+ assert_eq!(
+ preflight_headers,
+ vec![(
+ "Access-Control-Request-Method".to_owned(),
+ "POST".to_owned()
+ )]
+ );
+ }
+
#[test]
fn streaming_fetch_events_project_to_subresource_stream_queue() {
let service = new_service_worker_runtime_service();
diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs
index c8210e668..fbb76dad1 100644
--- a/moli-renderer-v8/src/types.rs
+++ b/moli-renderer-v8/src/types.rs
@@ -89,7 +89,10 @@ pub(super) enum PendingSubresourceContinuation {
web_font: Option<crate::css_resource_urls::StylesheetWebFont>,
css_image: Option<crate::native_bridge::CssImageResourceRequestIdentity>,
},
- Xhr(v8::Global<v8::Object>),
+ Xhr {
+ xhr: v8::Global<v8::Object>,
+ use_cors_preflight: bool,
+ },
WebSocket(PendingWebSocketConnection),
WorkerFetch {
worker_id: DedicatedWorkerId,
@@ -179,7 +182,17 @@ impl PendingSubresourceContinuation {
}
pub(super) fn is_window_xhr(&self) -> bool {
- matches!(self, Self::Xhr(_))
+ matches!(self, Self::Xhr { .. })
+ }
+
+ pub(super) fn use_cors_preflight(&self) -> bool {
+ matches!(
+ self,
+ Self::Xhr {
+ use_cors_preflight: true,
+ ..
+ }
+ )
}
pub(super) fn is_window_fetch(&self) -> bool {
diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rs
index 7041b7608..35f54c626 100644
--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs
+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs
@@ -515,6 +515,7 @@ pub(in crate::worker) fn spawn_worker_xhr_network(
body: Option<Vec<u8>>,
headers: moli_fetch::RequestHeaders,
credentials_mode: RequestCredentialsMode,
+ use_cors_preflight: bool,
auth: Option<crate::protocol_types::SubresourceAuthCredentials>,
redirect_headers: Option<moli_fetch::RequestHeaders>,
redirect_chain: Vec<moli_fetch::RedirectInfo>,
@@ -536,7 +537,8 @@ pub(in crate::worker) fn spawn_worker_xhr_network(
.with_initiator_url(&document_url)
.with_credentials_mode(credentials_mode)
.with_network_partition_key(network_partition_key.clone())
- .with_browser_request_metadata(BrowserRequestMetadata::Xhr);
+ .with_browser_request_metadata(BrowserRequestMetadata::Xhr)
+ .with_use_cors_preflight(use_cors_preflight);
if let Some(referrer_policy) = referrer_policy {
request =
request.with_script_fetch_metadata(moli_fetch::ScriptFetchRequestMetadata {
@@ -977,6 +979,7 @@ pub(in crate::worker) fn continue_pending_worker_xhr(
document_url,
network_partition_key,
credentials_mode,
+ use_cors_preflight,
xhr_id,
resolved_url,
method,
@@ -1020,6 +1023,7 @@ pub(in crate::worker) fn continue_pending_worker_xhr(
pending.document_url.clone(),
network_partition_key,
pending.credentials_mode,
+ pending.use_cors_preflight,
request.xhr_id,
request.url,
request.method,
@@ -1042,6 +1046,7 @@ pub(in crate::worker) fn continue_pending_worker_xhr(
body.map(|body| body.into_bytes()),
headers,
credentials_mode,
+ use_cors_preflight,
auth,
redirect_headers,
redirect_chain,
@@ -1918,6 +1923,7 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>(
referrer_policy: init.referrer_policy.unwrap_or(inherited.referrer_policy),
integrity: init.integrity.unwrap_or(inherited.integrity),
keepalive: init.keepalive.unwrap_or(inherited.keepalive),
+ use_cors_preflight: false,
};
(
url,
@@ -1955,6 +1961,7 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>(
referrer_policy: init.referrer_policy.unwrap_or_default(),
integrity: init.integrity.unwrap_or_default(),
keepalive: init.keepalive.unwrap_or(false),
+ use_cors_preflight: false,
};
(
url,
diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rs
index 4cc542c33..ccf70b7c2 100644
--- a/moli-renderer-v8/src/worker/global_scope/mod.rs
+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs
@@ -56,6 +56,7 @@ use crate::context_bootstrap::{
simple_object_event_set_ordered_handler,
};
use crate::network::loads::{ResourceLoadDisposition, ResourceLoadKind, ResourceLoadLease};
+use crate::network_host::xhr_has_upload_listeners;
use crate::network_host::{
ABORTED_ERROR_TEXT, BLOCKED_BY_CLIENT_ERROR_TEXT, FAILED_ERROR_TEXT,
FetchResponseSecurityViolation, HeadersGuard, PreparedXhrSendBody, XHR_ABORTED_SLOT,
diff --git a/moli-renderer-v8/src/worker/global_scope/network_state.rs b/moli-renderer-v8/src/worker/global_scope/network_state.rs
index 0eab8e2c5..42455cc24 100644
--- a/moli-renderer-v8/src/worker/global_scope/network_state.rs
+++ b/moli-renderer-v8/src/worker/global_scope/network_state.rs
@@ -145,6 +145,7 @@ pub(in crate::worker) struct PendingWorkerXhr {
pub(in crate::worker) xhr: v8::Global<v8::Object>,
pub(in crate::worker) document_url: Url,
pub(in crate::worker) credentials_mode: RequestCredentialsMode,
+ pub(in crate::worker) use_cors_preflight: bool,
pub(in crate::worker) load: ResourceLoadLease,
pub(in crate::worker) request_paused: bool,
pub(in crate::worker) request_url: Url,
diff --git a/moli-renderer-v8/src/worker/global_scope/xhr.rs b/moli-renderer-v8/src/worker/global_scope/xhr.rs
index 5ad0faf54..3cba40aba 100644
--- a/moli-renderer-v8/src/worker/global_scope/xhr.rs
+++ b/moli-renderer-v8/src/worker/global_scope/xhr.rs
@@ -8,6 +8,7 @@ use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub(in crate::worker) struct PreparedWorkerXhrSendRequest {
+ pub(in crate::worker) use_cors_preflight: bool,
document_url: Url,
resolved_url: Url,
method: String,
@@ -458,6 +459,7 @@ pub(crate) fn try_worker_xhr_send_callback<'s>(
xhr: v8::Global::new(scope, xhr),
document_url: prepared.document_url.clone(),
credentials_mode: prepared.credentials_mode,
+ use_cors_preflight: prepared.use_cors_preflight,
load: load.clone(),
request_paused: intercept_request_stage,
request_url: prepared.resolved_url.clone(),
@@ -530,6 +532,7 @@ pub(crate) fn try_worker_xhr_send_callback<'s>(
prepared.send_body,
prepared.request_headers,
prepared.credentials_mode,
+ prepared.use_cors_preflight,
None,
None,
Vec::new(),
@@ -559,7 +562,8 @@ fn send_synchronous_worker_xhr(
.with_request_origin(moli_url::WebOrigin::from_url(&prepared.document_url))
.with_credentials_mode(prepared.credentials_mode)
.with_network_partition_key(state.borrow().network_partition_key.clone())
- .with_browser_request_metadata(BrowserRequestMetadata::Xhr);
+ .with_browser_request_metadata(BrowserRequestMetadata::Xhr)
+ .with_use_cors_preflight(prepared.use_cors_preflight);
if let Some(referrer_policy) = state.borrow().referrer_policy.clone() {
request =
request.with_script_fetch_metadata(moli_fetch::ScriptFetchRequestMetadata {
@@ -1181,6 +1185,7 @@ pub(in crate::worker) fn prepare_worker_xhr_send_request<'s>(
};
Ok(PreparedWorkerXhrSendRequest {
+ use_cors_preflight: xhr_has_upload_listeners(scope, xhr),
document_url,
resolved_url,
method,
diff --git a/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs b/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs
index 5f66b76cd..f5862c412 100644
--- a/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs
@@ -616,6 +616,7 @@ async fn service_worker_fetch_event_request_exposes_destination_metadata() {
referrer_policy: "origin".to_owned(),
integrity: "sha256-test".to_owned(),
keepalive: true,
+ use_cors_preflight: false,
},
};
let completion =
diff --git a/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs b/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs
index 39329ef5c..be4c26982 100644
--- a/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs
@@ -1067,6 +1067,92 @@ async fn worker_xmlhttprequest_upload_dispatches_completion_events() {
.expect("worker xhr upload server should finish");
}
+#[tokio::test]
+async fn worker_xhr_upload_listener_preflight_survives_sync_and_interception() {
+ ensure_v8();
+ for mode in ["async", "sync", "intercept", "none", "late", "clear"] {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/upload", listener.local_addr().unwrap());
+ let requires_preflight = !matches!(mode, "none" | "late");
+ let server = tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let methods: &[&str] = if requires_preflight {
+ &["OPTIONS", "POST"]
+ } else {
+ &["POST"]
+ };
+ for method in methods {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut head = Vec::new();
+ let mut byte = [0; 1];
+ while !head.ends_with(b"\r\n\r\n") {
+ assert_eq!(socket.read(&mut byte).await.unwrap(), 1);
+ head.push(byte[0]);
+ }
+ let head = String::from_utf8(head).unwrap();
+ assert!(
+ head.starts_with(&format!("{method} /upload HTTP/1.1\r\n")),
+ "{mode}: {head}"
+ );
+ if *method == "OPTIONS" {
+ let lower = head.to_ascii_lowercase();
+ assert!(lower.contains("access-control-request-method: post\r\n"));
+ assert!(!lower.contains("access-control-request-headers:"));
+ } else {
+ let mut body = [0; 7];
+ socket.read_exact(&mut body).await.unwrap();
+ assert_eq!(&body, b"payload");
+ }
+ socket.write_all(b"HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok").await.unwrap();
+ }
+ });
+ let mut config = FetchConfig::default();
+ config.set_http_no_proxy(Some("*".to_owned()));
+ let loader = ResourceRequestClient::new(&config).unwrap();
+ let mut handle = spawn_worker_with_request_client(
+ format!(
+ r#"
+ onmessage = () => {{
+ const xhr = new XMLHttpRequest();
+ const mode = {mode:?};
+ const listener = () => {{}};
+ if (mode !== "none" && mode !== "late") xhr.upload.addEventListener("custom", listener);
+ xhr.onloadstart = () => {{
+ if (mode === "late") xhr.upload.addEventListener("custom", listener);
+ if (mode === "clear") xhr.upload.removeEventListener("custom", listener);
+ }};
+ const finish = () => {{ postMessage([xhr.status, xhr.responseText]); close(); }};
+ xhr.open("POST", {url:?}, mode !== "sync");
+ if (mode !== "sync") xhr.onloadend = finish;
+ xhr.send("payload");
+ if (mode === "sync") finish();
+ }};
+ "#
+ ),
+ "http://origin.test/worker.js".to_owned(),
+ loader,
+ );
+ if mode == "intercept" {
+ handle.set_fetch_subresource_interception(true, Some(SubresourceResourceType::Xhr));
+ }
+ handle.post_message(serialize_test_string("go"));
+ if mode == "intercept" {
+ let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
+ let WorkerToParentMessage::PendingSubresourceFetch(pending) = message else {
+ panic!("expected intercepted XHR, got {message:?}");
+ };
+ handle.continue_pending_xhr(pending_worker_xhr_continue(
+ pending.fetch_id,
+ 47,
+ &pending.info,
+ false,
+ ));
+ }
+ assert_eq!(recv_post_json(&mut handle).await, "[200,\"ok\"]", "{mode}");
+ timeout(TIMEOUT, server).await.unwrap().unwrap();
+ }
+}
+
#[tokio::test]
async fn worker_xmlhttprequest_bad_port_errors_before_transport() {
ensure_v8();