Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(fetch): preserve inherited header lists and cover transport
ldm0de1093d9c1ab
diff --git a/moli-fetch/src/blocking/mod.rs b/moli-fetch/src/blocking/mod.rsindex 2db4cf95e..5c78f0aad 100644--- a/moli-fetch/src/blocking/mod.rs+++ b/moli-fetch/src/blocking/mod.rs@@ -698,8 +698,16 @@ pub(crate) fn configure_easy(let mut has_content_type_header = false;for (name, value) in outgoing_headers.iter() {- has_content_type_header |= name.eq_ignore_ascii_case("content-type");- let mut header_line = format!("{name}:").into_bytes();+ let is_content_type = name.eq_ignore_ascii_case("content-type");+ has_content_type_header |= is_content_type;+ let mut header_line = name.as_bytes().to_vec();+ // curl sends an empty field for `Name;`, but removes it for `Name:`.+ // Empty Content-Type remains the internal upload-default suppression marker.+ header_line.push(if value.is_empty() && !is_content_type {+ b';'+ } else {+ b':'+ });if !value.is_empty() {header_line.push(b' ');header_line.extend_from_slice(value);diff --git a/moli-renderer-v8/src/network_host/fetch_surface.rs b/moli-renderer-v8/src/network_host/fetch_surface.rsindex b49a6ebf7..f85413d75 100644--- a/moli-renderer-v8/src/network_host/fetch_surface.rs+++ b/moli-renderer-v8/src/network_host/fetch_surface.rs@@ -1,4 +1,6 @@-use super::headers::{build_headers_object, headers_entries, mark_headers_immutable};+use super::headers::{+ build_headers_object, headers_entries, mark_headers_immutable, normalized_headers_entries,+};use super::response::{ParsedResponseInit, install_response_body_methods, parse_response_init};use super::*;use crate::context_bootstrap::readable_stream_disturbed;@@ -459,7 +461,10 @@ fn response_content_type<'s>(response: v8::Local<'s, v8::Object>,) -> Option<String> {let headers = response_slot_object(scope, response, RESPONSE_HEADERS_SLOT)?;- moli_web_mime::response_header_value(&headers_entries(scope, headers), "content-type")+ moli_web_mime::response_header_value(+ &normalized_headers_entries(&headers_entries(scope, headers)),+ "content-type",+ )}fn request_slot_attribute_getter_callback<'s>(diff --git a/moli-renderer-v8/src/network_host/headers/methods/iteration.rs b/moli-renderer-v8/src/network_host/headers/methods/iteration.rsindex 15d695dfa..d9363a159 100644--- a/moli-renderer-v8/src/network_host/headers/methods/iteration.rs+++ b/moli-renderer-v8/src/network_host/headers/methods/iteration.rs@@ -1,4 +1,4 @@-use super::super::store::headers_entries;+use super::super::store::{headers_entries, normalized_headers_entries};use super::*;use crate::web_api_interfaces;use crate::{@@ -126,7 +126,7 @@ pub(in crate::network_host::headers) fn headers_for_each_callback<'s>(.this_arg.unwrap_or_else(|| v8::undefined(scope).into());let callback = parsed.callback.prepare(scope);- for (name, value) in headers_entries(scope, this) {+ for (name, value) in normalized_headers_entries(&headers_entries(scope, this)) {let Some(name) = v8_string(scope, &name) else {continue;};@@ -205,7 +205,7 @@ fn headers_iterator_next_callback<'s>(return;};let index = index_value.integer_value(scope).unwrap_or(0).max(0) as usize;- let entries = headers_entries(scope, target);+ let entries = normalized_headers_entries(&headers_entries(scope, target));if index >= entries.len() {let result = HeadersIteratorResultDeclaration::new(true, v8::undefined(scope).into()).bind(scope)diff --git a/moli-renderer-v8/src/network_host/headers/store/entries.rs b/moli-renderer-v8/src/network_host/headers/store/entries.rsindex 897e49259..2ff3dcb5f 100644--- a/moli-renderer-v8/src/network_host/headers/store/entries.rs+++ b/moli-renderer-v8/src/network_host/headers/store/entries.rs@@ -144,13 +144,13 @@ pub(in crate::network_host) fn set_headers_entries(}pub(in crate::network_host) fn headers_entries_json(entries: &[(String, String)]) -> String {- let entries = normalized_headers_entries(entries);+ // Keep the underlying header list intact. Request construction can refill+ // this list under a different guard, which must see each original entry.+ let entries = normalized_header_list(entries);serde_json::to_string(&entries).unwrap_or_else(|_| "[]".to_owned())}-pub(in crate::network_host) fn normalized_headers_entries(- entries: &[(String, String)],-) -> Vec<(String, String)> {+fn normalized_header_list(entries: &[(String, String)]) -> Vec<(String, String)> {let mut normalized = Vec::<(String, String)>::new();for (name, value) in entries {let Some(lower) = normalized_header_name(name) else {@@ -160,6 +160,18 @@ pub(in crate::network_host) fn normalized_headers_entries(if !is_valid_header_value(&value) {continue;}+ normalized.push((lower, value));+ }+ normalized+}++// JS iteration and XHR's serialized response headers use sort-and-combine;+// storage and internal Request copies must retain duplicate entries.+pub(in crate::network_host) fn normalized_headers_entries(+ entries: &[(String, String)],+) -> Vec<(String, String)> {+ let mut normalized = Vec::<(String, String)>::new();+ for (lower, value) in normalized_header_list(entries) {if lower == "set-cookie" {normalized.push((lower, value));continue;@@ -261,7 +273,32 @@ fn private_string_value<'s>(#[cfg(test)]mod tests {- use super::{HeadersGuard, header_allowed_by_guard, normalized_headers_entries};+ use super::{+ HeadersGuard, header_allowed_by_guard, headers_entries_json, normalized_headers_entries,+ };++ #[test]+ fn headers_storage_preserves_duplicate_entries_and_order() {+ let entries = [+ ("X-Test".to_owned(), " one ".to_owned()),+ ("Set-Cookie".to_owned(), "a=1".to_owned()),+ ("x-test".to_owned(), String::new()),+ ("set-cookie".to_owned(), "b=2".to_owned()),+ ("X-TEST".to_owned(), "two".to_owned()),+ ];+ let stored: Vec<(String, String)> =+ serde_json::from_str(&headers_entries_json(&entries)).unwrap();+ assert_eq!(+ stored,+ vec![+ ("x-test".to_owned(), "one".to_owned()),+ ("set-cookie".to_owned(), "a=1".to_owned()),+ ("x-test".to_owned(), String::new()),+ ("set-cookie".to_owned(), "b=2".to_owned()),+ ("x-test".to_owned(), "two".to_owned()),+ ]+ );+ }#[test]fn normalized_headers_entries_keeps_set_cookie_values_separate() {diff --git a/moli-renderer-v8/src/network_host/request/input.rs b/moli-renderer-v8/src/network_host/request/input.rsindex 950f2d7f5..bc96c5fc0 100644--- a/moli-renderer-v8/src/network_host/request/input.rs+++ b/moli-renderer-v8/src/network_host/request/input.rs@@ -206,15 +206,9 @@ fn request_input_snapshot_from_private_slots<'s>(webidl::WebIdlError::custom_message("Failed to materialize request body")})?};- let headers = webidl::property_result(- scope,- object,- "headers",- webidl::Context::member("Request", "headers"),- )?- .map(|value| headers_entries_from_init(scope, value))- .transpose()?- .unwrap_or_default();+ // Inherited headers are an internal list copy, unlike an explicit+ // RequestInit.headers value, which undergoes WebIDL iterable conversion.+ let headers = request_headers_entries(scope, object);let signal = request_slot_value(scope, object, REQUEST_SIGNAL_SLOT).map(|value| request_signal_snapshot_from_value(scope, value)).transpose()?diff --git a/moli-renderer-v8/src/network_host/response/body_methods.rs b/moli-renderer-v8/src/network_host/response/body_methods.rsindex 563267c1f..a2c7182b4 100644--- a/moli-renderer-v8/src/network_host/response/body_methods.rs+++ b/moli-renderer-v8/src/network_host/response/body_methods.rs@@ -4,6 +4,7 @@ mod text_json;use super::super::fetch_surface::{REQUEST_BODY_USED_SLOT, REQUEST_HEADERS_SLOT, RESPONSE_BODY_USED_SLOT, RESPONSE_HEADERS_SLOT,};+use super::super::headers::normalized_headers_entries;use super::*;use moli_web_mime::{is_form_urlencoded_mime, multipart_form_data_boundary, response_blob_mime_type,@@ -183,6 +184,7 @@ fn body_headers<'s>(BodyReceiver::Request => request_slot_object(scope, object, REQUEST_HEADERS_SLOT).map(|headers| headers_entries(scope, headers)),}+ .map(|headers| normalized_headers_entries(&headers))}fn is_urlencoded_content_type(content_type: &str) -> bool {diff --git a/moli-renderer-v8/src/script_vm/tests/http_fixture.rs b/moli-renderer-v8/src/script_vm/tests/http_fixture.rsindex 5a6052b09..7ca9168b8 100644--- a/moli-renderer-v8/src/script_vm/tests/http_fixture.rs+++ b/moli-renderer-v8/src/script_vm/tests/http_fixture.rs@@ -41,16 +41,37 @@ impl StaticHttpServer {}pub(super) async fn spawn_with_bodies(response_bodies: Vec<String>) -> Self {+ Self::spawn_with_responder(+ response_bodies.len(),+ "Content-Type: text/html; charset=utf-8\r\n",+ move |index, _| response_bodies[index].clone(),+ )+ .await+ }++ pub(super) async fn spawn_echo(expected_requests: usize) -> Self {+ Self::spawn_with_responder(+ expected_requests,+ "Content-Type: application/json\r\nCache-Control: no-store\r\n",+ |_, request| serde_json::json!({ "headers": request.headers }).to_string(),+ )+ .await+ }++ async fn spawn_with_responder(+ expected_requests: usize,+ response_headers: &'static str,+ response_body: impl Fn(usize, &CapturedHttpRequest) -> String + Send + 'static,+ ) -> Self {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind static HTTP test server");let address = listener.local_addr().expect("read static HTTP test server address");- let expected_requests = response_bodies.len();let task = tokio::spawn(async move {let mut requests = Vec::with_capacity(expected_requests);- for body in response_bodies {+ for index in 0..expected_requests {let (mut socket, _) = listener.accept().await@@ -118,17 +139,19 @@ impl StaticHttpServer {.iter().find(|(name, _)| name.eq_ignore_ascii_case("host")).map(|(_, value)| value.clone());- requests.push(CapturedHttpRequest {+ let captured = CapturedHttpRequest {method,host,target,headers,- });+ };+ let body = response_body(index, &captured);+ requests.push(captured);socket.write_all(format!(- "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ "HTTP/1.1 200 OK\r\n{response_headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()).as_bytes(),diff --git a/moli-renderer-v8/src/script_vm/tests/no_cors_header_fill.rs b/moli-renderer-v8/src/script_vm/tests/no_cors_header_fill.rsindex e734925f1..29ce0a7b7 100644--- a/moli-renderer-v8/src/script_vm/tests/no_cors_header_fill.rs+++ b/moli-renderer-v8/src/script_vm/tests/no_cors_header_fill.rs@@ -4,13 +4,15 @@ use super::*;async fn no_cors_header_fill_uses_append_guards_in_window_and_worker() {let fixture = include_str!("../../../tests/fixtures/no-cors-header-fill.js");for worker in [false, true] {+ let server = StaticHttpServer::spawn_echo(64).await;+ let base = server.base_url();+ let origin = serde_json::to_string(base.as_str().trim_end_matches('/')).unwrap();let loader = static_http_loader([]);- let mut vm =- new_page_task_executor_test_vm_with_loader("https://no-cors-fill.test/", &loader);+ let mut vm = new_page_task_executor_test_vm_with_loader(base.as_str(), &loader);vm.eval("globalThis.headerFillResult = null;").unwrap();let script = if worker {let source = format!(- "{fixture}\nnoCorsFillProbe('https://no-cors-fill.test', false).then(postMessage, error => postMessage({{error: String(error.stack || error)}}));"+ "{fixture}\nnoCorsFillProbe({origin}).then(postMessage, error => postMessage({{error: String(error.stack || error)}}));");format!(r#"@@ -28,7 +30,7 @@ async fn no_cors_header_fill_uses_append_guards_in_window_and_worker() {)} else {format!(- "{fixture}\nnoCorsFillProbe('https://no-cors-fill.test', false).then(value => {{ headerFillResult = value; }}, error => {{ headerFillResult = {{error: String(error.stack || error)}}; }});"+ "{fixture}\nnoCorsFillProbe({origin}).then(value => {{ headerFillResult = value; }}, error => {{ headerFillResult = {{error: String(error.stack || error)}}; }});")};vm.eval(&script).unwrap();@@ -50,6 +52,7 @@ async fn no_cors_header_fill_uses_append_guards_in_window_and_worker() {.filter(|check| check["pass"] != true).collect();assert_eq!(result["state"], "pass", "worker={worker}: {failures:?}");- assert_eq!(checks.len(), 208, "worker={worker}");+ assert_eq!(checks.len(), 320, "worker={worker}");+ assert_eq!(server.finish().await.len(), 64, "worker={worker}");}}diff --git a/moli-renderer-v8/tests/fixtures/no-cors-header-fill.js b/moli-renderer-v8/tests/fixtures/no-cors-header-fill.jsindex 4e55577c8..2d5a7d792 100644--- a/moli-renderer-v8/tests/fixtures/no-cors-header-fill.js+++ b/moli-renderer-v8/tests/fixtures/no-cors-header-fill.js@@ -1,4 +1,4 @@-async function noCorsFillProbe(base, transport = true) {+async function noCorsFillProbe(base) {const checks = [];const check = (label, actual, wanted) => checks.push({label, actual, wanted, pass: actual === wanted});const cases = [];@@ -35,23 +35,34 @@ async function noCorsFillProbe(base, transport = true) {check(label + '/inherited-mode', new Request(inherited, {headers: pairs}).headers.get(name), wanted);const cors = new Request(url, {headers: pairs});check(label + '/override', new Request(cors, {mode: 'no-cors', headers: pairs}).headers.get(name), wanted);+ Object.defineProperty(cors.headers, Symbol.iterator, {+ get() { throw new Error('Inherited headers must not use the JS iterator'); }+ });+ // Without init.headers, Request copies the underlying header list and+ // appends each entry under the new guard (Fetch Request constructor).+ check(label + '/inherited-headers', new Request(cors, {mode: 'no-cors'}).headers.get(name), wanted);+ check(label + '/inherited-clone', new Request(cors.clone(), {mode: 'no-cors'}).headers.get(name), wanted);+ const appendedCors = new Request(url);+ for (const [key, value] of pairs) appendedCors.headers.append(key, value);+ check(label + '/inherited-appended', new Request(appendedCors, {mode: 'no-cors'}).headers.get(name), wanted);+ // Explicit init.headers is a HeadersInit union (sequence or record).+ // WebIDL consumes Headers' JS iterator, whose values are combined already.check(label + '/headers-init', new Request(url, {mode: 'no-cors', headers: new Headers(pairs)}).headers.get(name), mergedWanted);check(label + '/cors', cors.headers.get(name), joined);check(label + '/response', new Response(null, {headers: pairs}).headers.get(name), joined);check(label + '/input-unchanged', JSON.stringify(pairs), original);- if (transport) {- for (const [kind, input, init] of [- ['direct', url, {mode: 'no-cors', headers: pairs}],- ['captured', request, undefined],- ['override', cors, {mode: 'no-cors', headers: pairs}],- ]) {- let actual;- try {- const response = await fetch(input, init);- actual = new Headers((await response.json()).headers).get(name);- } catch (error) { actual = String(error); }- check(label + '/fetch-' + kind, actual, wanted);- }+ for (const [kind, input, init] of [+ ['direct', url, {mode: 'no-cors', headers: pairs}],+ ['captured', request, undefined],+ ['override', cors, {mode: 'no-cors', headers: pairs}],+ ['inherited', cors, {mode: 'no-cors'}],+ ]) {+ let actual;+ try {+ const response = await fetch(input, init);+ actual = new Headers((await response.json()).headers).get(name);+ } catch (error) { actual = String(error); }+ check(label + '/fetch-' + kind, actual, wanted);}const reset = name === 'Content-Type' ? 'text/plain' : 'reset';request.headers.set(name, reset);diff --git a/moli-wpt-compat/fixtures/wpt/ported/fetch/headers-exception-propagation-basic.html b/moli-wpt-compat/fixtures/wpt/ported/fetch/headers-exception-propagation-basic.htmlindex 958aefa9e..4182face7 100644--- a/moli-wpt-compat/fixtures/wpt/ported/fetch/headers-exception-propagation-basic.html+++ b/moli-wpt-compat/fixtures/wpt/ported/fetch/headers-exception-propagation-basic.html@@ -123,10 +123,23 @@ test(function () {throw new RangeError("request headers getter failed");},});+ assert_equals(new Request(request).headers.get("x-test"), "one",+ "Request(input) should copy the internal header list");+ assert_equals(request.clone().headers.get("x-test"), "one",+ "Request.clone() should copy the internal header list");+}, "Request copies internal headers without invoking an input headers getter");++test(function () {+ const init = {};+ Object.defineProperty(init, "headers", {+ get() {+ throw new RangeError("request init headers getter failed");+ },+ });assert_throws_name("RangeError", function () {- new Request(request);- }, "Request(input) should propagate a throwing input headers getter");-}, "Request constructor propagates throwing input headers getter");+ new Request("https://example.test/headers", init);+ }, "Request init should propagate a throwing headers getter");+}, "Request constructor propagates throwing init headers getter");test(function () {const init = {};