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 HTTP header bytes across the transport
ldm0ba11283d57e5
diff --git a/moli-fetch/src/blocking/collectors.rs b/moli-fetch/src/blocking/collectors.rsindex 014624866..08d96f5d6 100644--- a/moli-fetch/src/blocking/collectors.rs+++ b/moli-fetch/src/blocking/collectors.rs@@ -14,6 +14,7 @@ use url::Url;use crate::{FetchCancelHandle, FetchConfig, NegotiatedHttpVersion, NetworkRequestExtraInfo, Request,client_hints::{ClientHintResponseAction, ClientHintResponsePolicy},+ headers::{decode_http_header_bytes, parse_http_header_line},};use crate::RedirectInfo;@@ -945,7 +946,7 @@ impl Handler for ResponseCollector {}fn header(&mut self, data: &[u8]) -> bool {- let line = String::from_utf8_lossy(data);+ let line = decode_http_header_bytes(data);let line = line.trim_end_matches(['\r', '\n']);if line.is_empty() {@@ -958,12 +959,10 @@ impl Handler for ResponseCollector {return true;}- let Some((name, value)) = line.split_once(':') else {+ let Some((mut name, value)) = parse_http_header_line(line) else {return true;};-- let name = name.trim().to_ascii_lowercase();- let value = value.trim().to_owned();+ name.make_ascii_lowercase();if name == "content-length"&& self@@ -1003,7 +1002,7 @@ impl Handler for StreamingResponseCollector {}fn header(&mut self, data: &[u8]) -> bool {- let line = String::from_utf8_lossy(data);+ let line = decode_http_header_bytes(data);let line = line.trim_end_matches(['\r', '\n']);if line.is_empty() {@@ -1024,12 +1023,10 @@ impl Handler for StreamingResponseCollector {return true;}- let Some((name, value)) = line.split_once(':') else {+ let Some((mut name, value)) = parse_http_header_line(line) else {return true;};-- let name = name.trim().to_ascii_lowercase();- let value = value.trim().to_owned();+ name.make_ascii_lowercase();if name == "content-length"&& self@@ -1076,7 +1073,7 @@ impl Handler for RawStreamingResponseCollector {}fn header(&mut self, data: &[u8]) -> bool {- let line = String::from_utf8_lossy(data);+ let line = decode_http_header_bytes(data);let line = line.trim_end_matches(['\r', '\n']);if line.is_empty() {@@ -1097,12 +1094,10 @@ impl Handler for RawStreamingResponseCollector {return true;}- let Some((name, value)) = line.split_once(':') else {+ let Some((mut name, value)) = parse_http_header_line(line) else {return true;};-- let name = name.trim().to_ascii_lowercase();- let value = value.trim().to_owned();+ name.make_ascii_lowercase();if name == "content-length"&& selfdiff --git a/moli-fetch/src/blocking/mod.rs b/moli-fetch/src/blocking/mod.rsindex eb3aef09e..d0279d39e 100644--- a/moli-fetch/src/blocking/mod.rs+++ b/moli-fetch/src/blocking/mod.rs@@ -1,5 +1,8 @@mod cache;mod collectors;+mod request_headers;++pub(crate) use request_headers::RequestHeaderList;use std::{ffi::{c_char, c_long},@@ -513,8 +516,8 @@ pub(crate) fn store_response_cookies())}-pub(crate) fn configure_easy<H: Handler>(- easy: &mut Easy2<H>,+pub(crate) fn configure_easy(+ easy: &mut Easy2<crate::runtime::FetchTransferHandler>,config: &FetchConfig,proxy_route: &HttpProxyRoute,request: &Request,@@ -648,7 +651,7 @@ pub(crate) fn configure_easy<H: Handler>(.context("failed to configure curl host resolve overrides")?;}- let mut headers = List::new();+ let mut headers = RequestHeaderList::default();let mut outgoing_headers =outgoing_request_headers_for_url(config, request, request_url, cookie_header);// A 407 can come from a transparent proxy even when no explicit proxy@@ -666,7 +669,6 @@ pub(crate) fn configure_easy<H: Handler>(.append_request_headers(&mut outgoing_headers, &request.method, request_url).with_context(|| anyhow!("failed to sign web bot auth request for {request_url}"))?;}- let mut has_headers = false;let mut has_content_type_header = false;for (name, value) in &outgoing_headers {@@ -679,7 +681,6 @@ pub(crate) fn configure_easy<H: Handler>(headers.append(&header_line).context("failed to build request header")?;- has_headers = true;}if let Some(validation_headers) = validation_headers {for (name, value) in validation_headers {@@ -687,7 +688,6 @@ pub(crate) fn configure_easy<H: Handler>(headers.append(&format!("{name}: {value}")).context("failed to build cache validation request header")?;- has_headers = true;}}if (request.method.eq_ignore_ascii_case("POST")@@ -700,12 +700,6 @@ pub(crate) fn configure_easy<H: Handler>(headers.append("Content-Type:").context("failed to suppress curl default content-type")?;- has_headers = true;- }-- if has_headers {- easy.http_headers(headers)- .context("failed to attach curl request headers")?;}if let Some(auth) = request.auth()@@ -747,6 +741,7 @@ pub(crate) fn configure_easy<H: Handler>(}}+ crate::runtime::FetchTransferHandler::set_request_headers(easy, headers)?;Ok(outgoing_headers)}diff --git a/moli-fetch/src/blocking/request_headers.rs b/moli-fetch/src/blocking/request_headers.rsnew file mode 100644index 000000000..0c4ca295a--- /dev/null+++ b/moli-fetch/src/blocking/request_headers.rs@@ -0,0 +1,64 @@+use std::ffi::CString;++use anyhow::{Context, Result};++// curl::easy::List only accepts UTF-8 strings. Own a libcurl list here so the+// transport can send ByteString header values without re-encoding them.+#[derive(Default)]+pub(crate) struct RequestHeaderList {+ raw: *mut curl_sys::curl_slist,+}++// SAFETY: the list has a single owner and no thread-affine state. Once attached,+// it moves with its Easy2 handler and is never mutated during a transfer.+unsafe impl Send for RequestHeaderList {}++impl RequestHeaderList {+ pub(crate) fn append(&mut self, line: &str) -> Result<()> {+ let line = if line.is_ascii() {+ CString::new(line.as_bytes())+ } else {+ let bytes = line+ .chars()+ .map(|ch| u8::try_from(u32::from(ch)))+ .collect::<std::result::Result<Vec<_>, _>>()+ .context("HTTP request header contains a non-byte character")?;+ CString::new(bytes)+ }+ .context("HTTP request header contains NUL")?;+ // SAFETY: self.raw is null or a live list owned by self. libcurl copies+ // the NUL-terminated string; failure leaves the existing list intact.+ let raw = unsafe { curl_sys::curl_slist_append(self.raw, line.as_ptr()) };+ if raw.is_null() {+ return Err(curl::Error::new(curl_sys::CURLE_OUT_OF_MEMORY).into());+ }+ self.raw = raw;+ Ok(())+ }++ pub(crate) fn as_ptr(&self) -> *mut curl_sys::curl_slist {+ self.raw+ }+}++impl Drop for RequestHeaderList {+ fn drop(&mut self) {+ // SAFETY: this is the sole owner, and Easy2 cleans up the curl handle+ // before dropping its handler and this list.+ unsafe { curl_sys::curl_slist_free_all(self.raw) };+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rejects_non_byte_characters_and_nul() {+ let mut headers = RequestHeaderList::default();+ headers.append("X-Valid: \u{ff}").unwrap();+ assert!(headers.append("X-Invalid: \u{100}").is_err());+ assert!(headers.append("X-Invalid: before\0after").is_err());+ headers.append("X-Valid: after").unwrap();+ }+}diff --git a/moli-fetch/src/headers.rs b/moli-fetch/src/headers.rsindex 39f5f91a6..285d528fb 100644--- a/moli-fetch/src/headers.rs+++ b/moli-fetch/src/headers.rs@@ -1,5 +1,28 @@+use std::borrow::Cow;+use moli_web_mime::request_header_content_type_essence;+// Header strings represent HTTP bytes one-for-one, including obs-text. UTF-8+// decoding would either replace bytes or combine a valid multibyte sequence.+pub(crate) fn decode_http_header_bytes(data: &[u8]) -> Cow<'_, str> {+ if data.is_ascii() {+ Cow::Borrowed(std::str::from_utf8(data).expect("ASCII is valid UTF-8"))+ } else {+ Cow::Owned(data.iter().copied().map(char::from).collect())+ }+}++pub(crate) fn parse_http_header_line(line: &str) -> Option<(String, String)> {+ let line = line.trim_end_matches(['\r', '\n']);+ let (name, value) = line.split_once(':')?;+ let name = name.trim_matches([' ', '\t']);+ if name.is_empty() {+ return None;+ }+ // Only HTTP OWS is framing. NBSP and NEL are ordinary header bytes.+ Some((name.to_owned(), value.trim_matches([' ', '\t']).to_owned()))+}+pub fn is_forbidden_request_header_name(name: &str) -> bool {let name = name.to_ascii_lowercase();matches!(diff --git a/moli-fetch/src/network_fetch_result.rs b/moli-fetch/src/network_fetch_result.rsindex e692bf04f..894e260b3 100644--- a/moli-fetch/src/network_fetch_result.rs+++ b/moli-fetch/src/network_fetch_result.rs@@ -1,3 +1,5 @@+use crate::headers::{decode_http_header_bytes, parse_http_header_line};+use std::{fmt, sync::Arc};use moli_cookie_jar::StoredCookieQueryReport;@@ -233,7 +235,7 @@ impl NetworkObservationRecorder {if state.journal.truncated {return;}- let line = String::from_utf8_lossy(data);+ let line = decode_http_header_bytes(data);let line = line.trim_end_matches(['\r', '\n']);if let Some(status) = parse_status_line(line) {@@ -273,7 +275,7 @@ impl NetworkObservationRecorder {response.truncated = true;return;}- if let Some(header) = parse_header_line(line) {+ if let Some(header) = parse_http_header_line(line) {response.headers.push(header);}}@@ -323,7 +325,7 @@ fn bounded_header_data(data: &[u8]) -> (&[u8], bool) {}fn parse_request_header_block(data: &[u8]) -> Vec<(String, String)> {- String::from_utf8_lossy(data)+ decode_http_header_bytes(data).lines().enumerate().filter_map(|(index, line)| {@@ -331,7 +333,7 @@ fn parse_request_header_block(data: &[u8]) -> Vec<(String, String)> {if (index == 0 && is_http_request_line(line)) || line.starts_with(':') {return None;}- parse_header_line(line)+ parse_http_header_line(line)}).collect()}@@ -351,15 +353,6 @@ fn is_http_request_line(line: &str) -> bool {&& version.starts_with("HTTP/")}-fn parse_header_line(line: &str) -> Option<(String, String)> {- let (name, value) = line.split_once(':')?;- let name = name.trim();- if name.is_empty() {- return None;- }- Some((name.to_owned(), value.trim().to_owned()))-}-fn parse_status_line(line: &str) -> Option<u16> {line.strip_prefix("HTTP/")?.split_whitespace()diff --git a/moli-fetch/src/proxy_connect.rs b/moli-fetch/src/proxy_connect.rsindex d0ea33fa8..d7e9ac23e 100644--- a/moli-fetch/src/proxy_connect.rs+++ b/moli-fetch/src/proxy_connect.rs@@ -1,3 +1,5 @@+use crate::headers::{decode_http_header_bytes, parse_http_header_line};+const MAX_PROXY_CONNECT_HEADER_BYTES: usize = 256 * 1024;#[derive(Clone, Debug, Eq, PartialEq)]@@ -52,7 +54,7 @@ impl ProxyConnectResponseRecorder {return;}- let line = String::from_utf8_lossy(data);+ let line = decode_http_header_bytes(data);let line = line.trim_end_matches(['\r', '\n']);if let Some(status) = parse_status_line(line) {self.pending_status = Some(status);@@ -70,7 +72,7 @@ impl ProxyConnectResponseRecorder {});return;}- if let Some(header) = parse_header_line(line) {+ if let Some(header) = parse_http_header_line(line) {self.pending_headers.push(header);}}@@ -102,15 +104,6 @@ fn parse_status_line(line: &str) -> Option<u16> {.ok()}-fn parse_header_line(line: &str) -> Option<(String, String)> {- let (name, value) = line.split_once(':')?;- let name = name.trim();- if name.is_empty() {- return None;- }- Some((name.to_owned(), value.trim().to_owned()))-}-#[cfg(test)]mod tests {use super::*;@@ -123,7 +116,7 @@ mod tests {b"CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n"));recorder.record_incoming_header_line(b"HTTP/1.1 407 Proxy Authentication Required\r\n");- recorder.record_incoming_header_line(b"Proxy-Authenticate: Basic realm=\"proxy\"\r\n");+ recorder.record_incoming_header_line(b"Proxy-Authenticate: Basic realm=\"\xff\"\r\n");recorder.record_incoming_header_line(b"\r\n");assert!(@@ -141,7 +134,7 @@ mod tests {status: 407,headers: vec![("Proxy-Authenticate".to_owned(),- "Basic realm=\"proxy\"".to_owned(),+ "Basic realm=\"\u{ff}\"".to_owned(),)],}));diff --git a/moli-fetch/src/runtime.rs b/moli-fetch/src/runtime.rsindex e7c27dd3b..2eff43475 100644--- a/moli-fetch/src/runtime.rs+++ b/moli-fetch/src/runtime.rs@@ -2658,7 +2658,8 @@ struct ActiveRawStreamingTransferContext {effective_request: Request,}-struct FetchTransferHandler {+pub(crate) struct FetchTransferHandler {+ request_headers: crate::blocking::RequestHeaderList,response: FetchResponseCollector,network_observation_recorder: Option<NetworkObservationRecorder>,proxy_connect_response_recorder: ProxyConnectResponseRecorder,@@ -2671,6 +2672,23 @@ enum FetchResponseCollector {}impl FetchTransferHandler {+ pub(crate) fn set_request_headers(+ easy: &mut Easy2<Self>,+ headers: crate::blocking::RequestHeaderList,+ ) -> Result<()> {+ // SAFETY: libcurl borrows this list. On success, retain it in the+ // handler until replacement or Easy2 cleanup (which precedes handler+ // destruction). Keep the previous list alive if setopt fails.+ let result = unsafe {+ curl_sys::curl_easy_setopt(easy.raw(), curl_sys::CURLOPT_HTTPHEADER, headers.as_ptr())+ };+ if result != curl_sys::CURLE_OK {+ return Err(curl::Error::new(result)).context("failed to attach curl request headers");+ }+ easy.get_mut().request_headers = headers;+ Ok(())+ }+fn new_buffered(collector: ResponseCollector) -> Self {Self::new(FetchResponseCollector::Buffered(collector))}@@ -2685,6 +2703,7 @@ impl FetchTransferHandler {fn new(response: FetchResponseCollector) -> Self {Self {+ request_headers: crate::blocking::RequestHeaderList::default(),response,network_observation_recorder: None,proxy_connect_response_recorder: ProxyConnectResponseRecorder::default(),diff --git a/moli-fetch/src/tests/header_bytes.rs b/moli-fetch/src/tests/header_bytes.rsnew file mode 100644index 000000000..35b53ec91--- /dev/null+++ b/moli-fetch/src/tests/header_bytes.rs@@ -0,0 +1,189 @@+use super::*;+use crate::network_fetch_result::NetworkObservationRecorder;++async fn serve_responses(listener: TcpListener, responses: Vec<Vec<u8>>) -> Result<Vec<Vec<u8>>> {+ let mut requests = Vec::new();+ for response in responses {+ let (mut stream, _) =+ tokio::time::timeout(Duration::from_secs(5), listener.accept()).await??;+ let mut request = Vec::new();+ while !request.windows(4).any(|part| part == b"\r\n\r\n") {+ let mut chunk = [0; 1024];+ let count =+ tokio::time::timeout(Duration::from_secs(5), stream.read(&mut chunk)).await??;+ anyhow::ensure!(+ count != 0 && request.len() < 64 * 1024,+ "incomplete request"+ );+ request.extend_from_slice(&chunk[..count]);+ }+ requests.push(request);+ stream.write_all(&response).await?;+ stream.shutdown().await?;+ }+ Ok(requests)+}++fn response(headers: &[u8]) -> Vec<u8> {+ [+ b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n".as_slice(),+ headers,+ b"\r\n\x00\xff\x80",+ ]+ .concat()+}++async fn fetch_in_mode(+ client: &FetchClientHandle,+ request: Request,+ mode: &str,+) -> Result<(ResponseHead, Vec<u8>)> {+ let (head, body) = match mode {+ "buffered" => client+ .fetch(request.with_follow_redirects(false))+ .await?+ .into_body(),+ "html" => client.fetch_html_stream(request).await?.into_body(),+ "raw" => client+ .fetch_raw_stream_with_cancel(request, FetchCancelHandle::new())+ .await?+ .into_body(),+ _ => unreachable!(),+ };+ Ok((head, body.into_materialized_bytes().await?))+}++#[tokio::test]+async fn http_header_bytes_survive_all_transports_and_observation() -> Result<()> {+ let bytes: Vec<u8> = (0x80..=0xff).collect();+ let value: String = bytes.iter().copied().map(char::from).collect();+ let headers = [+ b"X-Bytes: \t".as_slice(),+ bytes.as_slice(),+ b" \t\r\n",+ b"X-Edges: \t\xa0value\x85 \t\r\n",+ b"X-Utf8: \xc3\xbf\xe4\xb8\xad\r\n",+ b"X-Empty: \t \r\nX-Repeat: first\r\nX-Repeat: second\r\n",+ ]+ .concat();+ let listener = TcpListener::bind("127.0.0.1:0").await?;+ let url = format!("http://{}/bytes", listener.local_addr()?);+ let server = tokio::spawn(serve_responses(listener, vec![response(&headers); 3]));+ let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());+ for mode in ["buffered", "html", "raw"] {+ let recorder = NetworkObservationRecorder::default();+ let request = Request::new("GET", &url, None, vec![("X-Bytes".into(), value.clone())])?+ .with_network_observation_recorder(recorder.clone());+ let (head, body) = fetch_in_mode(&client, request, mode).await?;+ // The HTML stream intentionally decodes the body as text, independently+ // of header ByteStrings. The raw and buffered paths preserve its bytes.+ if mode != "html" {+ assert_eq!(body, [0, 255, 128], "{mode}");+ }+ let expected = [+ ("x-bytes".to_owned(), value.clone()),+ ("x-edges".to_owned(), "\u{a0}value\u{85}".to_owned()),+ (+ "x-utf8".to_owned(),+ "\u{c3}\u{bf}\u{e4}\u{b8}\u{ad}".to_owned(),+ ),+ ("x-empty".to_owned(), String::new()),+ ("x-repeat".to_owned(), "first".to_owned()),+ ("x-repeat".to_owned(), "second".to_owned()),+ ];+ assert_eq!(+ head.headers+ .iter()+ .filter(|(n, _)| n.starts_with("x-"))+ .cloned()+ .collect::<Vec<_>>(),+ expected,+ "{mode}"+ );+ let journal = recorder.snapshot();+ let received = journal.final_response_observation().unwrap().headers();+ assert_eq!(+ received+ .iter()+ .filter(|(n, _)| n.starts_with("X-"))+ .map(|(n, v)| (n.to_ascii_lowercase(), v.clone()))+ .collect::<Vec<_>>(),+ expected,+ "{mode}"+ );+ let sent = journal.final_request_observation().unwrap().headers();+ assert!(+ sent.contains(&("X-Bytes".into(), value.clone())),+ "{mode}: {sent:?}"+ );+ }+ let expected_line = [b"X-Bytes: ".as_slice(), bytes.as_slice(), b"\r\n"].concat();+ for request in server.await?? {+ assert!(+ request+ .windows(expected_line.len())+ .any(|part| part == expected_line)+ );+ }+ assert!(client.shutdown().is_clean());+ Ok(())+}++#[tokio::test]+async fn http_header_bytes_survive_redirect_handle_reuse() -> Result<()> {+ let listener = TcpListener::bind("127.0.0.1:0").await?;+ let url = format!("http://{}/start", listener.local_addr()?);+ let redirect = b"HTTP/1.1 307 Redirect\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec();+ let server = tokio::spawn(serve_responses(+ listener,+ vec![redirect, response(b"X-Bytes: \xff\r\n")],+ ));+ let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());+ let request = Request::new("GET", &url, None, vec![("X-Bytes".into(), "\u{ff}".into())])?;+ let (head, body) = fetch_in_mode(&client, request, "raw").await?;+ assert!(head.redirected);+ assert_eq!(head.final_url.path(), "/final");+ assert_eq!(body, [0, 255, 128]);+ assert!(head.headers.contains(&("x-bytes".into(), "\u{ff}".into())));+ let requests = server.await??;+ assert_eq!(requests.len(), 2);+ for request in requests {+ assert!(+ request+ .windows(b"X-Bytes: \xff\r\n".len())+ .any(|part| part == b"X-Bytes: \xff\r\n")+ );+ }+ assert!(client.shutdown().is_clean());+ Ok(())+}++#[tokio::test]+async fn http_header_bytes_survive_disk_cache_reopen() -> Result<()> {+ for first_mode in ["html", "raw"] {+ let cache_dir = unique_test_cache_dir();+ let listener = TcpListener::bind("127.0.0.1:0").await?;+ let url = format!("http://{}/cache", listener.local_addr()?);+ let server = tokio::spawn(serve_responses(+ listener,+ vec![response(+ b"Cache-Control: max-age=60\r\nX-Bytes: \xa0\xc3\xbf\x85\r\n",+ )],+ ));+ let mut config = FetchConfig::default();+ config.set_http_cache_dir(Some(cache_dir.display().to_string()));+ for (index, mode) in [first_mode, "html", "raw"].into_iter().enumerate() {+ let client = FetchClient::new(&config, new_shared_browser_cookie_store());+ let (head, _) = fetch_in_mode(&client, Request::get(&url)?, mode).await?;+ assert_eq!(head.from_cache, index != 0, "{first_mode} to {mode}");+ assert!(+ head.headers+ .contains(&("x-bytes".into(), "\u{a0}\u{c3}\u{bf}\u{85}".into()))+ );+ assert!(client.shutdown().is_clean());+ }+ assert_eq!(server.await??.len(), 1);+ fs::remove_dir_all(cache_dir)?;+ }+ Ok(())+}diff --git a/moli-fetch/src/tests/mod.rs b/moli-fetch/src/tests/mod.rsindex 3b8bf021d..573a6d09a 100644--- a/moli-fetch/src/tests/mod.rs+++ b/moli-fetch/src/tests/mod.rs@@ -1,5 +1,6 @@mod cookie_context;mod cookie_store;+mod header_bytes;mod mixed_transport;mod request_security;mod support;