Skip to content
Closed
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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,15 @@ ipnet = "2.10"
# The fetch tool's rendering of a response. `mime` reads its content type,
# `encoding_rs` decodes its body under the charset it declares,
# `readabilityrs` picks the article out of an HTML page, and `htmd`
# renders HTML to markdown.
# renders HTML to markdown. `html5ever` and `markup5ever_rcdom` are the
# parser and tree `htmd` builds on, at its versions, so resolving a page's
# links before rendering adds no crate to the tree.
mime = "0.3"
encoding_rs = "0.8"
readabilityrs = "0.1"
htmd = "0.5"
html5ever = "0.38"
markup5ever_rcdom = "0.38"
# Derives the fetch tool's error types.
thiserror = "2"
# Derives the JSON forms of what the search tool reads and writes: its
Expand Down
6 changes: 5 additions & 1 deletion crates/plugin-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ url.workspace = true
ipnet.workspace = true
# The rendering of a response: `mime` reads its content type,
# `encoding_rs` decodes its body, `readabilityrs` picks the article out of
# an HTML page, and `htmd` renders HTML to markdown.
# an HTML page, and `htmd` renders HTML to markdown. `html5ever` and
# `markup5ever_rcdom` parse the page so its links can be made absolute
# before either renders it.
mime.workspace = true
encoding_rs.workspace = true
readabilityrs.workspace = true
htmd.workspace = true
html5ever.workspace = true
markup5ever_rcdom.workspace = true
# Derives the fetch tool's error types.
thiserror.workspace = true

Expand Down
2 changes: 1 addition & 1 deletion crates/plugin-web/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ impl FetchClient {
Ok(d) => d,
Err(e) => return soft_or_hard(&e),
};
let base_url = final_url.to_string();
let base_url = final_url.clone();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this making a copy of the buffer or just incrementing an Arc?

