diff --git a/crates/plugin-web/src/error.rs b/crates/plugin-web/src/error.rs index 00bae23..45149ca 100644 --- a/crates/plugin-web/src/error.rs +++ b/crates/plugin-web/src/error.rs @@ -150,6 +150,13 @@ pub(crate) enum FetchError { limit: usize, }, + /// The HTML page nests elements too deeply to render. + #[error("the HTML of {url} nests elements more than {limit} levels deep, which is the limit; try a different URL", limit = crate::html_tree::MAX_DEPTH)] + TooDeep { + /// The URL whose page nests too deeply. + url: SafeUrl, + }, + /// Reading the response body failed mid-stream. #[error("the response body from {url} could not be read; try again or use a different URL")] BodyRead { @@ -248,6 +255,7 @@ impl FetchError { | FetchError::NoContentType { .. } | FetchError::Timeout { .. } | FetchError::TooLarge { .. } + | FetchError::TooDeep { .. } | FetchError::BodyRead { .. } | FetchError::Undecodable { .. } | FetchError::Dns { .. } @@ -318,7 +326,7 @@ mod tests { #[test] fn disposition_table() { let parse = url::Url::parse("not a url").expect_err("must fail to parse"); - let soft: [FetchError; 9] = [ + let soft: [FetchError; 10] = [ FetchError::HttpStatus { url: SafeUrl::new("https://u/"), status: 404, @@ -337,6 +345,9 @@ mod tests { url: SafeUrl::new("https://u/"), limit: 100, }, + FetchError::TooDeep { + url: SafeUrl::new("https://u/"), + }, FetchError::Undecodable { url: SafeUrl::new("https://u/"), charset: "x".into(), diff --git a/crates/plugin-web/src/fetch.rs b/crates/plugin-web/src/fetch.rs index 5e77bce..f997175 100644 --- a/crates/plugin-web/src/fetch.rs +++ b/crates/plugin-web/src/fetch.rs @@ -188,9 +188,14 @@ impl FetchClient { let rendering = on_blocking_thread(move || { extract_html(&decoded, Some(&base_url), raw, max_chars) }); - let Some((markdown, extraction)) = rendering.await else { + let Some(rendered) = rendering.await else { return Err(did_not_finish()); }; + let Ok((markdown, extraction)) = rendered else { + return soft_or_hard(&FetchError::TooDeep { + url: SafeUrl::new(final_url.as_str()), + }); + }; (markdown, extraction, false) } Route::Plain { structured: true } => { diff --git a/crates/plugin-web/src/fetch/tests-body.rs b/crates/plugin-web/src/fetch/tests-body.rs index 83f3a8b..cd1088d 100644 --- a/crates/plugin-web/src/fetch/tests-body.rs +++ b/crates/plugin-web/src/fetch/tests-body.rs @@ -165,6 +165,28 @@ async fn a_short_article_under_leading_spaces_is_returned_when_they_push_the_pag ); } +/// Without the limit, each of these fetches aborts the process. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_page_nested_too_deeply_is_refused_with_and_without_raw() { + let (port, _hits) = spawn_server().await; + let tool = loopback_tool(port); + + let url = format!("http://localhost:{port}/deep"); + for raw in [true, false] { + let result = tool + .call(serde_json::json!({ "url": url, "raw": raw })) + .await + .expect("a page nested too deeply is a soft return") + .text() + .to_owned(); + + assert!( + result.contains("more than 256 levels deep"), + "raw: {raw}, got: {result}" + ); + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn text_over_max_chars_is_truncated_on_char_boundary() { let (port, _hits) = spawn_server().await; diff --git a/crates/plugin-web/src/fetch/tests.rs b/crates/plugin-web/src/fetch/tests.rs index 2b6302b..ff39e90 100644 --- a/crates/plugin-web/src/fetch/tests.rs +++ b/crates/plugin-web/src/fetch/tests.rs @@ -216,6 +216,11 @@ async fn padded() -> Html { )) } +/// A page with no article, nested far past what `htmd` can render. +async fn deep() -> Html { + Html(format!("{}text", "
".repeat(100_000))) +} + async fn gzip_bomb() -> impl IntoResponse { let raw = "A".repeat(200_000); let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); @@ -371,6 +376,7 @@ async fn spawn_server() -> (u16, Arc) { .route("/archive", get(archive)) .route("/padded", get(padded)) .route("/topics", get(topics)) + .route("/deep", get(deep)) .route("/gzip", get(gzip_bomb)) .route("/liar", get(liar_content_length)) .route("/table", get(table)) diff --git a/crates/plugin-web/src/html_tree.rs b/crates/plugin-web/src/html_tree.rs new file mode 100644 index 0000000..0acd5dd --- /dev/null +++ b/crates/plugin-web/src/html_tree.rs @@ -0,0 +1,197 @@ +//! Parsing HTML into a tree whose depth is bounded. +//! +//! `htmd` renders a tree with one level of recursion for each level of +//! nesting, so a page nested a few thousand levels deep overflows the stack +//! of its thread. That aborts the process, the Host's included, and no +//! unwind can catch it. The parser itself takes time that grows with the +//! square of the depth, because a block's start tag searches the elements +//! that are open. So [`parse`] refuses a page that nests too deeply, and it +//! stops while it reads the page rather than after it. + +use std::cell::Cell; +use std::marker::PhantomData; +use std::rc::Rc; + +use html5ever::interface::Tracer; +use html5ever::tendril::{StrTendril, TendrilSink}; +use html5ever::{ParseOpts, parse_document}; +use markup5ever_rcdom::{Handle, NodeData, RcDom}; + +/// The deepest a node may sit below the document. It is half of the 512 +/// levels Chromium's parser nests, and leaves `htmd` room on the 2 MiB stack +/// of the thread that renders, where a debug build overflows before 1,000 +/// levels. +pub(crate) const MAX_DEPTH: usize = 256; + +/// How many elements the parser may hold open, checked between chunks. It +/// is over [`MAX_DEPTH`] because the count takes in handles that add no +/// depth, such as the formatting elements the parser may reopen. The check +/// of the finished tree is the exact one. +const MAX_OPEN: usize = 2 * MAX_DEPTH; + +/// The bytes of HTML the parser is given between two checks, which bounds +/// how many elements it can open past [`MAX_OPEN`]. +const CHUNK_BYTES: usize = 4096; + +/// The page nests deeper than [`MAX_DEPTH`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TooDeep; + +/// Parses `html` into the tree `htmd` renders from, with the options `htmd` +/// parses with. +/// +/// # Errors +/// Returns [`TooDeep`] when a node sits deeper than [`MAX_DEPTH`], or when +/// the parser holds more than [`MAX_OPEN`] elements open. +pub(crate) fn parse(html: &str) -> Result { + let mut parser = parse_document(RcDom::default(), ParseOpts::default()); + let mut rest = html; + while !rest.is_empty() { + let (chunk, after) = rest.split_at(chunk_len(rest)); + parser.process(StrTendril::from_slice(chunk)); + rest = after; + + let open = HandleCount::default(); + parser.tokenizer.sink.trace_handles(&open); + if open.count.get() > MAX_OPEN { + return Err(TooDeep); + } + } + let document = parser.finish().document; + if is_too_deep(&document) { + return Err(TooDeep); + } + Ok(document) +} + +/// The length of the next chunk of `html`: [`CHUNK_BYTES`], or fewer so that +/// it ends on a character boundary. +fn chunk_len(html: &str) -> usize { + if html.len() <= CHUNK_BYTES { + return html.len(); + } + (0..=CHUNK_BYTES) + .rev() + .find(|&at| html.is_char_boundary(at)) + .unwrap_or(html.len()) +} + +/// Whether a node of `document` sits deeper than [`MAX_DEPTH`], the contents +/// of a `