aKode fase 3: provider locali, chiavi per provider, modelli dal server, SearXNG

- Provider: rimossi openai, Bedrock e GCP integrati e ogni fallback a OpenAI;
  restano ollama, lmstudio e i provider personalizzati. Senza provider, exec e
  TUI mostrano come configurarlo.
- Chiave per provider: api_key = "keyring", provider_api_key_store =
  auto|keyring|file (fallback su file 0600 / ACL Windows); `codex login
  --provider <id> --with-api-key`, `logout --provider`; login status e doctor
  mostrano dove sta la chiave senza rivelarla.
- Modelli letti da GET {base_url}/models; contesto da config, poi dal server
  (/props, meta.n_ctx), poi 32768; apply_patch come tool function; niente tool
  ospitati; niente piu' avviso "metadata not found".
- Unione dei soli messaggi system/developer iniziali in un unico system;
  quelli successivi restano al loro posto come user (cache del server
  preservata: turno N prefisso esatto del turno N+1).
- Modelli ausiliari (memorie, guardian-v2) = modello di sessione se il
  preferito gpt-* non e' nel catalogo.
- Ricerca web: crate web-tools, backend SearXNG con web_search e web_fetch
  (protezione SSRF); senza backend nessuno strumento web.
- Skill: rimossa openai-docs; skill-installer punta a git.difonzo.net.
- apply_patch accetta gli header @@ -a,b +c,d @@ dei diff unificati.
- Rimossi resti: request_plugin_install, AppsInstructions, --cyber-access-program,
  URL updater/realtime predefiniti.
- Fix: importazione sessioni con provider vuoto.
- Istruzioni di sistema invariate. Test: cancellati solo quelli del codice
  rimosso, test di sicurezza adattati; restano solo fallimenti d'ambiente.
- Prova reale su imeAI + SearXNG: risposta, modifica file, web_search,
  cache riusata, connessioni solo verso .25 e .57.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 02:11:45 +01:00
parent 9e33707b8e
commit e39aae0085
545 changed files with 9742 additions and 24503 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "web-tools",
crate_name = "codex_web_tools",
)

View File

@@ -0,0 +1,28 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-web-tools"
version.workspace = true
[lib]
name = "codex_web_tools"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
encoding_rs = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["net", "time"] }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,28 @@
use std::time::Duration;
use crate::error::Result;
use crate::error::request_error;
/// Reads at most `cap` bytes of the response body, streaming chunk by chunk
/// so an oversized body is never buffered. Returns the bytes and whether the
/// body was cut short.
pub(crate) async fn read_capped(
response: &mut reqwest::Response,
cap: usize,
timeout: Duration,
) -> Result<(Vec<u8>, bool)> {
let mut buf = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|err| request_error(err, timeout))?
{
let remaining = cap.saturating_sub(buf.len());
if chunk.len() > remaining {
buf.extend_from_slice(&chunk[..remaining]);
return Ok((buf, true));
}
buf.extend_from_slice(&chunk);
}
Ok((buf, false))
}

View File

@@ -0,0 +1,72 @@
use std::net::IpAddr;
use std::time::Duration;
/// Errors returned by the web tools. Messages are written to be shown to
/// the model as-is.
#[derive(Debug, thiserror::Error)]
pub enum WebToolsError {
#[error("invalid URL: {0}")]
InvalidUrl(String),
#[error("unsupported URL scheme `{0}`: only http and https are allowed")]
UnsupportedScheme(String),
#[error("URLs with embedded credentials (user:password@) are not allowed")]
CredentialsInUrl,
#[error("URL has no host")]
MissingHost,
#[error(
"access to `{host}` ({addr}) is blocked: loopback, private, link-local and reserved addresses are not allowed"
)]
BlockedAddress { host: String, addr: IpAddr },
#[error("could not resolve host `{host}`: {message}")]
Dns { host: String, message: String },
#[error("too many redirects (limit is {0})")]
TooManyRedirects(usize),
#[error("redirect response without a valid Location header")]
InvalidRedirect,
#[error("request timed out after {0:?}")]
Timeout(Duration),
#[error("HTTP {status}: {message}")]
HttpStatus { status: u16, message: String },
#[error("response exceeds the {0}-byte limit")]
ResponseTooLarge(usize),
#[error("unsupported content type `{0}`: only HTML, text and JSON can be fetched")]
UnsupportedContentType(String),
#[error("invalid response: {0}")]
InvalidResponse(String),
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("HTTP request failed: {0}")]
Request(String),
}
pub type Result<T> = std::result::Result<T, WebToolsError>;
/// Converts a reqwest error into a [`WebToolsError`], keeping the source
/// chain in the message (reqwest's top-level message is often vague).
pub(crate) fn request_error(err: reqwest::Error, timeout: Duration) -> WebToolsError {
if err.is_timeout() {
return WebToolsError::Timeout(timeout);
}
let mut message = err.to_string();
let mut source = std::error::Error::source(&err);
while let Some(cause) = source {
message.push_str(": ");
message.push_str(&cause.to_string());
source = cause.source();
}
WebToolsError::Request(message)
}

View File