let rendering =
on_blocking_thread(move || extract_html(&decoded, Some(&base_url), raw));
let Some((markdown, extraction)) = rendering.await else {
Expand Down
263 changes: 258 additions & 5 deletions crates/plugin-web/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,18 @@
//! read, so a binary or absent type is refused without downloading it. HTML and
//! structured text are read all-or-nothing under the byte cap; genuinely flat
//! text is truncated at the cap. Decoding honors the declared charset, and HTML
//! is rendered to markdown with readability plus a whole-page fallback.
//! is rendered to markdown with readability plus a whole-page fallback, after
//! every relative link in it is resolved against the URL it was served from.

use std::rc::Rc;

use html5ever::serialize::{SerializeOpts, serialize};
use markup5ever_rcdom::{Handle, NodeData, SerializableHandle};
use readabilityrs::{Readability, ReadabilityOptions};
use url::Url;

use crate::error::{FetchError, SafeUrl};
use crate::url_policy::MAX_URL_CHARS;

/// The minimum extracted length below which the whole-page fallback fires.
const MIN_CONTENT_LEN: usize = 100;
Expand Down Expand Up @@ -137,7 +144,14 @@ pub(crate) fn decode_body(
/// than [`MIN_CONTENT_LEN`] characters, the whole document is converted instead
/// and the mode is [`Extraction::RawHtml`]. Rendering never fails: the worst
/// case is an empty string when even the whole-page conversion produces no text.
pub(crate) fn extract_html(html: &str, base_url: Option<&str>, raw: bool) -> (String, Extraction) {
///
/// Before either renders the page, each relative link and image source in it
/// is made absolute against `base_url`, the URL the page was served from, as
/// [`absolutize`] says, so a model can fetch what the markdown links to.
pub(crate) fn extract_html(html: &str, base_url: Option<&Url>, raw: bool) -> (String, Extraction) {
let absolute = base_url.and_then(|base| absolutize(html, base));
let html = absolute.as_deref().unwrap_or(html);

if raw {
return (htmd::convert(html).unwrap_or_default(), Extraction::RawHtml);
}
Expand All @@ -147,7 +161,7 @@ pub(crate) fn extract_html(html: &str, base_url: Option<&str>, raw: bool) -> (St
..ReadabilityOptions::default()
};

let article_markdown = Readability::new(html, base_url, Some(options))
let article_markdown = Readability::new(html, base_url.map(Url::as_str), Some(options))
.ok()
.and_then(Readability::parse)
.and_then(|article| {
Expand All @@ -169,6 +183,100 @@ pub(crate) fn extract_html(html: &str, base_url: Option<&str>, raw: bool) -> (St
)
}

/// Returns `html` with every relative `href` of an `a` and `src` of an `img`
/// resolved to an absolute `http` or `https` URL, or `None` when the page does
/// not parse back into text.
///
/// A reference resolves against the page's first `<base href>` when it names an
/// `http` or `https` URL, and against `page_url` otherwise, as a browser
/// resolves it. A reference that is already absolute, such as a `mailto:`
/// link, one that is only a fragment, which points into the page itself, and
/// one that does not resolve to `http` or `https` are left as written, as is
/// one whose absolute form [`check_url`](crate::url_policy::check_url) would
/// refuse as too long.
///
/// Resolving lengthens a link by up to the length of the base, which the page
/// chooses with `<base href>`, so a page of many short links could otherwise
/// grow far past the byte cap of its body. The links resolve in document order
/// until they have added as many bytes as the page holds, and the rest stay as
/// written, so the result is at most about twice the size of `html`.
fn absolutize(html: &str, page_url: &Url) -> Option<String> {
let document = htmd::HtmlToMarkdown::new().html_to_tree(html).ok()?;
let base = document_base(&document, page_url);
let mut budget = html.len();
for node in descendants(&document) {
let NodeData::Element { name, attrs, .. } = &node.data else {
continue;
};
let target = match &*name.local {
"a" => "href",
"img" => "src",
_ => continue,
};
for attr in attrs.borrow_mut().iter_mut() {
if &*attr.name.local == target
&& let Some(url) = resolve(&attr.value, &base)
&& let Some(rest) =
budget.checked_sub(url.as_str().len().saturating_sub(attr.value.len()))
{
budget = rest;
attr.value = url.as_str().into();
}
}
}
let mut out = Vec::new();
serialize(
&mut out,
&SerializableHandle::from(document),
SerializeOpts::default(),
)
.ok()?;
String::from_utf8(out).ok()
}

/// The URL a page's relative references resolve against: its first
/// `<base href>`, resolved against `page_url`, when that is `http` or `https`,
/// and `page_url` otherwise.
fn document_base(document: &Handle, page_url: &Url) -> Url {
descendants(document)
.find_map(|node| match &node.data {
NodeData::Element { name, attrs, .. } if &*name.local == "base" => attrs
.borrow()
.iter()
.find(|attr| &*attr.name.local == "href")
.map(|attr| attr.value.trim().to_owned()),
_ => None,
})
.and_then(|href| page_url.join(&href).ok())
.filter(|base| matches!(base.scheme(), "http" | "https"))
.unwrap_or_else(|| page_url.clone())
}

/// Resolves `reference` against `base`, or `None` when it is empty, already
/// absolute, only a fragment, or resolves to a scheme other than `http` or
/// `https` or to a URL over [`MAX_URL_CHARS`], which no fetch would take.
fn resolve(reference: &str, base: &Url) -> Option<Url> {
let reference = reference.trim();
if reference.is_empty() || reference.starts_with('#') || Url::parse(reference).is_ok() {
return None;
}
let url = base.join(reference).ok()?;
// A serialized URL is ASCII, so its byte length is its character count.
(matches!(url.scheme(), "http" | "https") && url.as_str().len() <= MAX_URL_CHARS).then_some(url)
}

/// Every node under `root`, in document order, walked with a stack rather than
/// recursion, so a page nested thousands of levels deep cannot overflow the
/// thread's stack.
fn descendants(root: &Handle) -> impl Iterator<Item = Handle> {
let mut stack = vec![Rc::clone(root)];
std::iter::from_fn(move || {
let node = stack.pop()?;
stack.extend(node.children.borrow().iter().rev().cloned());
Some(node)
})
}

/// Reads a response body into memory, truncating at a decompressed-byte cap.
///
/// Unlike [`read_body_capped`], a body over `max_bytes` is not refused: the read
Expand Down Expand Up @@ -263,7 +371,27 @@ pub(crate) fn truncate_to_chars(text: &str, max_chars: usize) -> (&str, bool) {

#[cfg(test)]
mod tests {
use super::extract_html;
use url::Url;

use super::{Extraction, absolutize, extract_html};
use crate::url_policy::MAX_URL_CHARS;

/// Parses `s` into a [`Url`], panicking with context on failure.
fn url(s: &str) -> Url {
Url::parse(s).expect("test url must parse")
}

/// A page whose article readability keeps, with `links` as its last
/// paragraph.
fn article(links: &str) -> String {
let prose = "<p>This paragraph is long enough for the extractor to treat it as \
real article content rather than navigation or boilerplate.</p>"
.repeat(4);
format!(
"<html><head><title>T</title></head><body><article><h1>Title</h1>\
{prose}<p>{links}</p></article></body></html>"
)
}

#[test]
fn extracts_article_body_and_drops_boilerplate() {
Expand All @@ -285,7 +413,8 @@ mod tests {
</html>
"#;

let (markdown, _mode) = extract_html(html, Some("https://example.com/article"), false);
let (markdown, _mode) =
extract_html(html, Some(&url("https://example.com/article")), false);

assert!(
markdown.contains("first substantial paragraph"),
Expand All @@ -312,4 +441,128 @@ mod tests {
"fallback should preserve the page text, got: {markdown}"
);
}

#[test]
fn an_article_links_absolutely_to_what_it_names() {
let html = article(
r#"See <a href="/learn">learn</a>, <a href="guide/intro.html">intro</a>, and <img src="../img/a.png" alt="a">."#,
);

let (markdown, mode) = extract_html(
&html,
Some(&url("https://www.rust-lang.org/tools/install")),
false,
);

assert_eq!(mode, Extraction::Readability, "got: {markdown}");
for link in [
"(https://www.rust-lang.org/learn)",
"(https://www.rust-lang.org/tools/guide/intro.html)",
"(https://www.rust-lang.org/img/a.png)",
] {
assert!(markdown.contains(link), "expected {link} in: {markdown}");
}
}

#[test]
fn a_raw_page_links_absolutely_to_what_it_names() {
let html = r#"<nav><a href="/docs">Docs</a> <a href="//cdn.example.org/x">CDN</a></nav>"#;

let (markdown, mode) = extract_html(html, Some(&url("https://example.com/a/b")), true);

assert_eq!(mode, Extraction::RawHtml);
assert!(
markdown.contains("(https://example.com/docs)"),
"got: {markdown}"
);
assert!(
markdown.contains("(https://cdn.example.org/x)"),
"got: {markdown}"
);
}

#[test]
fn a_base_element_moves_where_links_resolve() {
let html = r#"<head><base href="https://mirror.example.net/v2/"></head><body><a href="page">Page</a></body>"#;

let (markdown, _mode) = extract_html(html, Some(&url("https://example.com/a/b")), true);

assert!(
markdown.contains("(https://mirror.example.net/v2/page)"),
"got: {markdown}"
);
}

#[test]
fn a_base_element_that_is_not_http_is_ignored() {
let html =
r#"<head><base href="ftp://example.net/"></head><body><a href="page">Page</a></body>"#;

let (markdown, _mode) = extract_html(html, Some(&url("https://example.com/a/b")), true);

assert!(
markdown.contains("(https://example.com/a/page)"),
"got: {markdown}"
);
}

#[test]
fn links_that_need_no_resolving_stay_as_written() {
let html = r##"<p><a href="#top">Top</a> <a href="mailto:a@example.com">Mail</a> <a href="https://other.example/x">Other</a> <a href="javascript:void(0)">Js</a></p>"##;

let (markdown, _mode) = extract_html(html, Some(&url("https://example.com/a")), true);

for link in [
"(#top)",
"(mailto:a@example.com)",
"(https://other.example/x)",
"(javascript:void",
] {
assert!(markdown.contains(link), "expected {link} in: {markdown}");
}
}

#[test]
fn without_a_base_url_links_stay_as_written() {
let html = r#"<p><a href="/docs">Docs</a></p>"#;

let (markdown, _mode) = extract_html(html, None, true);

assert!(markdown.contains("(/docs)"), "got: {markdown}");
}

#[test]
fn a_link_too_long_to_fetch_stays_as_written() {
let base = format!("https://example.com/{}/", "a".repeat(MAX_URL_CHARS));
let html =
format!(r#"<head><base href="{base}"></head><body><a href="page">Page</a></body>"#);

let (markdown, _mode) = extract_html(&html, Some(&url("https://example.com/")), true);

assert!(markdown.contains("(page)"), "got: {markdown}");
}

#[test]
fn resolving_at_most_doubles_the_page() {
let base = format!("https://example.com/{}/", "a".repeat(1_900));
let links = r#"<a href="b">x</a>"#.repeat(1_000);
let html = format!(r#"<html><head><base href="{base}"></head><body>{links}</body></html>"#);

let out = absolutize(&html, &url("https://example.com/")).expect("the page serializes");

assert!(
out.len() <= 2 * html.len(),
"{} bytes resolved from {}",
out.len(),
html.len()
);
assert!(
out.contains(&format!(r#"href="{base}b""#)),
"the first links resolve"
);
assert!(
out.ends_with(r#"<a href="b">x</a></body></html>"#),
"the last link stays as written"
);
}
}
Loading