Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion crates/plugin-web/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -248,6 +255,7 @@ impl FetchError {
| FetchError::NoContentType { .. }
| FetchError::Timeout { .. }
| FetchError::TooLarge { .. }
| FetchError::TooDeep { .. }
| FetchError::BodyRead { .. }
| FetchError::Undecodable { .. }
| FetchError::Dns { .. }
Expand Down Expand Up @@ -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,
Expand All @@ -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(),
Expand Down
7 changes: 6 additions & 1 deletion crates/plugin-web/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 } => {
Expand Down
22 changes: 22 additions & 0 deletions crates/plugin-web/src/fetch/tests-body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions crates/plugin-web/src/fetch/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,11 @@ async fn padded() -> Html<String> {
))
}

/// A page with no article, nested far past what `htmd` can render.
async fn deep() -> Html<String> {
Html(format!("{}text", "<div>".repeat(100_000)))
}

async fn gzip_bomb() -> impl IntoResponse {
let raw = "A".repeat(200_000);
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
Expand Down Expand Up @@ -371,6 +376,7 @@ async fn spawn_server() -> (u16, Arc<AtomicUsize>) {
.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))
Expand Down
197 changes: 197 additions & 0 deletions crates/plugin-web/src/html_tree.rs
Original file line number Diff line number Diff line change
@@ -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<Handle, TooDeep> {
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 `<template>` included. It walks with a stack of its own rather than
/// recursion.
fn is_too_deep(document: &Handle) -> bool {
let mut stack = vec![(Rc::clone(document), 0)];
while let Some((node, depth)) = stack.pop() {
if depth > MAX_DEPTH {
return true;
}
stack.extend(
node.children
.borrow()
.iter()
.map(|child| (Rc::clone(child), depth + 1)),
);
if let NodeData::Element {
template_contents, ..
} = &node.data
&& let Some(contents) = template_contents.borrow().as_ref()
{
stack.push((Rc::clone(contents), depth + 1));
}
}
false
}

/// Counts the handles the parser holds: its open elements, and a few more.
#[derive(Default)]
struct HandleCount {
count: Cell<usize>,
handle: PhantomData<Handle>,
}

impl Tracer for HandleCount {
type Handle = Handle;

fn trace_handle(&self, _node: &Handle) {
self.count.set(self.count.get() + 1);
}
}

#[cfg(test)]
mod tests {
use html5ever::serialize::{SerializeOpts, serialize};
use markup5ever_rcdom::{Handle, SerializableHandle};

use super::{CHUNK_BYTES, MAX_DEPTH, TooDeep, parse};

fn to_html(document: Handle) -> String {
let mut out = Vec::new();
serialize(
&mut out,
&SerializableHandle::from(document),
SerializeOpts::default(),
)
.expect("the tree serializes");
String::from_utf8(out).expect("the serialized tree is UTF-8")
}

/// The `html` and `body` elements and the text sit on the path too, so
/// `MAX_DEPTH - 3` nested elements put the text at [`MAX_DEPTH`].
#[test]
fn a_page_at_the_limit_parses_and_one_level_more_is_too_deep() {
let page = |levels: usize| format!("{}text", "<div>".repeat(levels));
assert!(parse(&page(MAX_DEPTH - 3)).is_ok());
assert_eq!(parse(&page(MAX_DEPTH - 2)).err(), Some(TooDeep));
}

/// Each of these is at least 1 MiB of open tags. Parsing one in full
/// takes minutes for the block elements.
#[test]
fn a_huge_nest_of_any_kind_is_too_deep() {
for open in [
"<div>",
"<span>",
"<b>",
"<ul><li>",
"<table><tr><td>",
"<template>",
"<svg><g>",
] {
let html = open.repeat((1 << 20) / open.len() + 1);
assert_eq!(parse(&html).err(), Some(TooDeep), "{open}");
}
}

/// The elements are closed again before the parser's next check, so only
/// the check of the finished tree can see them.
#[test]
fn a_nest_that_opens_and_closes_within_one_chunk_is_too_deep() {
let html = format!("{}x{}", "<b>".repeat(500), "</b>".repeat(500));
assert!(html.len() < CHUNK_BYTES, "got: {}", html.len());
assert_eq!(parse(&html).err(), Some(TooDeep));
}

#[test]
fn many_elements_whose_end_tags_are_left_out_are_not_deep() {
let items = "<li>item".repeat(20_000);
let rows = "<tr><td>cell".repeat(20_000);
let paragraphs = "<p>text".repeat(20_000);
let html = format!("<ul>{items}</ul><table>{rows}</table>{paragraphs}");
assert!(parse(&html).is_ok());
}

/// The padding moves the chunk boundary across every byte of the text: a
/// multibyte character, a character reference, a tag, and a line ending.
#[test]
fn the_tree_does_not_depend_on_where_the_chunks_end() {
let tail = "é&amp;日本<a href=\"/x\">link</a>\r\n<!-- c --><pre>\r\ny</pre>".repeat(2);
for padding in CHUNK_BYTES - tail.len()..=CHUNK_BYTES {
let html = format!("{}{tail}", " x".repeat(padding).split_at(padding).0);
let whole = htmd::HtmlToMarkdown::new()
.html_to_tree(&html)
.expect("the page parses");
let chunked = parse(&html).expect("the page is shallow");
assert_eq!(to_html(chunked), to_html(whole), "padding: {padding}");
}
}
}
1 change: 1 addition & 0 deletions crates/plugin-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ mod config;
mod error;
mod fetch;
mod gateway;
mod html_tree;
#[cfg(test)]
mod mock_gateway;
mod redirect;
Expand Down
Loading
Loading