@@ -0,0 +1,421 @@
//! SSRF-hardened page fetcher.
use std::fmt;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use reqwest::StatusCode;
use reqwest::header::ACCEPT;
use reqwest::header::CONTENT_TYPE;
use reqwest::header::LOCATION;
use url::Host;
use url::Url;
use crate::body::read_capped;
use crate::error::Result;
use crate::error::WebToolsError;
use crate::error::request_error;
use crate::html::html_to_text;
use crate::net::HostResolver;
use crate::net::PinnedResolver;
use crate::net::SystemResolver;
use crate::net::is_addr_allowed;
use crate::net::is_localhost_name;
pub const DEFAULT_FETCH_USER_AGENT: &str = "aKode-web-fetch/0.1";
const ACCEPT_VALUE: &str =
"text/html,application/xhtml+xml,text/plain;q=0.9,application/json;q=0.9,*/*;q=0.5";
/// Options for [`WebFetcher`].
#[derive(Clone)]
pub struct WebFetchOptions {
/// Total time budget for the whole fetch, redirects included.
pub timeout: Duration,
/// Maximum number of redirects followed (each hop is re-validated).
pub max_redirects: usize,
/// Maximum number of body bytes downloaded; the rest is not read.
pub max_download_bytes: usize,
/// Maximum size in bytes of the returned text (cut on a char boundary).
pub max_text_bytes: usize,
pub user_agent: String,
/// Exact socket addresses (IP and port) that may be contacted even
/// though they are private/loopback. Empty by default; meant for tests.
pub allowed_private_addrs: Vec<SocketAddr>,
/// Resolver used to look up host names before vetting them.
pub resolver: Arc<dyn HostResolver>,
}
impl Default for WebFetchOptions {
fn default() -> Self {
Self {
timeout: Duration::from_secs(20),
max_redirects: 5,
max_download_bytes: 2 * 1024 * 1024,
max_text_bytes: 100 * 1024,
user_agent: DEFAULT_FETCH_USER_AGENT.to_string(),
allowed_private_addrs: Vec::new(),
resolver: Arc::new(SystemResolver),
}
}
}
impl fmt::Debug for WebFetchOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WebFetchOptions")
.field("timeout", &self.timeout)
.field("max_redirects", &self.max_redirects)
.field("max_download_bytes", &self.max_download_bytes)
.field("max_text_bytes", &self.max_text_bytes)
.field("user_agent", &self.user_agent)
.field("allowed_private_addrs", &self.allowed_private_addrs)
.finish_non_exhaustive()
}
}
/// A fetched page converted to text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchedPage {
/// URL after following redirects.
pub final_url: Url,
pub status: u16,
pub content_type: Option<String>,
pub title: Option<String>,
pub text: String,
/// True when the download or the text was cut at its size limit.
pub truncated: bool,
}
#[derive(Debug, Clone)]
pub struct WebFetcher {
opts: WebFetchOptions,
}
enum BodyKind {
Html,
Text,
/// No usable content type: decide by sniffing the bytes.
Unknown,
}
impl WebFetcher {
pub fn new(opts: WebFetchOptions) -> Self {
Self { opts }
}
pub fn options(&self) -> &WebFetchOptions {
&self.opts
}
/// Fetches `url` (http/https only) and returns its content as text.
pub async fn fetch(&self, url: &str) -> Result<FetchedPage> {
let url =
Url::parse(url.trim()).map_err(|err| WebToolsError::InvalidUrl(err.to_string()))?;
let timeout = self.opts.timeout;
tokio::time::timeout(timeout, self.fetch_inner(url))
.await
.unwrap_or(Err(WebToolsError::Timeout(timeout)))
}
async fn fetch_inner(&self, mut url: Url) -> Result<FetchedPage> {
let mut redirects = 0;
loop {
url.set_fragment(None);
let pinned = self.vet_url(&url).await?;
let client = self.build_client(pinned)?;
let mut response = client
.get(url.clone())
.header(ACCEPT, ACCEPT_VALUE)
.send()
.await
.map_err(|err| request_error(err, self.opts.timeout))?;
let status = response.status();
if is_followed_redirect(status) {
if redirects >= self.opts.max_redirects {
return Err(WebToolsError::TooManyRedirects(self.opts.max_redirects));
}
let location = response
.headers()
.get(LOCATION)
.and_then(|v| v.to_str().ok())
.ok_or(WebToolsError::InvalidRedirect)?;
let next = url
.join(location)
.map_err(|_| WebToolsError::InvalidRedirect)?;
tracing::debug!(from = %url, to = %next, "web fetch redirect");
url = next;
redirects += 1;
continue;
}
return self.read_page(url, &mut response).await;
}
}
/// Validates scheme, credentials and destination addresses. For a host
/// name, returns the vetted addresses the connection must be pinned to.
async fn vet_url(&self, url: &Url) -> Result<Option<(String, Vec<SocketAddr>)>> {
match url.scheme() {
"http" | "https" => {}
other => return Err(WebToolsError::UnsupportedScheme(other.to_string())),
}
if !url.username().is_empty() || url.password().is_some() {
return Err(WebToolsError::CredentialsInUrl);
}
let port = url
.port_or_known_default()
.ok_or_else(|| WebToolsError::InvalidUrl("missing port".to_string()))?;
let allowlist = &self.opts.allowed_private_addrs;
let check = |host: &str, addr: SocketAddr| {
if is_addr_allowed(addr, allowlist) {
Ok(())
} else {
Err(WebToolsError::BlockedAddress {
host: host.to_string(),
addr: addr.ip(),
})
}
};
match url.host().ok_or(WebToolsError::MissingHost)? {
Host::Ipv4(ip) => {
check(&ip.to_string(), SocketAddr::new(IpAddr::V4(ip), port))?;
Ok(None)
}
Host::Ipv6(ip) => {
check(&ip.to_string(), SocketAddr::new(IpAddr::V6(ip), port))?;
Ok(None)
}
Host::Domain(domain) => {
let addrs = if is_localhost_name(domain) {
vec![
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), port),
]
} else {
self.opts
.resolver
.resolve(domain, port)
.await
.map_err(|err| WebToolsError::Dns {
host: domain.to_string(),
message: err.to_string(),
})?
};
if addrs.is_empty() {
return Err(WebToolsError::Dns {
host: domain.to_string(),
message: "no addresses found".to_string(),
});
}
if is_localhost_name(domain) {
// Only the allowlisted loopback addresses survive.
let allowed: Vec<SocketAddr> = addrs
.iter()
.copied()
.filter(|a| is_addr_allowed(*a, allowlist))
.collect();
if allowed.is_empty() {
return Err(WebToolsError::BlockedAddress {
host: domain.to_string(),
addr: addrs[0].ip(),
});
}
return Ok(Some((domain.to_string(), allowed)));
}
// Any blocked answer rejects the host outright.
for addr in &addrs {
check(domain, *addr)?;
}
Ok(Some((domain.to_string(), addrs)))
}
}
}
fn build_client(&self, pinned: Option<(String, Vec<SocketAddr>)>) -> Result<reqwest::Client> {
let (host, addrs) = pinned.unwrap_or_default();
reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.no_proxy()
.timeout(self.opts.timeout)
.user_agent(self.opts.user_agent.as_str())
// Every lookup goes through the vetted addresses; the system
// resolver is never used, so DNS rebinding cannot redirect us.
.dns_resolver(PinnedResolver::new(host, addrs))
.build()
.map_err(|err| request_error(err, self.opts.timeout))
}
async fn read_page(
&self,
final_url: Url,
response: &mut reqwest::Response,
) -> Result<FetchedPage> {
let status = response.status().as_u16();
let content_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty());
let mime = content_type
.as_deref()
.map(|ct| {
ct.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
})
.unwrap_or_default();
let mut kind = classify_mime(&mime)?;
let (bytes, download_truncated) =
read_capped(response, self.opts.max_download_bytes, self.opts.timeout).await?;
if matches!(kind, BodyKind::Unknown) {
kind = sniff(&bytes).ok_or_else(|| {
WebToolsError::UnsupportedContentType(if mime.is_empty() {
"unknown (binary data)".to_string()
} else {
mime.clone()
})
})?;
}
let is_html = matches!(kind, BodyKind::Html);
let charset = content_type.as_deref().and_then(charset_param).or_else(|| {
if is_html {
sniff_meta_charset(&bytes)
} else {
None
}
});
let decoded = decode_bytes(&bytes, charset.as_deref());
let (title, mut text) = if is_html {
let extracted = html_to_text(&decoded);
(extracted.title, extracted.text)
} else {
(None, decoded)
};
let text_truncated = truncate_on_char_boundary(&mut text, self.opts.max_text_bytes);
Ok(FetchedPage {
final_url,
status,
content_type,
title,
text,
truncated: download_truncated || text_truncated,
})
}
}
fn is_followed_redirect(status: StatusCode) -> bool {
matches!(
status,
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::SEE_OTHER
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT
)
}
fn classify_mime(mime: &str) -> Result<BodyKind> {
let kind = match mime {
"" | "application/octet-stream" => BodyKind::Unknown,
"text/html" | "application/xhtml+xml" => BodyKind::Html,
m if m.starts_with("text/") => BodyKind::Text,
"application/json"
| "application/xml"
| "application/javascript"
| "application/ecmascript"
| "application/x-javascript"
| "application/x-ndjson"
| "application/yaml"
| "application/x-yaml"
| "application/toml"
| "application/x-sh"
| "application/sql"
| "application/graphql" => BodyKind::Text,
m if m.ends_with("+json") || m.ends_with("+xml") => BodyKind::Text,
other => return Err(WebToolsError::UnsupportedContentType(other.to_string())),
};
Ok(kind)
}
/// Guesses the kind of an untyped body. Returns `None` for binary data.
fn sniff(bytes: &[u8]) -> Option<BodyKind> {
let head = &bytes[..bytes.len().min(1024)];
if head.contains(&0) {
return None;
}
let valid_utf8 = match std::str::from_utf8(bytes) {
Ok(_) => true,
// Tolerate a multi-byte sequence cut by the download cap.
Err(err) => err.error_len().is_none(),
};
if !valid_utf8 {
return None;
}
let start = String::from_utf8_lossy(head)
.trim_start()
.to_ascii_lowercase();
if start.starts_with("<!doctype html") || start.starts_with("<html") {
Some(BodyKind::Html)
} else {
Some(BodyKind::Text)
}
}
fn charset_param(content_type: &str) -> Option<String> {
content_type.split(';').skip(1).find_map(|param| {
let (key, value) = param.split_once('=')?;
key.trim()
.eq_ignore_ascii_case("charset")
.then(|| value.trim().trim_matches(['"', '\'']).to_string())
})
}
/// Looks for `charset=` in a `<meta>` tag near the start of an HTML body.
fn sniff_meta_charset(bytes: &[u8]) -> Option<String> {
let head = String::from_utf8_lossy(&bytes[..bytes.len().min(2048)]).to_ascii_lowercase();
let meta = head.find("<meta")?;
let pos = head[meta..].find("charset=")? + meta + "charset=".len();
let value: String = head[pos..]
.trim_start_matches(['"', '\''])
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'))
.collect();
(!value.is_empty()).then_some(value)
}
/// Decodes `bytes` using the charset label (UTF-8 by default), lossily. A
/// byte-order mark takes precedence over the label.
fn decode_bytes(bytes: &[u8], charset: Option<&str>) -> String {
let encoding = charset
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
.unwrap_or(encoding_rs::UTF_8);
let (text, _, _) = encoding.decode(bytes);
text.into_owned()
}
/// Truncates `s` to at most `max` bytes on a char boundary. Returns whether
/// anything was removed.
pub(crate) fn truncate_on_char_boundary(s: &mut String, max: usize) -> bool {
if s.len() <= max {
return false;
}
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
s.truncate(end);
true
}
#[cfg(test)]
#[path = "fetch_tests.rs"]
mod tests;

