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): reject page output from raw headers
ldm04c4055d5e0ae
diff --git a/moli-core/src/runtime/lifecycle_fetch.rs b/moli-core/src/runtime/lifecycle_fetch.rsindex b8483d5a8..9f652c247 100644--- a/moli-core/src/runtime/lifecycle_fetch.rs+++ b/moli-core/src/runtime/lifecycle_fetch.rs@@ -5,7 +5,7 @@//! lifecycle decision cannot reset or extend the caller's timeout budget.use super::{- Browser, FetchDeadline, FetchedDocument, RawDocumentDisposition, RenderedDomWaitUntil,+ Browser, FetchDeadline, FetchedDocument, RawDocumentFetchPolicy, RenderedDomWaitUntil,RendererLifecycleDecider, RendererLifecycleDecision, RendererLifecycleSnapshot,RendererReplyBoundary,};@@ -33,18 +33,25 @@ impl Browser {{let deadline = FetchDeadline::new(timeout)?;self.fetch_document_with_lifecycle_decider_and_deadline(- request, wait_until, deadline, decider,+ request,+ wait_until,+ deadline,+ RawDocumentFetchPolicy::Materialize,+ decider,).await}/// Applies a lifecycle decision using a caller-owned absolute deadline.- /// The same deadline can then gate response, selector, and script waits.+ /// The same deadline can then gate response, selector, and script waits;+ /// `raw_document_policy` decides whether a non-Page response is read or+ /// rejected from its headers.pub async fn fetch_document_with_lifecycle_decider_and_deadline<F>(&self,request: Request,wait_until: RenderedDomWaitUntil,deadline: FetchDeadline,+ raw_document_policy: RawDocumentFetchPolicy,decider: F,) -> Result<FetchedDocument>where@@ -66,7 +73,7 @@ impl Browser {deadline,RendererReplyBoundary::Stage,Some(decider),- RawDocumentDisposition::Materialize,+ raw_document_policy,).await}diff --git a/moli-core/src/runtime/mod.rs b/moli-core/src/runtime/mod.rsindex 753de7a1b..d6a18fa89 100644--- a/moli-core/src/runtime/mod.rs+++ b/moli-core/src/runtime/mod.rs@@ -23,6 +23,7 @@ use moli_renderer_v8::network::{};use moli_url::is_about_blank as is_about_blank_url;use moli_web_mime::response_headers_indicate_raw_document;+use std::fmt;use std::sync::atomic::{AtomicU64, Ordering};use std::time::Duration;use std::time::Instant;@@ -52,14 +53,32 @@ pub use navigation_engine::{static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);+/// Controls whether a document fetch may consume a raw/download response.#[derive(Clone, Copy, Debug, Eq, PartialEq)]-enum RawDocumentDisposition {+pub enum RawDocumentFetchPolicy {+ /// Read the response body and return [`FetchedDocument::Raw`].Materialize,- RejectForPageApi,+ /// Require a renderable Page, rejecting raw responses from their headers.+ RequirePage,}-fn raw_document_page_api_error() -> anyhow::Error {- anyhow!("raw non-HTML document cannot be returned through the Page fetch API")+/// Typed rejection produced by [`RawDocumentFetchPolicy::RequirePage`].+#[derive(Debug)]+pub struct RawDocumentPageRequired;++impl fmt::Display for RawDocumentPageRequired {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("raw non-HTML document cannot be returned through the Page fetch API")+ }+}++impl std::error::Error for RawDocumentPageRequired {}++fn ensure_raw_document_materialization_allowed(policy: RawDocumentFetchPolicy) -> Result<()> {+ match policy {+ RawDocumentFetchPolicy::Materialize => Ok(()),+ RawDocumentFetchPolicy::RequirePage => Err(anyhow::Error::new(RawDocumentPageRequired)),+ }}fn is_fetch_readiness_timeout(error: &anyhow::Error, wait_until: RenderedDomWaitUntil) -> bool {@@ -386,7 +405,7 @@ impl Browser {deadline,RendererReplyBoundary::Stage,None,- RawDocumentDisposition::RejectForPageApi,+ RawDocumentFetchPolicy::RequirePage,).await?{@@ -412,18 +431,24 @@ impl Browser {) -> Result<FetchedDocument> {let deadline = FetchDeadline::new(timeout)?;self.fetch_request_document_allow_http_error_with_wait_until_deadline(- request, wait_until, deadline,+ request,+ wait_until,+ deadline,+ RawDocumentFetchPolicy::Materialize,).await}/// Fetches a document to `wait_until` without starting a new timeout- /// budget. Callers can reuse `deadline` for later readiness conditions.+ /// budget. Callers can reuse `deadline` for later readiness conditions and+ /// choose whether raw responses are materialized or rejected from their+ /// headers.pub async fn fetch_request_document_allow_http_error_with_wait_until_deadline(&self,request: Request,wait_until: RenderedDomWaitUntil,deadline: FetchDeadline,+ raw_document_policy: RawDocumentFetchPolicy,) -> Result<FetchedDocument> {let fetched = self.fetch_document_to_base_stage(@@ -432,7 +457,7 @@ impl Browser {deadline,RendererReplyBoundary::Stage,None,- RawDocumentDisposition::Materialize,+ raw_document_policy,).await?;@@ -456,7 +481,7 @@ impl Browser {deadline: FetchDeadline,reply_boundary: RendererReplyBoundary,lifecycle_decider: Option<RendererLifecycleDecider>,- raw_document_disposition: RawDocumentDisposition,+ raw_document_policy: RawDocumentFetchPolicy,) -> Result<FetchedDocument> {let timeout = deadline.timeout();let stage = wait_until.base_stage();@@ -522,9 +547,7 @@ impl Browser {if let Some(response) = response {navigation_loader.note_service_worker_response_ready()?;if response_headers_indicate_raw_document(&response.headers) {- if raw_document_disposition == RawDocumentDisposition::RejectForPageApi {- return Err(raw_document_page_api_error());- }+ ensure_raw_document_materialization_allowed(raw_document_policy)?;let raw_response =RawResponse::from_head_and_body(response.head(), response.clone_body_bytes());return Ok(FetchedDocument::Raw(Box::new(RawDocument::from_response(@@ -570,9 +593,7 @@ impl Browser {).await?;if response_headers_indicate_raw_document(&response.headers) {- if raw_document_disposition == RawDocumentDisposition::RejectForPageApi {- return Err(raw_document_page_api_error());- }+ ensure_raw_document_materialization_allowed(raw_document_policy)?;// Binary/download-like main resources have no DOM lifecycle// milestones, but materializing a RawDocument still consumes the// caller-owned absolute fetch-readiness budget.diff --git a/moli-core/src/runtime/tests.rs b/moli-core/src/runtime/tests.rsindex bec5bd58d..948ec1d4b 100644--- a/moli-core/src/runtime/tests.rs+++ b/moli-core/src/runtime/tests.rs@@ -2,7 +2,7 @@ use moli_test_support as support;use super::{Browser, FetchDeadline, FetchedDocument, NavigationEngine, NavigationPageStorageHandles,- NavigationResourceStorageHandles, RenderedDomWaitUntil,+ NavigationResourceStorageHandles, RawDocumentFetchPolicy, RenderedDomWaitUntil,external_raw_document_body_from_streaming_response_with_body_eof_observer,};use crate::{@@ -2089,6 +2089,7 @@ async fn fetch_deadline_spans_lifecycle_selector_and_script_without_reset() -> RRequest::get(&server.url("/static"))?,RenderedDomWaitUntil::Load,deadline,+ RawDocumentFetchPolicy::Materialize,).await?;let FetchedDocument::Page(mut page) = fetched else {@@ -2153,6 +2154,7 @@ async fn best_effort_page_readiness_consumes_only_the_remaining_fetch_deadline()Request::get(&server.url(path))?,wait_until,deadline,+ RawDocumentFetchPolicy::Materialize,).await?;let elapsed = started.elapsed();diff --git a/moli-core/tests/fetch.rs b/moli-core/tests/fetch.rsindex 5c59a66ed..49a8440a3 100644--- a/moli-core/tests/fetch.rs+++ b/moli-core/tests/fetch.rs@@ -3,7 +3,7 @@ use moli_test_support as support;use anyhow::Result;use moli_core::runtime::{Browser, BrowserConfig as AppConfig, FetchReadinessTimeout, FetchTimeoutPhase,- RenderedDomWaitUntil,+ RawDocumentPageRequired, RenderedDomWaitUntil,};use moli_fetch::Request;use std::time::{Duration, Instant};@@ -194,6 +194,7 @@ async fn page_fetch_rejects_raw_response_without_waiting_for_its_stalled_body().expect("the Page API must not wait for a raw response body").expect_err("the Page API must reject a raw non-HTML document");+ assert!(error.is::<RawDocumentPageRequired>());assert_eq!(error.to_string(),"raw non-HTML document cannot be returned through the Page fetch API"diff --git a/moli/src/app.rs b/moli/src/app.rsindex f5be12a0b..8c0bff730 100644--- a/moli/src/app.rs+++ b/moli/src/app.rs@@ -55,6 +55,8 @@ pub async fn run_cli_with_config<W: Write>(};let readiness =ReadinessPlan::from_fetch_args(&args, config.fetch.response_wait.clone())?;+ let raw_document_output =+ fetch_dump::RawDocumentOutputPolicy::from_command(&config.fetch);let request = build_fetch_request(&args.url, &config)?;if config.browser.fetch().obey_robots() {// Checked before the browser starts so a refused fetch costs@@ -65,12 +67,17 @@ pub async fn run_cli_with_config<W: Write>(}let browser = Browser::new(config.browser.clone())?;load_cookie_state(&browser, &config)?;- let fetch_result = readiness.fetch_document(&browser, request).await;+ let fetch_result = readiness+ .fetch_document(&browser, request, raw_document_output.fetch_policy())+ .await;let fetched_document = match fetch_result {Ok(document) => document,Err(error) => {finalize_fetch_browser(browser);- return Err(with_fetch_context(error, &args.url));+ return Err(with_fetch_context(+ raw_document_output.map_fetch_error(error),+ &args.url,+ ));}};@@ -96,7 +103,7 @@ pub async fn run_cli_with_config<W: Write>());}let rendered =- fetch_dump::render_raw_document_output(&raw_document, &config.fetch)+ fetch_dump::render_raw_document_output(&raw_document, raw_document_output).map_err(|error| with_fetch_context(error, &args.url))?;stdout.write_all(&rendered)diff --git a/moli/src/app/readiness.rs b/moli/src/app/readiness.rsindex b61162e39..066fa3753 100644--- a/moli/src/app/readiness.rs+++ b/moli/src/app/readiness.rs@@ -12,7 +12,9 @@ use crate::cli::{FetchArgs, FetchWaitUntil};use anyhow::{Context, Result, anyhow, bail};use moli_core::{page::{Page, SubresourceResponseWaitCriteria},- runtime::{Browser, FetchDeadline, FetchedDocument, RenderedDomWaitUntil},+ runtime::{+ Browser, FetchDeadline, FetchedDocument, RawDocumentFetchPolicy, RenderedDomWaitUntil,+ },};use moli_fetch::Request;use std::{path::Path, time::Duration};@@ -52,6 +54,7 @@ impl ReadinessPlan {&self,browser: &Browser,request: Request,+ raw_document_policy: RawDocumentFetchPolicy,) -> Result<FetchedDocument> {match self.wait_until {RenderedDomWaitUntil::DomContentLoaded@@ -63,6 +66,7 @@ impl ReadinessPlan {self.wait_until,self.deadline,self.minimum_navigation_wait,+ raw_document_policy,).await}@@ -72,6 +76,7 @@ impl ReadinessPlan {request,self.wait_until,self.deadline,+ raw_document_policy,).await}diff --git a/moli/src/app/redirect_navigation.rs b/moli/src/app/redirect_navigation.rsindex 73326a6c4..5ff84d9e4 100644--- a/moli/src/app/redirect_navigation.rs+++ b/moli/src/app/redirect_navigation.rs@@ -5,7 +5,8 @@use anyhow::{Context, Result};use moli_core::runtime::{- Browser, FetchDeadline, FetchedDocument, RenderedDomWaitUntil, RendererLifecycleDecision,+ Browser, FetchDeadline, FetchedDocument, RawDocumentFetchPolicy, RenderedDomWaitUntil,+ RendererLifecycleDecision,};use moli_fetch::Request;use std::time::{Duration, Instant};@@ -20,6 +21,7 @@ pub(super) async fn fetch_with_redirect_wait(wait_until: RenderedDomWaitUntil,deadline: FetchDeadline,minimum_navigation_wait: Duration,+ raw_document_policy: RawDocumentFetchPolicy,) -> Result<FetchedDocument> {let minimum_navigation_deadline = Instant::now().checked_add(minimum_navigation_wait)@@ -35,6 +37,7 @@ pub(super) async fn fetch_with_redirect_wait(request,wait_until,deadline,+ raw_document_policy,move |target| {Ok(if uses_redirect_wait(target.status) {RendererLifecycleDecision::FollowNextDocumentOrFinish {diff --git a/moli/src/fetch_dump/mod.rs b/moli/src/fetch_dump/mod.rsindex e0f3c07d1..244ba325b 100644--- a/moli/src/fetch_dump/mod.rs+++ b/moli/src/fetch_dump/mod.rs@@ -6,10 +6,10 @@ mod semantic;#[cfg(test)]mod tests;-use anyhow::{Result, bail};+use anyhow::{Result, anyhow, bail};use moli_core::{page::{Page, RendererScreenshotRegion, SubresourceResponseWaitCriteria},- runtime::RawDocument,+ runtime::{RawDocument, RawDocumentFetchPolicy, RawDocumentPageRequired},};use crate::{@@ -20,6 +20,39 @@ use crate::{pub use node_details::summarize_node_details_async;+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub(crate) enum RawDocumentOutputPolicy {+ Passthrough,+ Json,+ RequiresPage(DumpFormat),+}++impl RawDocumentOutputPolicy {+ pub(crate) fn from_command(command: &FetchCommandConfig) -> Self {+ match command.dump_mode {+ None => Self::Passthrough,+ Some(DumpFormat::Json) => Self::Json,+ Some(format) => Self::RequiresPage(format),+ }+ }++ pub(crate) const fn fetch_policy(self) -> RawDocumentFetchPolicy {+ match self {+ Self::Passthrough | Self::Json => RawDocumentFetchPolicy::Materialize,+ Self::RequiresPage(_) => RawDocumentFetchPolicy::RequirePage,+ }+ }++ pub(crate) fn map_fetch_error(self, error: anyhow::Error) -> anyhow::Error {+ if error.is::<RawDocumentPageRequired>()+ && let Self::RequiresPage(format) = self+ {+ return raw_document_requires_page_error(format);+ }+ error+ }+}+pub async fn render_page_output_async(page: &mut Page,command: &FetchCommandConfig,@@ -64,16 +97,13 @@ pub async fn render_page_dump_async(.await}-pub fn render_raw_document_output(+pub(crate) fn render_raw_document_output(raw: &RawDocument,- command: &FetchCommandConfig,+ policy: RawDocumentOutputPolicy,) -> Result<Vec<u8>> {- match command.dump_mode {- None => Ok(raw.body_bytes().to_vec()),- Some(DumpFormat::Html) => {- bail!("--dump html requires a renderable HTML document, not a raw download")- }- Some(DumpFormat::Json) => {+ match policy {+ RawDocumentOutputPolicy::Passthrough => Ok(raw.body_bytes().to_vec()),+ RawDocumentOutputPolicy::Json => {let html = String::from_utf8_lossy(raw.body_bytes());let redirect_chain = raw.navigation_redirect_chain()@@ -92,15 +122,25 @@ pub fn render_raw_document_output()?;Ok(payload.into_bytes())}- Some(- DumpFormat::Markdown- | DumpFormat::Screenshot- | DumpFormat::ScreenshotFull- | DumpFormat::Pdf- | DumpFormat::SemanticTree- | DumpFormat::SemanticTreeText,- ) => {- bail!("raw download output only supports automatic output or --dump json")+ RawDocumentOutputPolicy::RequiresPage(format) => {+ Err(raw_document_requires_page_error(format))+ }+ }+}++fn raw_document_requires_page_error(format: DumpFormat) -> anyhow::Error {+ match format {+ DumpFormat::Html => {+ anyhow!("--dump html requires a renderable HTML document, not a raw download")+ }+ DumpFormat::Json => unreachable!("JSON output accepts raw documents"),+ DumpFormat::Markdown+ | DumpFormat::Screenshot+ | DumpFormat::ScreenshotFull+ | DumpFormat::Pdf+ | DumpFormat::SemanticTree+ | DumpFormat::SemanticTreeText => {+ anyhow!("raw download output only supports automatic output or --dump json")}}}diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rsindex 5fdfcd61d..6294da652 100644--- a/moli/tests/fetch_cli.rs+++ b/moli/tests/fetch_cli.rs@@ -31,7 +31,11 @@ use std::{};use strip_ansi_escapes::strip;use support::FixtureServer;-use tokio::{io::AsyncReadExt, net::TcpListener, task::JoinHandle};+use tokio::{+ io::{AsyncReadExt, AsyncWriteExt},+ net::TcpListener,+ task::JoinHandle,+};use tracing_subscriber::fmt::MakeWriter;#[path = "fetch_cli/anubis_deferred_module.rs"]@@ -156,15 +160,21 @@ fn run_fetch_cli_with_default_wait_and_dump(url: &str, dump: &str) -> Result<Out}fn run_fetch_cli_without_dump(url: &str) -> Result<Output> {- run_moli([+ run_fetch_cli_without_dump_with_args(url, &[])+}++fn run_fetch_cli_without_dump_with_args(url: &str, args: &[&str]) -> Result<Output> {+ let mut cli_args = vec!["moli","fetch","--log-level","error","--http-no-proxy","*",- url,- ])+ ];+ cli_args.extend_from_slice(args);+ cli_args.push(url);+ run_moli(cli_args)}fn run_moli<I, S>(args: I) -> Result<Output>@@ -285,6 +295,34 @@ struct BinaryDocumentFixtureServer {task: JoinHandle<()>,}+async fn spawn_stalled_raw_document_server() -> Result<(String, JoinHandle<()>)> {+ let listener = TcpListener::bind("127.0.0.1:0").await?;+ let address = listener.local_addr()?;+ let server = tokio::spawn(async move {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut request = [0_u8; 4096];+ let Ok(read) = stream.read(&mut request).await else {+ return;+ };+ if read == 0 {+ return;+ }+ if stream+ .write_all(+ b"HTTP/1.1 200 OK\r\nContent-Type: video/mp4\r\nContent-Length: 1048576\r\nConnection: keep-alive\r\n\r\n",+ )+ .await+ .is_err()+ {+ return;+ }+ std::future::pending::<()>().await;+ });+ Ok((format!("http://{address}/stalled.mp4"), server))+}+struct BlockingStylesheetTimeoutFixtureServer {base_url: String,task: JoinHandle<()>,@@ -1098,12 +1136,47 @@ fn cli_dump_html_rejects_raw_documents_without_partial_output() -> Result<()> {Ok(())}+#[test]+fn cli_dump_html_rejects_from_raw_headers_without_waiting_for_body() -> Result<()> {+ let runtime = tokio::runtime::Runtime::new()?;+ let (url, server) = runtime.block_on(spawn_stalled_raw_document_server())?;+ let output = run_moli([+ "moli",+ "fetch",+ "--log-level",+ "error",+ "--http-no-proxy",+ "*",+ "--http-timeout",+ "5000",+ "--timeout",+ "500",+ "--dump",+ "html",+ &url,+ ])?;+ server.abort();+ let _ = runtime.block_on(server);++ let stdout = clean_output(&output.stdout);+ let stderr = clean_output(&output.stderr);+ assert!(!output.status.success(), "stdout={stdout}\nstderr={stderr}");+ assert!(stdout.is_empty(), "stdout={stdout}");+ assert_single_fetch_failure_reason(+ &stderr,+ &url,+ "--dump html requires a renderable HTML document, not a raw download",+ );+ assert!(!stderr.contains("timed out"), "stderr={stderr}");+ Ok(())+}+#[test]fn cli_fetch_raw_document_with_page_wait_uses_fetch_failure_report() -> Result<()> {let runtime = tokio::runtime::Runtime::new()?;let server = runtime.block_on(BinaryDocumentFixtureServer::spawn())?;let url = server.url("/inline.pdf");- let output = run_fetch_cli_with_dump_and_args(&url, "html", &["--wait-script", "true"])?;+ let output = run_fetch_cli_without_dump_with_args(&url, &["--wait-script", "true"])?;runtime.block_on(server.shutdown());let stdout = clean_output(&output.stdout);