View File

@@ -0,0 +1,489 @@
use std::collections::HashMap;
use std::io;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::net::ResolveFuture;
/// Fetcher that may reach exactly the given mock server(s), nothing else private.
fn fetcher_for(servers: &[&MockServer]) -> WebFetcher {
WebFetcher::new(WebFetchOptions {
allowed_private_addrs: servers.iter().map(|s| *s.address()).collect(),
..WebFetchOptions::default()
})
}
/// Resolver answering from a fixed table, never touching real DNS.
struct StaticResolver(HashMap<String, Vec<IpAddr>>);
impl HostResolver for StaticResolver {
fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a> {
let answer = self
.0
.get(host)
.map(|ips| ips.iter().map(|ip| SocketAddr::new(*ip, port)).collect())
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "unknown host"));
Box::pin(async move { answer })
}
}
fn static_resolver(entries: &[(&str, &[&str])]) -> Arc<dyn HostResolver> {
Arc::new(StaticResolver(
entries
.iter()
.map(|(host, ips)| {
(
(*host).to_string(),
ips.iter().map(|ip| ip.parse().unwrap()).collect(),
)
})
.collect(),
))
}
async fn serve(server: &MockServer, route: &str, response: ResponseTemplate) {
Mock::given(method("GET"))
.and(path(route))
.respond_with(response)
.mount(server)
.await;
}
#[tokio::test]
async fn fetches_html_as_text() {
let server = MockServer::start().await;
let html = "<html><head><title>Mock &amp; Page</title><script>evil()</script></head>\
<body><h1>Hello</h1><p>World &lt;3</p></body></html>";
serve(
&server,
"/page",
ResponseTemplate::new(200).set_body_raw(html, "text/html; charset=utf-8"),
)
.await;
let page = fetcher_for(&[&server])
.fetch(&format!("{}/page#frag", server.uri()))
.await
.unwrap();
assert_eq!(
page,
FetchedPage {
final_url: Url::parse(&format!("{}/page", server.uri())).unwrap(),
status: 200,
content_type: Some("text/html; charset=utf-8".to_string()),
title: Some("Mock & Page".to_string()),
text: "Hello\n\nWorld <3".to_string(),
truncated: false,
}
);
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests[0].headers.get("user-agent").unwrap(),
DEFAULT_FETCH_USER_AGENT
);
}
#[tokio::test]
async fn returns_plain_text_and_json_as_is() {
let server = MockServer::start().await;
serve(
&server,
"/t",
ResponseTemplate::new(200).set_body_raw("a <b>\n c", "text/plain"),
)
.await;
serve(
&server,
"/j",
ResponseTemplate::new(200).set_body_raw(r#"{"k": [1, 2]}"#, "application/json"),
)
.await;
let fetcher = fetcher_for(&[&server]);
let text = fetcher.fetch(&format!("{}/t", server.uri())).await.unwrap();
assert_eq!(text.text, "a <b>\n c");
assert_eq!(text.title, None);
let json = fetcher.fetch(&format!("{}/j", server.uri())).await.unwrap();
assert_eq!(json.text, r#"{"k": [1, 2]}"#);
}
#[tokio::test]
async fn decodes_declared_charset_and_lossy_utf8() {
let server = MockServer::start().await;
serve(
&server,
"/latin1",
ResponseTemplate::new(200)
.set_body_raw(b"caf\xe9".to_vec(), "text/plain; charset=ISO-8859-1"),
)
.await;
serve(
&server,
"/bad",
ResponseTemplate::new(200).set_body_raw(b"ok \xff end".to_vec(), "text/plain"),
)
.await;
serve(
&server,
"/meta",
ResponseTemplate::new(200).set_body_raw(
b"<html><head><meta charset=\"windows-1252\"></head><body>na\xefve</body></html>"
.to_vec(),
"text/html",
),
)
.await;
let fetcher = fetcher_for(&[&server]);
let latin1 = fetcher
.fetch(&format!("{}/latin1", server.uri()))
.await
.unwrap();
assert_eq!(latin1.text, "café");
let bad = fetcher
.fetch(&format!("{}/bad", server.uri()))
.await
.unwrap();
assert_eq!(bad.text, "ok \u{fffd} end");
let meta = fetcher
.fetch(&format!("{}/meta", server.uri()))
.await
.unwrap();
assert_eq!(meta.text, "naïve");
}
#[tokio::test]
async fn rejects_binary_content() {
let server = MockServer::start().await;
serve(
&server,
"/img",
ResponseTemplate::new(200).set_body_raw(vec![0x89, b'P', b'N', b'G', 0, 0], "image/png"),
)
.await;
serve(
&server,
"/bin",
ResponseTemplate::new(200).set_body_raw(vec![1, 2, 0, 3], "application/octet-stream"),
)
.await;
let fetcher = fetcher_for(&[&server]);
let err = fetcher
.fetch(&format!("{}/img", server.uri()))
.await
.unwrap_err();
assert!(
matches!(&err, WebToolsError::UnsupportedContentType(ct) if ct == "image/png"),
"{err:?}"
);
let err = fetcher
.fetch(&format!("{}/bin", server.uri()))
.await
.unwrap_err();
assert!(
matches!(err, WebToolsError::UnsupportedContentType(_)),
"{err:?}"
);
}
#[tokio::test]
async fn caps_text_size_on_char_boundary() {
let server = MockServer::start().await;
// 3-byte chars so a 100 KiB cut lands inside a character.
let body = "€".repeat(50_000);
serve(
&server,
"/big",
ResponseTemplate::new(200).set_body_raw(body, "text/plain; charset=utf-8"),
)
.await;
let page = fetcher_for(&[&server])
.fetch(&format!("{}/big", server.uri()))
.await
.unwrap();
assert!(page.truncated);
assert_eq!(page.text.len(), 102_399);
assert!(page.text.chars().all(|c| c == '€'));
}
#[tokio::test]
async fn caps_download_size() {
let server = MockServer::start().await;
serve(
&server,
"/huge",
ResponseTemplate::new(200).set_body_raw("x".repeat(500_000), "text/plain"),
)
.await;
let fetcher = WebFetcher::new(WebFetchOptions {
max_download_bytes: 1000,
allowed_private_addrs: vec![*server.address()],
..WebFetchOptions::default()
});
let page = fetcher
.fetch(&format!("{}/huge", server.uri()))
.await
.unwrap();
assert!(page.truncated);
assert_eq!(page.text.len(), 1000);
}
#[tokio::test]
async fn times_out() {
let server = MockServer::start().await;
serve(
&server,
"/slow",
ResponseTemplate::new(200)
.set_body_string("late")
.set_delay(Duration::from_secs(5)),
)
.await;
let fetcher = WebFetcher::new(WebFetchOptions {
timeout: Duration::from_millis(200),
allowed_private_addrs: vec![*server.address()],
..WebFetchOptions::default()
});
let err = fetcher
.fetch(&format!("{}/slow", server.uri()))
.await
.unwrap_err();
assert!(matches!(err, WebToolsError::Timeout(_)), "{err:?}");
}
#[tokio::test]
async fn follows_redirects_and_revalidates() {
let server = MockServer::start().await;
serve(
&server,
"/a",
ResponseTemplate::new(302).insert_header("location", "/b"),
)
.await;
serve(
&server,
"/b",
ResponseTemplate::new(301).insert_header("location", "c"),
)
.await;
serve(
&server,
"/c",
ResponseTemplate::new(200).set_body_raw("done", "text/plain"),
)
.await;
let page = fetcher_for(&[&server])
.fetch(&format!("{}/a", server.uri()))
.await
.unwrap();
assert_eq!(page.text, "done");
assert_eq!(page.final_url.path(), "/c");
}
#[tokio::test]
async fn enforces_redirect_limit() {
let server = MockServer::start().await;
serve(
&server,
"/loop",
ResponseTemplate::new(307).insert_header("location", "/loop"),
)
.await;
let err = fetcher_for(&[&server])
.fetch(&format!("{}/loop", server.uri()))
.await
.unwrap_err();
assert!(matches!(err, WebToolsError::TooManyRedirects(5)), "{err:?}");
// The first request plus five followed redirects.
assert_eq!(server.received_requests().await.unwrap().len(), 6);
}
#[tokio::test]
async fn blocks_redirect_to_private_addresses() {
let public = MockServer::start().await;
let private = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200).set_body_string("secret"))
.expect(0)
.mount(&private)
.await;
let targets = [
format!("http://127.0.0.1:{}/", private.address().port()),
format!("http://localhost:{}/", private.address().port()),
"http://169.254.169.254/latest/meta-data/".to_string(),
"http://10.0.0.1/".to_string(),
"http://[::1]/".to_string(),
"file:///etc/passwd".to_string(),
];
for (i, target) in targets.iter().enumerate() {
serve(
&public,
&format!("/r{i}"),
ResponseTemplate::new(302).insert_header("location", target.as_str()),
)
.await;
}
// Only the first hop's exact socket address is allowlisted.
let fetcher = fetcher_for(&[&public]);
for (i, target) in targets.iter().enumerate() {
let err = fetcher
.fetch(&format!("{}/r{i}", public.uri()))
.await
.unwrap_err();
let ok = if target.starts_with("file:") {
matches!(err, WebToolsError::UnsupportedScheme(_))
} else {
matches!(err, WebToolsError::BlockedAddress { .. })
};
assert!(ok, "{target}: {err:?}");
}
}
#[tokio::test]
async fn blocks_private_destinations_by_default() {
let fetcher = WebFetcher::new(WebFetchOptions {
resolver: static_resolver(&[]),
..WebFetchOptions::default()
});
let cases = [
("http://127.0.0.1/", "127.0.0.1"),
("http://localhost/", "127.0.0.1"),
("http://LocalHost.:8080/", "127.0.0.1"),
("http://foo.localhost/", "127.0.0.1"),
("http://10.1.2.3/", "10.1.2.3"),
("http://172.16.5.4/", "172.16.5.4"),
("http://192.168.1.1/", "192.168.1.1"),
("http://100.64.0.1/", "100.64.0.1"),
(
"http://169.254.169.254/latest/meta-data/",
"169.254.169.254",
),
("http://0.0.0.0/", "0.0.0.0"),
("http://255.255.255.255/", "255.255.255.255"),
("http://224.0.0.1/", "224.0.0.1"),
("http://[::1]/", "::1"),
("http://[::]/", "::"),
("http://[::ffff:127.0.0.1]/", "::ffff:127.0.0.1"),
("http://[::ffff:a9fe:a9fe]/", "::ffff:169.254.169.254"),
("http://[fd00::1]/", "fd00::1"),
("http://[fe80::1]/", "fe80::1"),
("http://[64:ff9b::7f00:1]/", "64:ff9b::7f00:1"),
// The url crate normalizes these numeric forms to 127.0.0.1.
("http://2130706433/", "127.0.0.1"),
("http://0x7f.1/", "127.0.0.1"),
("http://0177.0.0.1/", "127.0.0.1"),
("http://127.1/", "127.0.0.1"),
("https://017700000001/", "127.0.0.1"),
];
for (url, ip) in cases {
let err = fetcher.fetch(url).await.unwrap_err();
match err {
WebToolsError::BlockedAddress { addr, .. } => {
assert_eq!(addr, ip.parse::<IpAddr>().unwrap(), "{url}");
}
other => panic!("{url}: expected BlockedAddress, got {other:?}"),
}
}
}
#[test]
fn url_crate_normalizes_numeric_hosts() {
for raw in ["http://2130706433/", "http://0x7f.1/", "http://0177.0.0.1/"] {
let url = Url::parse(raw).unwrap();
assert_eq!(url.host(), Some(Host::Ipv4(Ipv4Addr::LOCALHOST)), "{raw}");
}
}
#[tokio::test]
async fn blocks_host_names_resolving_to_private_addresses() {
let fetcher = WebFetcher::new(WebFetchOptions {
resolver: static_resolver(&[
("internal.example", &["10.0.0.5"]),
("mixed.example", &["93.184.216.34", "192.168.0.10"]),
("v6.example", &["::ffff:127.0.0.1"]),
]),
..WebFetchOptions::default()
});
for (url, ip) in [
("http://internal.example/", "10.0.0.5"),
("http://mixed.example/", "192.168.0.10"),
("https://v6.example/", "::ffff:127.0.0.1"),
] {
match fetcher.fetch(url).await.unwrap_err() {
WebToolsError::BlockedAddress { addr, .. } => {
assert_eq!(addr, ip.parse::<IpAddr>().unwrap(), "{url}");
}
other => panic!("{url}: expected BlockedAddress, got {other:?}"),
}
}
let err = fetcher.fetch("http://unknown.example/").await.unwrap_err();
assert!(matches!(err, WebToolsError::Dns { .. }), "{err:?}");
}
#[tokio::test]
async fn connects_to_the_vetted_address_only() {
// A made-up host name resolved by the injected resolver to the mock
// server: the request must reach it without consulting real DNS.
let server = MockServer::start().await;
serve(
&server,
"/",
ResponseTemplate::new(200).set_body_raw("pinned", "text/plain"),
)
.await;
let fetcher = WebFetcher::new(WebFetchOptions {
resolver: static_resolver(&[("pinned.example", &["127.0.0.1"])]),
allowed_private_addrs: vec![*server.address()],
..WebFetchOptions::default()
});
let url = format!("http://pinned.example:{}/", server.address().port());
let page = fetcher.fetch(&url).await.unwrap();
assert_eq!(page.text, "pinned");
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests[0].headers.get("host").unwrap(),
format!("pinned.example:{}", server.address().port()).as_str()
);
}
#[tokio::test]
async fn rejects_bad_urls() {
let fetcher = WebFetcher::new(WebFetchOptions {
resolver: static_resolver(&[]),
..WebFetchOptions::default()
});
for url in [
"ftp://example.com/",
"file:///etc/passwd",
"gopher://example.com/",
"data:text/plain,hi",
"javascript:alert(1)",
] {
let err = fetcher.fetch(url).await.unwrap_err();
assert!(
matches!(err, WebToolsError::UnsupportedScheme(_)),
"{url}: {err:?}"
);
}
for url in ["http://user:pass@example.com/", "http://user@example.com/"] {
let err = fetcher.fetch(url).await.unwrap_err();
assert!(
matches!(err, WebToolsError::CredentialsInUrl),
"{url}: {err:?}"
);
}
let err = fetcher.fetch("not a url").await.unwrap_err();
assert!(matches!(err, WebToolsError::InvalidUrl(_)), "{err:?}");
}
#[test]
fn truncates_on_char_boundary() {
let mut s = "aé".to_string();
assert!(truncate_on_char_boundary(&mut s, 2));
assert_eq!(s, "a");
let mut s = "abc".to_string();
assert!(!truncate_on_char_boundary(&mut s, 3));
}

View File

@@ -0,0 +1,98 @@
//! Compact text renderings of tool results for the model.
use crate::fetch::FetchedPage;
use crate::search::SearchResult;
/// Formats search results as a numbered list:
///
/// ```text
/// 1. Title
/// https://example.com/
/// Snippet text
/// ```
pub fn format_search_results(results: &[SearchResult]) -> String {
if results.is_empty() {
return "No results found.".to_string();
}
let mut out = String::new();
for (index, result) in results.iter().enumerate() {
if index > 0 {
out.push_str("\n\n");
}
out.push_str(&format!(
"{}. {}\n {}",
index + 1,
result.title,
result.url
));
if !result.snippet.is_empty() {
out.push_str("\n ");
out.push_str(&result.snippet);
}
}
out
}
/// Formats a fetched page with a short header followed by its text.
pub fn format_fetched_page(page: &FetchedPage) -> String {
let mut out = format!("URL: {}\nStatus: {}", page.final_url, page.status);
if let Some(content_type) = &page.content_type {
out.push_str(&format!("\nContent-Type: {content_type}"));
}
if let Some(title) = &page.title {
out.push_str(&format!("\nTitle: {title}"));
}
if page.truncated {
out.push_str("\nNote: content truncated at the size limit");
}
out.push_str("\n\n");
if page.text.is_empty() {
out.push_str("(no text content)");
} else {
out.push_str(&page.text);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn formats_results() {
let results = vec![
SearchResult {
title: "A".to_string(),
url: "https://a.example/".to_string(),
snippet: "first".to_string(),
},
SearchResult {
title: "B".to_string(),
url: "https://b.example/".to_string(),
snippet: String::new(),
},
];
assert_eq!(
format_search_results(&results),
"1. A\n https://a.example/\n first\n\n2. B\n https://b.example/"
);
assert_eq!(format_search_results(&[]), "No results found.");
}
#[test]
fn formats_page() {
let page = FetchedPage {
final_url: url::Url::parse("https://a.example/x").unwrap(),
status: 200,
content_type: Some("text/html".to_string()),
title: Some("T".to_string()),
text: "body".to_string(),
truncated: true,
};
assert_eq!(
format_fetched_page(&page),
"URL: https://a.example/x\nStatus: 200\nContent-Type: text/html\nTitle: T\nNote: content truncated at the size limit\n\nbody"
);
}
}

View File

@@ -0,0 +1,461 @@
//! Small hand-written HTML-to-text extractor. It is not a conforming HTML
//! parser; it aims to produce readable text for a language model from
//! typical web pages without pulling in a parsing dependency.
/// Text extracted from an HTML document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedHtml {
pub title: Option<String>,
pub text: String,
}
/// Elements whose content is raw text that must be skipped entirely.
const RAW_SKIP: &[&str] = &["script", "style"];
/// Container elements whose whole subtree is dropped.
const SKIP_CONTAINERS: &[&str] = &[
"head", "noscript", "template", "svg", "math", "iframe", "object", "canvas",
];
/// Elements separated from their surroundings by a blank line.
const PARAGRAPH_ELEMENTS: &[&str] = &[
"blockquote",
"dl",
"figure",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"ol",
"p",
"table",
"ul",
];
/// Elements that start a new line in the extracted text.
const BLOCK_ELEMENTS: &[&str] = &[
"address",
"article",
"aside",
"blockquote",
"body",
"caption",
"dd",
"details",
"dialog",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"html",
"legend",
"main",
"menu",
"nav",
"ol",
"p",
"pre",
"section",
"summary",
"table",
"tbody",
"tfoot",
"thead",
"tr",
"ul",
];
/// Converts an HTML document into plain text plus its `<title>`.
pub fn html_to_text(html: &str) -> ExtractedHtml {
let mut extractor = Extractor::default();
extractor.run(html);
ExtractedHtml {
title: extractor
.title
.map(|t| collapse_inline_whitespace(&t))
.filter(|t| !t.is_empty()),
text: normalize_whitespace(&extractor.out),
}
}
#[derive(Default)]
struct Extractor {
out: String,
title: Option<String>,
skip_stack: Vec<String>,
pre_depth: usize,
}
impl Extractor {
fn run(&mut self, html: &str) {
let bytes = html.as_bytes();
let len = bytes.len();
let mut i = 0;
while i < len {
if bytes[i] != b'<' {
let next = html[i..].find('<').map_or(len, |p| i + p);
self.push_text(&html[i..next]);
i = next;
continue;
}
let rest = &html[i..];
if let Some(comment) = rest.strip_prefix("<!--") {
match comment.find("-->") {
Some(p) => i += 4 + p + 3,
None => break,
}
continue;
}
if rest.starts_with("<!") || rest.starts_with("<?") {
i = rest.find('>').map_or(len, |p| i + p + 1);
continue;
}
let (is_close, name_start) = if bytes.get(i + 1) == Some(&b'/') {
(true, i + 2)
} else {
(false, i + 1)
};
if name_start >= len || !bytes[name_start].is_ascii_alphabetic() {
// A literal '<' in text.
self.push_text("<");
i += 1;
continue;
}
let mut name_end = name_start;
while name_end < len
&& (bytes[name_end].is_ascii_alphanumeric()
|| bytes[name_end] == b'-'
|| bytes[name_end] == b':')
{
name_end += 1;
}
let name = html[name_start..name_end].to_ascii_lowercase();
let tag_end = find_tag_end(bytes, name_end);
let self_closing =
tag_end >= 2 && bytes[tag_end - 1] == b'>' && bytes[tag_end - 2] == b'/';
i = tag_end;
if !is_close && !self_closing && (RAW_SKIP.contains(&name.as_str()) || name == "title")
{
let (content_end, after) = find_closing_tag(html, i, &name);
if name == "title" && self.title.is_none() {
self.title = Some(decode_entities(&html[i..content_end]));
}
i = after;
continue;
}
self.handle_tag(&name, is_close, self_closing);
}
}
fn handle_tag(&mut self, name: &str, is_close: bool, self_closing: bool) {
if SKIP_CONTAINERS.contains(&name) {
if is_close {
if let Some(pos) = self.skip_stack.iter().rposition(|n| n == name) {
self.skip_stack.truncate(pos);
}
} else if !self_closing {
self.skip_stack.push(name.to_string());
}
return;
}
if name == "body" && !is_close {
// `<body>` implicitly closes an unterminated `<head>`.
if let Some(pos) = self.skip_stack.iter().position(|n| n == "head") {
self.skip_stack.truncate(pos);
}
}
if !self.skip_stack.is_empty() {
return;
}
match name {
"br" => self.out.push('\n'),
"li" if !is_close => {
self.ensure_breaks(1);
self.out.push_str("- ");
}
"td" | "th" if !is_close => self.out.push(' '),
"pre" => {
if is_close {
self.pre_depth = self.pre_depth.saturating_sub(1);
} else if !self_closing {
self.pre_depth += 1;
}
self.ensure_breaks(2);
}
_ if PARAGRAPH_ELEMENTS.contains(&name) => self.ensure_breaks(2),
_ if BLOCK_ELEMENTS.contains(&name) => self.ensure_breaks(1),
_ => {}
}
}
/// Makes sure the output ends with at least `n` line breaks (ignoring
/// trailing spaces). Nothing is added at the very start of the output.
fn ensure_breaks(&mut self, n: usize) {
let trimmed = self.out.trim_end_matches(' ');
if trimmed.is_empty() {
return;
}
let have = trimmed.len() - trimmed.trim_end_matches('\n').len();
for _ in have..n {
self.out.push('\n');
}
}
fn push_text(&mut self, raw: &str) {
if !self.skip_stack.is_empty() {
return;
}
let decoded = decode_entities(raw);
let keep_newlines = self.pre_depth > 0;
for c in decoded.chars() {
if c == '\n' && keep_newlines {
self.out.push('\n');
} else if c.is_whitespace() {
self.out.push(' ');
} else {
self.out.push(c);
}
}
}
}
/// Returns the index just past the `>` ending the tag whose name ends at
/// `from`, honouring quoted attribute values.
fn find_tag_end(bytes: &[u8], from: usize) -> usize {
let mut quote: Option<u8> = None;
let mut i = from;
while i < bytes.len() {
let b = bytes[i];
match quote {
Some(q) if b == q => quote = None,
Some(_) => {}
None if b == b'"' || b == b'\'' => quote = Some(b),
None if b == b'>' => return i + 1,
None => {}
}
i += 1;
}
bytes.len()
}
/// Finds `</name ...>` (case-insensitive) starting at `from`. Returns the
/// end of the content and the index after the closing tag; both are the
/// end of input when the element is never closed.
fn find_closing_tag(html: &str, from: usize, name: &str) -> (usize, usize) {
let bytes = html.as_bytes();
let needle = name.as_bytes();
let mut i = from;
while let Some(p) = html[i..].find("</") {
let start = i + p;
let name_start = start + 2;
let name_end = name_start + needle.len();
if name_end <= bytes.len()
&& bytes[name_start..name_end].eq_ignore_ascii_case(needle)
&& bytes
.get(name_end)
.is_none_or(|b| !b.is_ascii_alphanumeric())
{
return (start, find_tag_end(bytes, name_end));
}
i = name_start;
}
(html.len(), html.len())
}
fn named_entity(name: &str) -> Option<char> {
let c = match name {
"amp" | "AMP" => '&',
"lt" | "LT" => '<',
"gt" | "GT" => '>',
"quot" | "QUOT" => '"',
"apos" => '\'',
"nbsp" => ' ',
"copy" | "COPY" => '©',
"reg" | "REG" => '®',
"trade" => '™',
"hellip" => '…',
"mdash" => '—',
"ndash" => '–',
"lsquo" => '‘',
"rsquo" => '’',
"sbquo" => '‚',
"ldquo" => '“',
"rdquo" => '”',
"bdquo" => '„',
"laquo" => '«',
"raquo" => '»',
"bull" => '•',
"middot" => '·',
"deg" => '°',
"plusmn" => '±',
"times" => '×',
"divide" => '÷',
"sect" => '§',
"para" => '¶',
"euro" => '€',
"pound" => '£',
"yen" => '¥',
"cent" => '¢',
"shy" => '\u{ad}',
"zwj" => '\u{200d}',
"zwnj" => '\u{200c}',
_ => return None,
};
Some(c)
}
/// Parses an entity at the start of `s` (which begins with `&`). Returns the
/// decoded character and the number of bytes consumed.
fn parse_entity(s: &str) -> Option<(char, usize)> {
let semi = s.bytes().take(32).position(|b| b == b';')?;
let body = &s[1..semi];
let c = if let Some(num) = body.strip_prefix('#') {
let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(hex, 16).unwrap_or(u32::MAX)
} else {
if num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
num.parse::<u32>().unwrap_or(u32::MAX)
};
char::from_u32(code)
.filter(|c| *c != '\0')
.unwrap_or('\u{fffd}')
} else {
named_entity(body)?
};
Some((c, semi + 1))
}
/// Decodes common named entities and numeric character references.
/// Unknown or unterminated entities are left untouched.
pub fn decode_entities(s: &str) -> String {
if !s.contains('&') {
return s.to_string();
}
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(p) = rest.find('&') {
out.push_str(&rest[..p]);
rest = &rest[p..];
match parse_entity(rest) {
Some((c, consumed)) => {
out.push(c);
rest = &rest[consumed..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
fn collapse_inline_whitespace(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Collapses runs of whitespace within lines, trims lines and keeps at most
/// one blank line between paragraphs.
pub(crate) fn normalize_whitespace(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut pending_blank = false;
for line in s.split('\n') {
let line = collapse_inline_whitespace(line);
if line.is_empty() {
pending_blank = !out.is_empty();
continue;
}
if !out.is_empty() {
out.push('\n');
if pending_blank {
out.push('\n');
}
}
pending_blank = false;
out.push_str(&line);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn extracts_text_and_title() {
let html = r#"<!DOCTYPE html>
<html><head><title> Hello &amp; welcome </title>
<meta charset="utf-8"><style>body { color: red; }</style>
<script>var x = "<p>not text</p>";</script></head>
<body>
<!-- a comment <p>hidden</p> -->
<h1>Heading</h1>
<p>First paragraph with <b>bold</b> and <a href="/x?a=1&amp;b=2">a link</a>.</p>
<noscript>enable js</noscript>
<template><p>tpl</p></template>
<svg viewBox="0 0 1 1"><text>svg text</text></svg>
<ul><li>one</li><li>two</li></ul>
<div>a<br>b</div>
<p>Entities: &lt;tag&gt; &quot;q&quot; &#39;s&#39; &#65;&#x42;&nbsp;end &unknown; & alone</p>
</body></html>"#;
let extracted = html_to_text(html);
assert_eq!(extracted.title.as_deref(), Some("Hello & welcome"));
assert_eq!(
extracted.text,
"Heading\n\nFirst paragraph with bold and a link.\n\n- one\n- two\n\na\nb\n\nEntities: <tag> \"q\" 's' AB end &unknown; & alone"
);
}
#[test]
fn head_without_close_ends_at_body() {
let extracted = html_to_text("<head><meta x='>'>junk<body>visible");
assert_eq!(extracted.text, "visible");
assert_eq!(extracted.title, None);
}
#[test]
fn unclosed_script_drops_rest() {
assert_eq!(html_to_text("<p>a</p><script>if (a < b) {").text, "a");
}
#[test]
fn script_close_is_case_insensitive() {
assert_eq!(html_to_text("x<SCRIPT>y</Script >z").text, "xz");
}
#[test]
fn pre_keeps_newlines() {
assert_eq!(html_to_text("<pre>a\nb</pre>").text, "a\nb");
}
#[test]
fn literal_less_than_and_numeric_entities() {
assert_eq!(
decode_entities("1 &lt; 2 &#0; &#xD800; &#x1F600;"),
"1 < 2 \u{fffd} \u{fffd} 😀"
);
assert_eq!(html_to_text("a < b").text, "a < b");
}
}

View File

@@ -0,0 +1,34 @@
//! Self-contained web tools for aKode: a SearXNG search client and an
//! SSRF-hardened page fetcher that turns HTML into plain text.
//!
//! Nothing in this crate talks to a hosted model provider; the only
//! endpoints contacted are the configured SearXNG instance and the pages
//! the caller explicitly asks to fetch.
mod body;
mod error;
mod fetch;
mod format;
mod html;
mod net;
mod search;
pub use error::Result;
pub use error::WebToolsError;
pub use fetch::DEFAULT_FETCH_USER_AGENT;
pub use fetch::FetchedPage;
pub use fetch::WebFetchOptions;
pub use fetch::WebFetcher;
pub use format::format_fetched_page;
pub use format::format_search_results;
pub use html::ExtractedHtml;
pub use html::decode_entities;
pub use html::html_to_text;
pub use net::HostResolver;
pub use net::ResolveFuture;
pub use net::SystemResolver;
pub use net::is_blocked_ip;
pub use search::DEFAULT_SEARCH_USER_AGENT;
pub use search::SearchResult;
pub use search::SearxngClient;
pub use search::SearxngOptions;

View File

@@ -0,0 +1,237 @@
//! Address classification and DNS resolution used for SSRF protection.
use std::future::Future;
use std::io;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
/// Future returned by [`HostResolver::resolve`].
pub type ResolveFuture<'a> = Pin<Box<dyn Future<Output = io::Result<Vec<SocketAddr>>> + Send + 'a>>;
/// Resolves a host name to socket addresses. The fetcher resolves names
/// itself, vets every address, and then connects only to the vetted ones.
/// Injectable so tests can simulate arbitrary DNS answers.
pub trait HostResolver: Send + Sync {
fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a>;
}
/// Resolver backed by the operating system (`getaddrinfo` via tokio).
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemResolver;
impl HostResolver for SystemResolver {
fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a> {
Box::pin(async move { Ok(tokio::net::lookup_host((host, port)).await?.collect()) })
}
}
/// IPv4 ranges that must never be reached by the fetcher.
const BLOCKED_V4: &[([u8; 4], u32)] = &[
([0, 0, 0, 0], 8), // "this network", incl. 0.0.0.0
([10, 0, 0, 0], 8), // private
([100, 64, 0, 0], 10), // CGNAT
([127, 0, 0, 0], 8), // loopback
([169, 254, 0, 0], 16), // link-local, incl. cloud metadata 169.254.169.254
([172, 16, 0, 0], 12), // private
([192, 0, 0, 0], 24), // IETF protocol assignments
([192, 0, 2, 0], 24), // TEST-NET-1
([192, 88, 99, 0], 24), // 6to4 relay anycast
([192, 168, 0, 0], 16), // private
([198, 18, 0, 0], 15), // benchmarking
([198, 51, 100, 0], 24), // TEST-NET-2
([203, 0, 113, 0], 24), // TEST-NET-3
([224, 0, 0, 0], 4), // multicast
([240, 0, 0, 0], 4), // reserved, incl. broadcast 255.255.255.255
];
fn in_v4_net(ip: Ipv4Addr, net: [u8; 4], prefix: u32) -> bool {
let mask = if prefix == 0 {
0
} else {
u32::MAX << (32 - prefix)
};
(u32::from(ip) & mask) == (u32::from(Ipv4Addr::from(net)) & mask)
}
fn is_blocked_ipv4(ip: Ipv4Addr) -> bool {
BLOCKED_V4
.iter()
.any(|(net, prefix)| in_v4_net(ip, *net, *prefix))
}
fn is_blocked_ipv6(ip: Ipv6Addr) -> bool {
let s = ip.segments();
// IPv4-mapped (::ffff:a.b.c.d): judge the embedded IPv4 address.
if let Some(v4) = ip.to_ipv4_mapped() {
return is_blocked_ipv4(v4);
}
// NAT64 well-known prefix 64:ff9b::/96: judge the embedded IPv4 address.
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
let low = u128::from(ip) as u32;
return is_blocked_ipv4(Ipv4Addr::from(low));
}
// 6to4 2002::/16 embeds an IPv4 address in bits 16..48.
if s[0] == 0x2002 {
let v4 = Ipv4Addr::new((s[1] >> 8) as u8, s[1] as u8, (s[2] >> 8) as u8, s[2] as u8);
return is_blocked_ipv4(v4);
}
// Only global unicast 2000::/3 is reachable. This rules out ::, ::1,
// IPv4-compatible ::a.b.c.d, IPv4-translated, 64:ff9b:1::/48, 100::/64,
// fc00::/7 (ULA), fe80::/10 (link-local), fec0::/10 and ff00::/8.
if s[0] & 0xe000 != 0x2000 {
return true;
}
// 2001::/23 IETF protocol assignments (Teredo, benchmarking, ORCHID, ...).
if s[0] == 0x2001 && s[1] < 0x0200 {
return true;
}
// 2001:db8::/32 and 3fff::/20 documentation.
if s[0] == 0x2001 && s[1] == 0x0db8 {
return true;
}
s[0] == 0x3fff && s[1] & 0xf000 == 0
}
/// Returns true when `ip` is loopback, private, link-local, CGNAT,
/// unspecified, multicast, broadcast, documentation/benchmark or otherwise
/// reserved, including IPv4-mapped, NAT64 and 6to4 forms of those.
pub fn is_blocked_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => is_blocked_ipv4(v4),
IpAddr::V6(v6) => is_blocked_ipv6(v6),
}
}
/// An address is acceptable if it is public, or if it is exactly one of the
/// explicitly allowlisted socket addresses (same IP and same port).
pub(crate) fn is_addr_allowed(addr: SocketAddr, allowlist: &[SocketAddr]) -> bool {
allowlist.contains(&addr) || !is_blocked_ip(addr.ip())
}
/// `localhost` and `*.localhost` always mean loopback (RFC 6761); they are
/// answered locally instead of trusting DNS.
pub(crate) fn is_localhost_name(host: &str) -> bool {
let host = host.trim_end_matches('.').to_ascii_lowercase();
host == "localhost" || host.ends_with(".localhost")
}
/// reqwest resolver that only ever returns the addresses vetted for the
/// current hop, so a second DNS lookup (DNS rebinding) cannot change the
/// destination and the system resolver is never consulted.
pub(crate) struct PinnedResolver {
host: String,
addrs: Vec<SocketAddr>,
}
impl PinnedResolver {
pub(crate) fn new(host: String, addrs: Vec<SocketAddr>) -> Arc<Self> {
Arc::new(Self { host, addrs })
}
}
impl reqwest::dns::Resolve for PinnedResolver {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let result: Result<reqwest::dns::Addrs, Box<dyn std::error::Error + Send + Sync>> =
if name.as_str().eq_ignore_ascii_case(&self.host) && !self.addrs.is_empty() {
Ok(Box::new(self.addrs.clone().into_iter()))
} else {
Err(format!("host `{}` was not vetted for this request", name.as_str()).into())
};
Box::pin(async move { result })
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn classifies_addresses() {
let blocked = [
"0.0.0.0",
"10.1.2.3",
"100.64.0.1",
"100.127.255.254",
"127.0.0.1",
"127.255.255.255",
"169.254.169.254",
"172.16.0.1",
"172.31.255.255",
"192.0.0.8",
"192.0.2.1",
"192.168.1.1",
"198.18.0.1",
"198.51.100.7",
"203.0.113.9",
"224.0.0.1",
"239.255.255.250",
"240.0.0.1",
"255.255.255.255",
"::",
"::1",
"::127.0.0.1",
"::ffff:127.0.0.1",
"::ffff:10.0.0.1",
"::ffff:169.254.169.254",
"64:ff9b::7f00:1",
"64:ff9b::a9fe:a9fe",
"64:ff9b:1::1",
"100::1",
"2001::1",
"2001:db8::1",
"2002:7f00:1::1",
"2002:c0a8:101::1",
"3fff::1",
"fc00::1",
"fd12:3456::1",
"fe80::1",
"fec0::1",
"ff02::1",
];
for ip in blocked {
let parsed: IpAddr = ip.parse().unwrap();
assert_eq!(is_blocked_ip(parsed), true, "{ip} should be blocked");
}
let allowed = [
"1.1.1.1",
"8.8.8.8",
"93.184.216.34",
"100.63.255.255",
"100.128.0.0",
"172.15.255.255",
"172.32.0.0",
"::ffff:8.8.8.8",
"64:ff9b::808:808",
"2002:808:808::1",
"2606:4700:4700::1111",
"2a00:1450:4001::200e",
];
for ip in allowed {
let parsed: IpAddr = ip.parse().unwrap();
assert_eq!(is_blocked_ip(parsed), false, "{ip} should be allowed");
}
}
#[test]
fn allowlist_is_exact_socket_address() {
let allowed: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let list = [allowed];
assert!(is_addr_allowed(allowed, &list));
assert!(!is_addr_allowed("127.0.0.1:8081".parse().unwrap(), &list));
assert!(!is_addr_allowed("127.0.0.2:8080".parse().unwrap(), &list));
assert!(is_addr_allowed("8.8.8.8:443".parse().unwrap(), &[]));
}
#[test]
fn localhost_names() {
assert!(is_localhost_name("localhost"));
assert!(is_localhost_name("LOCALHOST."));
assert!(is_localhost_name("foo.localhost"));
assert!(!is_localhost_name("localhost.example.com"));
}
}

View File

@@ -0,0 +1,213 @@
//! Client for a self-hosted SearXNG instance (JSON API).
use std::collections::HashSet;
use std::time::Duration;
use reqwest::header::ACCEPT;
use serde::Deserialize;
use serde::Serialize;
use url::Url;
use crate::body::read_capped;
use crate::error::Result;
use crate::error::WebToolsError;
use crate::error::request_error;
pub const DEFAULT_SEARCH_USER_AGENT: &str = "aKode-web-search/0.1";
/// Hard upper bound on the number of results returned by one search.
const MAX_RESULTS_LIMIT: usize = 50;
/// Options for [`SearxngClient`].
#[derive(Debug, Clone)]
pub struct SearxngOptions {
/// Results returned when the caller does not ask for a specific number.
pub max_results: usize,
pub timeout: Duration,
/// Maximum size of the JSON response; larger responses are an error.
pub max_response_bytes: usize,
pub user_agent: String,
}
impl Default for SearxngOptions {
fn default() -> Self {
Self {
max_results: 8,
timeout: Duration::from_secs(15),
max_response_bytes: 2 * 1024 * 1024,
user_agent: DEFAULT_SEARCH_USER_AGENT.to_string(),
}
}
}
/// One search hit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchResult {
pub title: String,
pub url: String,
pub snippet: String,
}
/// Client for the SearXNG JSON API. The configured instance may live on a
/// private or loopback address: it is trusted configuration, unlike the
/// URLs handled by [`crate::WebFetcher`].
#[derive(Debug, Clone)]
pub struct SearxngClient {
search_url: Url,
opts: SearxngOptions,
client: reqwest::Client,
}
#[derive(Deserialize)]
struct RawResponse {
#[serde(default)]
results: Vec<RawResult>,
}
#[derive(Deserialize)]
struct RawResult {
#[serde(default)]
title: Option<String>,
#[serde(default)]
url: Option<String>,
#[serde(default)]
content: Option<String>,
}
impl SearxngClient {
/// `base_url` is the instance root, e.g. `http://searxng:8080/` or
/// `https://host/searx/`; requests go to `{base_url}/search`.
pub fn new(base_url: Url, opts: SearxngOptions) -> Result<Self> {
match base_url.scheme() {
"http" | "https" => {}
other => return Err(WebToolsError::UnsupportedScheme(other.to_string())),
}
if base_url.host().is_none() {
return Err(WebToolsError::MissingHost);
}
let mut search_url = base_url;
search_url.set_fragment(None);
search_url
.path_segments_mut()
.map_err(|()| WebToolsError::InvalidUrl("URL cannot be a base".to_string()))?
.pop_if_empty()
.push("search");
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.no_proxy()
.timeout(opts.timeout)
.user_agent(opts.user_agent.as_str())
.build()
.map_err(|err| request_error(err, opts.timeout))?;
Ok(Self {
search_url,
opts,
client,
})
}
/// The endpoint queried by [`Self::search`] (without query parameters).
pub fn search_url(&self) -> &Url {
&self.search_url
}
/// Runs a search and returns at most `max_results` results (the
/// configured default when `None`, clamped to 1..=50).
pub async fn search(
&self,
query: &str,
max_results: Option<usize>,
) -> Result<Vec<SearchResult>> {
let query = query.trim();
if query.is_empty() {
return Err(WebToolsError::InvalidInput(
"the search query is empty".to_string(),
));
}
let limit = max_results
.unwrap_or(self.opts.max_results)
.clamp(1, MAX_RESULTS_LIMIT);
let mut url = self.search_url.clone();
url.query_pairs_mut()
.append_pair("q", query)
.append_pair("format", "json");
let timeout = self.opts.timeout;
let mut response = tokio::time::timeout(
timeout,
self.client
.get(url)
.header(ACCEPT, "application/json")
.send(),
)
.await
.map_err(|_| WebToolsError::Timeout(timeout))?
.map_err(|err| request_error(err, timeout))?;
let status = response.status();
let (bytes, truncated) = tokio::time::timeout(
timeout,
read_capped(&mut response, self.opts.max_response_bytes, timeout),
)
.await
.map_err(|_| WebToolsError::Timeout(timeout))??;
if !status.is_success() {
let mut message = String::from_utf8_lossy(&bytes[..bytes.len().min(300)])
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if status.as_u16() == 403 {
message.push_str(" (is `json` enabled in SearXNG `search.formats`?)");
}
return Err(WebToolsError::HttpStatus {
status: status.as_u16(),
message,
});
}
if truncated {
return Err(WebToolsError::ResponseTooLarge(
self.opts.max_response_bytes,
));
}
let parsed: RawResponse = serde_json::from_slice(&bytes).map_err(|err| {
WebToolsError::InvalidResponse(format!("SearXNG did not return valid JSON: {err}"))
})?;
Ok(collect_results(parsed, limit))
}
}
fn clean(s: Option<String>) -> String {
s.unwrap_or_default()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn collect_results(parsed: RawResponse, limit: usize) -> Vec<SearchResult> {
let mut seen = HashSet::new();
let mut out = Vec::new();
for raw in parsed.results {
let url = raw.url.unwrap_or_default().trim().to_string();
if url.is_empty() || !seen.insert(url.clone()) {
continue;
}
let mut title = clean(raw.title);
if title.is_empty() {
title.clone_from(&url);
}
out.push(SearchResult {
title,
url,
snippet: clean(raw.content),
});
if out.len() >= limit {
break;
}
}
out
}
#[cfg(test)]
#[path = "search_tests.rs"]
mod tests;

View File

@@ -0,0 +1,219 @@
use std::time::Duration;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use super::*;
fn results_json(n: usize) -> serde_json::Value {
let results: Vec<_> = (0..n)
.map(|i| {
json!({
"title": format!("Result {i}"),
"url": format!("https://example.com/{i}"),
"content": format!("snippet\n{i}"),
"engine": "test",
})
})
.collect();
json!({ "query": "q", "results": results })
}
fn client(base: &str, opts: SearxngOptions) -> SearxngClient {
SearxngClient::new(Url::parse(base).unwrap(), opts).unwrap()
}
#[tokio::test]
async fn parses_results_and_limits_count() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/search"))
.and(query_param("format", "json"))
.respond_with(ResponseTemplate::new(200).set_body_json(results_json(12)))
.mount(&server)
.await;
let client = client(&server.uri(), SearxngOptions::default());
let default_limit = client.search("rust", None).await.unwrap();
assert_eq!(default_limit.len(), 8);
assert_eq!(
default_limit[0],
SearchResult {
title: "Result 0".to_string(),
url: "https://example.com/0".to_string(),
snippet: "snippet 0".to_string(),
}
);
let three = client.search("rust", Some(3)).await.unwrap();
let urls: Vec<_> = three.iter().map(|r| r.url.as_str()).collect();
assert_eq!(
urls,
vec![
"https://example.com/0",
"https://example.com/1",
"https://example.com/2"
]
);
}
#[tokio::test]
async fn encodes_query_and_preserves_base_path() {
let server = MockServer::start().await;
let query = "rust & c++ ?=#/ è";
Mock::given(method("GET"))
.and(path("/searx/search"))
.and(query_param("q", query))
.and(query_param("format", "json"))
.respond_with(ResponseTemplate::new(200).set_body_json(results_json(1)))
.expect(2)
.mount(&server)
.await;
for base in [
format!("{}/searx", server.uri()),
format!("{}/searx/", server.uri()),
] {
let client = client(&base, SearxngOptions::default());
assert_eq!(client.search_url().path(), "/searx/search");
let results = client.search(query, None).await.unwrap();
assert_eq!(results.len(), 1);
}
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests[0].url.query(),
Some("q=rust+%26+c%2B%2B+%3F%3D%23%2F+%C3%A8&format=json")
);
}
#[tokio::test]
async fn skips_entries_without_url_and_duplicates() {
let server = MockServer::start().await;
let body = json!({ "results": [
{ "title": "no url" },
{ "url": "https://a.example/", "title": "", "content": null },
{ "url": "https://a.example/", "title": "dup" },
{ "url": "https://b.example/", "title": "B", "content": "b" },
]});
Mock::given(path("/search"))
.respond_with(ResponseTemplate::new(200).set_body_json(body))
.mount(&server)
.await;
let results = client(&server.uri(), SearxngOptions::default())
.search("x", None)
.await
.unwrap();
assert_eq!(
results,
vec![
SearchResult {
title: "https://a.example/".to_string(),
url: "https://a.example/".to_string(),
snippet: String::new(),
},
SearchResult {
title: "B".to_string(),
url: "https://b.example/".to_string(),
snippet: "b".to_string(),
},
]
);
}
#[tokio::test]
async fn non_json_response_is_an_error() {
let server = MockServer::start().await;
Mock::given(path("/search"))
.respond_with(ResponseTemplate::new(200).set_body_raw("<html>nope</html>", "text/html"))
.mount(&server)
.await;
let err = client(&server.uri(), SearxngOptions::default())
.search("x", None)
.await
.unwrap_err();
assert!(matches!(err, WebToolsError::InvalidResponse(_)), "{err:?}");
}
#[tokio::test]
async fn http_error_is_reported() {
let server = MockServer::start().await;
Mock::given(path("/search"))
.respond_with(ResponseTemplate::new(403).set_body_string("Forbidden"))
.mount(&server)
.await;
let err = client(&server.uri(), SearxngOptions::default())
.search("x", None)
.await
.unwrap_err();
match err {
WebToolsError::HttpStatus { status, message } => {
assert_eq!(status, 403);
assert!(message.starts_with("Forbidden"), "{message}");
}
other => panic!("unexpected error: {other:?}"),
}
}
#[tokio::test]
async fn oversized_response_is_an_error() {
let server = MockServer::start().await;
Mock::given(path("/search"))
.respond_with(ResponseTemplate::new(200).set_body_json(results_json(50)))
.mount(&server)
.await;
let opts = SearxngOptions {
max_response_bytes: 256,
..SearxngOptions::default()
};
let err = client(&server.uri(), opts)
.search("x", None)
.await
.unwrap_err();
assert!(
matches!(err, WebToolsError::ResponseTooLarge(256)),
"{err:?}"
);
}
#[tokio::test]
async fn times_out() {
let server = MockServer::start().await;
Mock::given(path("/search"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(results_json(1))
.set_delay(Duration::from_secs(5)),
)
.mount(&server)
.await;
let opts = SearxngOptions {
timeout: Duration::from_millis(200),
..SearxngOptions::default()
};
let err = client(&server.uri(), opts)
.search("x", None)
.await
.unwrap_err();
assert!(matches!(err, WebToolsError::Timeout(_)), "{err:?}");
}
#[tokio::test]
async fn rejects_bad_base_url_and_empty_query() {
for base in ["ftp://searx.example/", "file:///tmp/x", "mailto:a@b.c"] {
let err =
SearxngClient::new(Url::parse(base).unwrap(), SearxngOptions::default()).unwrap_err();
assert!(
matches!(err, WebToolsError::UnsupportedScheme(_)),
"{base}: {err:?}"
);
}
let client = client("http://127.0.0.1:9/", SearxngOptions::default());
let err = client.search(" ", None).await.unwrap_err();
assert!(matches!(err, WebToolsError::InvalidInput(_)), "{err:?}");
}