Skip to main content

aidaemon_tools/
web.rs

1//! `web_fetch`: GET a page and return its readable text.
2//!
3//! Every request, and every redirect hop, is checked against the
4//! private-network policy ([`validate_url_for_ssrf`]). By default redirects
5//! stay on the requested host, so the host declared in [`Tool::access`] is
6//! the only host contacted; [`WebFetch::follow_public_redirects`] allows
7//! other public hosts.
8
9use std::collections::HashMap;
10use std::io::Cursor;
11use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
12use std::sync::OnceLock;
13use std::time::Duration;
14
15use async_trait::async_trait;
16use reqwest::redirect::Policy;
17use reqwest::{Client, StatusCode, Url};
18use serde::Deserialize;
19use serde_json::{Value, json};
20
21use aidaemon_core::{
22    AccessManifest, CallEffects, EffectClass, EffectKey, Hook, HookContext, Tool, ToolAnnotations,
23    ToolCall, ToolContext, ToolDecision, ToolInfo, ToolOutput, ToolResult,
24};
25
26use crate::fs::ToolText;
27use crate::outcome::{OutcomeTool, spec_of};
28use crate::semantics::{
29    NetworkReach, ToolCallContext, ToolCallMetadata, ToolCallOutcome, ToolCallSemantics,
30    ToolCapabilities, ToolTargetHintKind, ToolVerificationMode,
31};
32use crate::util::{fail, parse_args, truncate_chars};
33
34const DEFAULT_MAX_CHARS: usize = 20_000;
35const MAX_MAX_CHARS: usize = 50_000;
36
37/// Hard cap on response-body bytes buffered from a web fetch/search. The
38/// model-facing output is already bounded (extracted-text char limit / result
39/// count); this only bounds *transient memory* against a pathologically large
40/// or mislabeled response that `.text()`/`.json()` would otherwise buffer whole.
41pub const MAX_FETCH_BODY_BYTES: usize = 10 * 1024 * 1024;
42
43/// Append `chunk` to `buf` without exceeding `max_bytes`. Returns true if the
44/// chunk was (partially) dropped because the cap was reached. Truncation is on a
45/// raw byte boundary, so callers must decode with `from_utf8_lossy`.
46pub fn append_capped(buf: &mut Vec<u8>, chunk: &[u8], max_bytes: usize) -> bool {
47    let remaining = max_bytes.saturating_sub(buf.len());
48    if chunk.len() > remaining {
49        buf.extend_from_slice(&chunk[..remaining]);
50        true
51    } else {
52        buf.extend_from_slice(chunk);
53        false
54    }
55}
56
57/// Stream a response body into memory, capping at `max_bytes` to avoid unbounded
58/// allocation. Returns the collected bytes and whether the body was truncated.
59pub async fn read_body_capped(
60    resp: reqwest::Response,
61    max_bytes: usize,
62) -> reqwest::Result<(Vec<u8>, bool)> {
63    let mut resp = resp;
64    let mut buf: Vec<u8> = Vec::new();
65    let mut truncated = false;
66    while let Some(chunk) = resp.chunk().await? {
67        if append_capped(&mut buf, &chunk, max_bytes) {
68            truncated = true;
69            break;
70        }
71    }
72    Ok((buf, truncated))
73}
74
75/// Validates a URL for SSRF vulnerabilities.
76/// Returns Ok(()) if the URL is safe to fetch, Err with a message otherwise.
77pub fn validate_url_for_ssrf(url: &str) -> Result<(), String> {
78    let parsed = reqwest::Url::parse(url).map_err(|e| format!("Invalid URL: {}", e))?;
79
80    // 1. Only allow http and https schemes
81    match parsed.scheme() {
82        "http" | "https" => {}
83        scheme => {
84            return Err(format!(
85                "Blocked scheme '{}': only http/https allowed",
86                scheme
87            ));
88        }
89    }
90
91    // 2. Must have a host
92    let host = parsed
93        .host_str()
94        .ok_or_else(|| "URL must have a host".to_string())?;
95
96    // 3. Block known dangerous hostnames
97    let host_lower = host.to_lowercase();
98    const BLOCKED_HOSTS: &[&str] = &[
99        "localhost",
100        "127.0.0.1",
101        "::1",
102        "[::1]",
103        "0.0.0.0",
104        "metadata.google.internal",
105        "metadata.goog",
106        "169.254.169.254",
107    ];
108    for blocked in BLOCKED_HOSTS {
109        if host_lower == *blocked {
110            return Err(format!("Blocked host: {}", host));
111        }
112    }
113
114    // 4. Block hosts that look like internal addresses
115    if host_lower.ends_with(".internal")
116        || host_lower.ends_with(".local")
117        || host_lower.ends_with(".localhost")
118    {
119        return Err(format!("Blocked internal hostname: {}", host));
120    }
121
122    // 5. Resolve the hostname and check all IP addresses
123    let port = parsed.port().unwrap_or(match parsed.scheme() {
124        "https" => 443,
125        _ => 80,
126    });
127
128    // Try to resolve the hostname
129    let socket_addr = format!("{}:{}", host, port);
130    match socket_addr.to_socket_addrs() {
131        Ok(addrs) => {
132            for addr in addrs {
133                if is_blocked_ip(addr.ip()) {
134                    return Err(format!(
135                        "Blocked IP address {} (resolved from {})",
136                        addr.ip(),
137                        host
138                    ));
139                }
140            }
141        }
142        Err(_) => {
143            // If we can't resolve, it might be a raw IP - try parsing it
144            if let Ok(ip) = host.parse::<IpAddr>()
145                && is_blocked_ip(ip)
146            {
147                return Err(format!("Blocked IP address: {}", ip));
148            }
149            // If resolution fails and it's not an IP, let the request fail naturally
150        }
151    }
152
153    Ok(())
154}
155
156/// Refuses at connection time any name that resolves to a blocked address.
157/// The check before a request and the connection look a name up separately,
158/// so a name could answer with a public address first and a private one next.
159pub(crate) struct PublicOnlyResolver;
160
161impl reqwest::dns::Resolve for PublicOnlyResolver {
162    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
163        let host = name.as_str().to_string();
164        Box::pin(async move {
165            let addrs: Vec<std::net::SocketAddr> =
166                tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
167            if let Some(blocked) = addrs.iter().find(|addr| is_blocked_ip(addr.ip())) {
168                let reason = format!("{host} resolves to blocked address {}", blocked.ip());
169                return Err(
170                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, reason).into(),
171                );
172            }
173            Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)
174        })
175    }
176}
177
178/// Check if an IP address is in a blocked range (private, loopback, link-local, etc.)
179fn is_blocked_ip(ip: IpAddr) -> bool {
180    match ip {
181        IpAddr::V4(ipv4) => is_blocked_ipv4(ipv4),
182        IpAddr::V6(ipv6) => is_blocked_ipv6(ipv6),
183    }
184}
185
186fn is_blocked_ipv4(ip: Ipv4Addr) -> bool {
187    let octets = ip.octets();
188
189    // Loopback: 127.0.0.0/8
190    if octets[0] == 127 {
191        return true;
192    }
193
194    // Private: 10.0.0.0/8
195    if octets[0] == 10 {
196        return true;
197    }
198
199    // Private: 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
200    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
201        return true;
202    }
203
204    // Private: 192.168.0.0/16
205    if octets[0] == 192 && octets[1] == 168 {
206        return true;
207    }
208
209    // Link-local: 169.254.0.0/16 (includes cloud metadata at 169.254.169.254)
210    if octets[0] == 169 && octets[1] == 254 {
211        return true;
212    }
213
214    // Broadcast: 255.255.255.255
215    if ip == Ipv4Addr::BROADCAST {
216        return true;
217    }
218
219    // Unspecified: 0.0.0.0
220    if ip == Ipv4Addr::UNSPECIFIED {
221        return true;
222    }
223
224    // Documentation ranges (TEST-NET): 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24
225    if (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
226        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
227        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
228    {
229        return true;
230    }
231
232    // Shared address space (CGNAT, tailnets): 100.64.0.0/10
233    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
234        return true;
235    }
236
237    // "This network" 0.0.0.0/8 (0.x.y.z reaches the local host on some
238    // systems), IETF protocol assignments 192.0.0.0/24, benchmarking
239    // 198.18.0.0/15, multicast 224.0.0.0/4 and reserved 240.0.0.0/4.
240    if octets[0] == 0
241        || (octets[0] == 192 && octets[1] == 0 && octets[2] == 0)
242        || (octets[0] == 198 && (18..=19).contains(&octets[1]))
243        || octets[0] >= 224
244    {
245        return true;
246    }
247
248    false
249}
250
251fn is_blocked_ipv6(ip: Ipv6Addr) -> bool {
252    // Loopback: ::1
253    if ip.is_loopback() {
254        return true;
255    }
256
257    // Unspecified: ::
258    if ip.is_unspecified() {
259        return true;
260    }
261
262    // IPv4-mapped addresses: check the embedded IPv4
263    if let Some(ipv4) = ip.to_ipv4_mapped() {
264        return is_blocked_ipv4(ipv4);
265    }
266
267    let segments = ip.segments();
268    let embedded_v4 = |high: u16, low: u16| {
269        Ipv4Addr::new(
270            (high >> 8) as u8,
271            (high & 0xff) as u8,
272            (low >> 8) as u8,
273            (low & 0xff) as u8,
274        )
275    };
276
277    // IPv4-compatible (deprecated) ::a.b.c.d: the first 96 bits are zero.
278    if segments[..6].iter().all(|segment| *segment == 0) {
279        return is_blocked_ipv4(embedded_v4(segments[6], segments[7]));
280    }
281
282    // NAT64 well-known prefix 64:ff9b::/96 and local-use 64:ff9b:1::/48:
283    // a translator forwards these to the embedded IPv4 address.
284    if segments[0] == 0x0064 && segments[1] == 0xff9b {
285        return segments[2..6].iter().all(|segment| *segment == 0)
286            && is_blocked_ipv4(embedded_v4(segments[6], segments[7]))
287            || segments[2] == 0x0001;
288    }
289
290    // 6to4 2002::/16 carries an IPv4 address in its next 32 bits.
291    if segments[0] == 0x2002 {
292        return is_blocked_ipv4(embedded_v4(segments[1], segments[2]));
293    }
294
295    // Teredo 2001::/32 tunnels to an obfuscated IPv4 address; discard-only
296    // 100::/64; site-local fec0::/10 (deprecated private); multicast ff00::/8.
297    if (segments[0] == 0x2001 && segments[1] == 0)
298        || (segments[0] == 0x0100 && segments[1..4].iter().all(|segment| *segment == 0))
299        || (segments[0] & 0xffc0) == 0xfec0
300        || (segments[0] & 0xff00) == 0xff00
301    {
302        return true;
303    }
304
305    // Link-local: fe80::/10
306    if (segments[0] & 0xffc0) == 0xfe80 {
307        return true;
308    }
309
310    // Unique local addresses (private): fc00::/7
311    if (segments[0] & 0xfe00) == 0xfc00 {
312        return true;
313    }
314
315    false
316}
317
318/// A coarse classification of *why* a host is blocked by the private-network
319/// policy. The whole point of this enum is **secret safety**: it carries only a
320/// fixed, low-cardinality category — never the URL, host, path, query, or
321/// credentials. Surfacing `class.label()` in an error message therefore cannot
322/// leak any caller-supplied data.
323///
324/// Shared by `web_fetch` and the `browser` tool so both name a blocked request
325/// the same way.
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub enum BlockedHostClass {
328    /// Loopback (`127.0.0.0/8`, `::1`, `localhost`, `0.0.0.0`).
329    Loopback,
330    /// RFC1918 / unique-local private ranges (`10/8`, `172.16/12`, `192.168/16`,
331    /// `fc00::/7`) and CGNAT shared space (`100.64.0.0/10`).
332    PrivateNetwork,
333    /// Link-local, including the cloud metadata endpoint (`169.254.0.0/16`,
334    /// notably `169.254.169.254`; `fe80::/10`; `*.internal`/metadata hostnames).
335    LinkLocalMetadata,
336    /// A non-http(s) scheme (e.g. `file:`, `ftp:`, `data:`).
337    DisallowedScheme,
338    /// Malformed URL or a URL with no host.
339    Malformed,
340    /// Other reserved/blocked address (broadcast, documentation/TEST-NET ranges,
341    /// `.local` hostnames) that isn't one of the more specific classes above.
342    OtherReserved,
343}
344
345impl BlockedHostClass {
346    /// A short, human-readable label naming ONLY the host class. Safe to embed
347    /// in a user/LLM-facing error: it contains no caller data.
348    pub fn label(self) -> &'static str {
349        match self {
350            BlockedHostClass::Loopback => "loopback address",
351            BlockedHostClass::PrivateNetwork => "private network",
352            BlockedHostClass::LinkLocalMetadata => "link-local/metadata address",
353            BlockedHostClass::DisallowedScheme => "disallowed scheme",
354            BlockedHostClass::Malformed => "malformed URL",
355            BlockedHostClass::OtherReserved => "reserved/blocked address",
356        }
357    }
358}
359
360/// Classify a blocked IPv4 address into a [`BlockedHostClass`]. Mirrors
361/// [`is_blocked_ipv4`] exactly (same ranges, same order) but reports the
362/// category instead of a bool. Returns `None` for a public address.
363fn classify_blocked_ipv4(ip: Ipv4Addr) -> Option<BlockedHostClass> {
364    let octets = ip.octets();
365
366    // Loopback: 127.0.0.0/8
367    if octets[0] == 127 {
368        return Some(BlockedHostClass::Loopback);
369    }
370    // Unspecified: 0.0.0.0 — treated as loopback-class (targets the local host).
371    if ip == Ipv4Addr::UNSPECIFIED {
372        return Some(BlockedHostClass::Loopback);
373    }
374    // Private: 10.0.0.0/8
375    if octets[0] == 10 {
376        return Some(BlockedHostClass::PrivateNetwork);
377    }
378    // Private: 172.16.0.0/12
379    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
380        return Some(BlockedHostClass::PrivateNetwork);
381    }
382    // Private: 192.168.0.0/16
383    if octets[0] == 192 && octets[1] == 168 {
384        return Some(BlockedHostClass::PrivateNetwork);
385    }
386    // Shared address space (CGNAT): 100.64.0.0/10
387    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
388        return Some(BlockedHostClass::PrivateNetwork);
389    }
390    // Link-local: 169.254.0.0/16 (includes cloud metadata 169.254.169.254)
391    if octets[0] == 169 && octets[1] == 254 {
392        return Some(BlockedHostClass::LinkLocalMetadata);
393    }
394    // Broadcast + documentation/TEST-NET ranges.
395    if ip == Ipv4Addr::BROADCAST
396        || (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
397        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
398        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
399    {
400        return Some(BlockedHostClass::OtherReserved);
401    }
402    None
403}
404
405/// Classify a blocked IPv6 address into a [`BlockedHostClass`]. Mirrors
406/// [`is_blocked_ipv6`] (IPv4-mapped addresses are unwrapped and classified as
407/// their embedded v4 class). Returns `None` for a public address.
408fn classify_blocked_ipv6(ip: Ipv6Addr) -> Option<BlockedHostClass> {
409    if ip.is_loopback() || ip.is_unspecified() {
410        return Some(BlockedHostClass::Loopback);
411    }
412    // IPv4-mapped (::ffff:a.b.c.d) — classify by the embedded IPv4 address.
413    if let Some(ipv4) = ip.to_ipv4_mapped() {
414        return classify_blocked_ipv4(ipv4);
415    }
416    let segments = ip.segments();
417    // Link-local: fe80::/10
418    if (segments[0] & 0xffc0) == 0xfe80 {
419        return Some(BlockedHostClass::LinkLocalMetadata);
420    }
421    // Unique local (private): fc00::/7
422    if (segments[0] & 0xfe00) == 0xfc00 {
423        return Some(BlockedHostClass::PrivateNetwork);
424    }
425    None
426}
427
428fn classify_blocked_ip(ip: IpAddr) -> Option<BlockedHostClass> {
429    match ip {
430        IpAddr::V4(v4) => classify_blocked_ipv4(v4),
431        IpAddr::V6(v6) => classify_blocked_ipv6(v6),
432    }
433}
434
435/// Classify a URL against the private-network policy and, if blocked, return the
436/// host CLASS — never the URL itself.
437///
438/// This is the shared, secret-safe entry point used by the `browser` tool to
439/// build request-level block errors. It applies the SAME policy as
440/// [`validate_url_for_ssrf`] (same scheme allow-list, same blocked-host names,
441/// same IP ranges, same DNS resolution), so the two tools never diverge.
442///
443/// Returns `None` when the URL is allowed (public http/https).
444pub fn classify_blocked_host(url: &str) -> Option<BlockedHostClass> {
445    let parsed = match reqwest::Url::parse(url) {
446        Ok(u) => u,
447        Err(_) => return Some(BlockedHostClass::Malformed),
448    };
449
450    match parsed.scheme() {
451        "http" | "https" => {}
452        _ => return Some(BlockedHostClass::DisallowedScheme),
453    }
454
455    let host = match parsed.host_str() {
456        Some(h) => h,
457        None => return Some(BlockedHostClass::Malformed),
458    };
459    let host_lower = host.to_lowercase();
460
461    // Named loopback / metadata hosts (mirrors BLOCKED_HOSTS in validate_url_for_ssrf).
462    match host_lower.as_str() {
463        "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0" => {
464            return Some(BlockedHostClass::Loopback);
465        }
466        "metadata.google.internal" | "metadata.goog" | "169.254.169.254" => {
467            return Some(BlockedHostClass::LinkLocalMetadata);
468        }
469        _ => {}
470    }
471    if host_lower.ends_with(".internal") {
472        return Some(BlockedHostClass::LinkLocalMetadata);
473    }
474    if host_lower.ends_with(".local") || host_lower.ends_with(".localhost") {
475        // `.localhost` resolves to loopback; `.local` is mDNS link-local-ish but
476        // historically grouped with internal names — report as reserved.
477        if host_lower.ends_with(".localhost") {
478            return Some(BlockedHostClass::Loopback);
479        }
480        return Some(BlockedHostClass::OtherReserved);
481    }
482
483    // Resolve and classify every address the host maps to.
484    let port = parsed.port().unwrap_or(match parsed.scheme() {
485        "https" => 443,
486        _ => 80,
487    });
488    let socket_addr = format!("{}:{}", host, port);
489    match socket_addr.to_socket_addrs() {
490        Ok(addrs) => {
491            for addr in addrs {
492                if let Some(class) = classify_blocked_ip(addr.ip()) {
493                    return Some(class);
494                }
495            }
496        }
497        Err(_) => {
498            // Couldn't resolve via DNS — try parsing the host as a raw IP.
499            if let Ok(ip) = host.parse::<IpAddr>()
500                && let Some(class) = classify_blocked_ip(ip)
501            {
502                return Some(class);
503            }
504            // Unresolvable non-IP host: let the request fail naturally (matches
505            // validate_url_for_ssrf). Not classified as blocked here.
506        }
507    }
508
509    None
510}
511
512/// What the owner approves to reach a site on this computer, or `None` when
513/// `url` is not loopback-only (public, private network, metadata and malformed
514/// targets are never approvable). A dev site's name is its own key;
515/// `localhost` and IP literals are shared by every local service, so their key
516/// includes the port.
517pub fn local_site_key(url: &str) -> Option<String> {
518    if !resolves_only_to_loopback(url) {
519        return None;
520    }
521    let parsed = reqwest::Url::parse(url).ok()?;
522    let host = parsed.host_str()?.to_lowercase();
523    let shared_name = host == "localhost"
524        || host
525            .trim_matches(['[', ']'])
526            .parse::<std::net::IpAddr>()
527            .is_ok();
528    if shared_name {
529        Some(format!("{host}:{}", parsed.port_or_known_default()?))
530    } else {
531        Some(host)
532    }
533}
534
535/// Whether `url` targets this computer and nothing else: blocked as loopback,
536/// with every address its host resolves to on loopback. A name that also maps
537/// to a private or metadata address is not loopback-only.
538fn resolves_only_to_loopback(url: &str) -> bool {
539    if classify_blocked_host(url) != Some(BlockedHostClass::Loopback) {
540        return false;
541    }
542    let Ok(parsed) = reqwest::Url::parse(url) else {
543        return false;
544    };
545    let Some(host) = parsed.host_str().map(str::to_lowercase) else {
546        return false;
547    };
548    if matches!(
549        host.as_str(),
550        "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0"
551    ) || host.ends_with(".localhost")
552    {
553        return true;
554    }
555    let Some(port) = parsed.port_or_known_default() else {
556        return false;
557    };
558    match format!("{host}:{port}").to_socket_addrs() {
559        Ok(addrs) => {
560            let mut addrs = addrs.peekable();
561            addrs.peek().is_some()
562                && addrs
563                    .all(|addr| classify_blocked_ip(addr.ip()) == Some(BlockedHostClass::Loopback))
564        }
565        // A literal IP in a form the resolver refused was classified above.
566        Err(_) => host
567            .parse::<IpAddr>()
568            .is_ok_and(|ip| classify_blocked_ip(ip) == Some(BlockedHostClass::Loopback)),
569    }
570}
571
572/// Whether `host` is a cloud metadata endpoint: by name, by address, or by
573/// what it resolves to. Narrower than [`BlockedHostClass::LinkLocalMetadata`],
574/// which also covers ordinary `*.internal` names.
575fn is_metadata_endpoint(host: &str, port: u16) -> bool {
576    let name = host.trim_end_matches('.').to_ascii_lowercase();
577    if matches!(name.as_str(), "metadata.google.internal" | "metadata.goog") {
578        return true;
579    }
580    let is_metadata_ip = |ip: IpAddr| match ip {
581        IpAddr::V4(v4) => v4.octets()[..2] == [169, 254],
582        IpAddr::V6(v6) => {
583            (v6.segments()[0] & 0xffc0) == 0xfe80
584                || v6 == Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254)
585                || v6
586                    .to_ipv4_mapped()
587                    .is_some_and(|v4| v4.octets()[..2] == [169, 254])
588        }
589    };
590    if let Ok(ip) = name.parse::<IpAddr>() {
591        return is_metadata_ip(ip);
592    }
593    (name.as_str(), port)
594        .to_socket_addrs()
595        .is_ok_and(|mut addrs| addrs.any(|addr| is_metadata_ip(addr.ip())))
596}
597
598/// Why a call to `target` (`host:port`) is refused under `reach`. Names only
599/// the class of address, never the target.
600fn network_refusal(reach: NetworkReach, target: &str) -> Option<&'static str> {
601    let (host, port) = target.rsplit_once(':')?;
602    let port: u16 = port.parse().ok()?;
603    if is_metadata_endpoint(host, port) {
604        return Some("cloud metadata endpoint");
605    }
606    if reach == NetworkReach::Any {
607        return None;
608    }
609    let authority = if host.contains(':') {
610        format!("[{host}]:{port}")
611    } else {
612        format!("{host}:{port}")
613    };
614    let class = classify_blocked_host(&format!("http://{authority}/"))?;
615    (reach == NetworkReach::PublicOnly || class != BlockedHostClass::Loopback)
616        .then(|| class.label())
617}
618
619/// Refuses calls whose declared egress names an address the tool may not
620/// reach, before anyone is asked. It sees the first request of a call: a
621/// redirect exists only once that request runs, so the tools recheck each
622/// hop themselves.
623#[derive(Debug, Clone, Default)]
624pub struct NetworkGuard {
625    reach: HashMap<String, NetworkReach>,
626}
627
628impl NetworkGuard {
629    pub fn new() -> Self {
630        Self::default()
631    }
632
633    /// State how far `tool` may reach. A tool not named reaches
634    /// [`NetworkReach::Any`].
635    pub fn reach(mut self, tool: impl Into<String>, reach: NetworkReach) -> Self {
636        self.reach.insert(tool.into(), reach);
637        self
638    }
639}
640
641#[async_trait]
642impl Hook for NetworkGuard {
643    async fn before_tool(
644        &self,
645        _ctx: &HookContext<'_>,
646        call: &ToolCall,
647        tool: &ToolInfo,
648    ) -> ToolDecision {
649        let reach = self.reach.get(&call.name).copied().unwrap_or_default();
650        let targets: Vec<String> = tool
651            .effects
652            .keys
653            .iter()
654            .filter(|key| key.class == EffectClass::Egress)
655            .map(|key| key.target.clone())
656            .collect();
657        if targets.is_empty() {
658            return ToolDecision::Allow;
659        }
660        // Classifying can resolve a name.
661        let refusal = tokio::task::spawn_blocking(move || {
662            targets
663                .iter()
664                .find_map(|target| network_refusal(reach, target))
665        })
666        .await
667        .unwrap_or(Some("address that could not be checked"));
668        match refusal {
669            Some(label) => ToolDecision::Deny {
670                reason: format!("Request blocked: target is a {label}"),
671            },
672            None => ToolDecision::Allow,
673        }
674    }
675}
676
677const BROWSER_USER_AGENT: &str =
678    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:142.0) Gecko/20100101 Firefox/142.0";
679
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
681enum Redirects {
682    SameHost,
683    Public,
684}
685
686/// Which redirects one client follows.
687enum Hops {
688    None,
689    SameHost(String),
690    Public,
691}
692
693/// Fetch a web page over http(s) and return its readable text.
694#[derive(Debug, Clone)]
695pub struct WebFetch {
696    max_chars: usize,
697    timeout: Duration,
698    use_proxy: bool,
699    user_agent: String,
700    browser_headers: bool,
701    allow_private: bool,
702    redirects: Redirects,
703    text: ToolText,
704    public_client: OnceLock<Result<Client, String>>,
705    no_redirect_client: OnceLock<Result<Client, String>>,
706}
707
708impl Default for WebFetch {
709    fn default() -> Self {
710        Self {
711            max_chars: DEFAULT_MAX_CHARS,
712            timeout: Duration::from_secs(30),
713            use_proxy: true,
714            user_agent: concat!("aidaemon-tools/", env!("CARGO_PKG_VERSION")).into(),
715            browser_headers: false,
716            allow_private: false,
717            redirects: Redirects::SameHost,
718            text: ToolText {
719                short: "Fetch a web page and return its readable text".into(),
720                schema: "Fetch a URL with HTTP GET (http/https only) and return the readable text \
721                         of the page; plain text and JSON are returned as is. A PDF or other \
722                         binary body is described (type and size), not shown. Private and \
723                         internal addresses are refused. Redirects to a different host are not \
724                         followed; the new location is reported instead."
725                    .into(),
726            },
727            public_client: OnceLock::new(),
728            no_redirect_client: OnceLock::new(),
729        }
730    }
731}
732
733impl WebFetch {
734    pub fn new() -> Self {
735        Self::default()
736    }
737
738    /// Default characters of text returned to the model.
739    pub fn max_chars(mut self, chars: usize) -> Self {
740        self.max_chars = chars.max(100);
741        self
742    }
743
744    pub fn timeout(mut self, timeout: Duration) -> Self {
745        self.timeout = timeout;
746        self
747    }
748
749    /// Ignore `HTTP(S)_PROXY` environment variables.
750    pub fn without_proxy(mut self) -> Self {
751        self.use_proxy = false;
752        self
753    }
754
755    pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
756        self.user_agent = agent.into();
757        self
758    }
759
760    /// Send a browser's user agent and headers, for sites that refuse other
761    /// clients.
762    pub fn browser_identity(mut self) -> Self {
763        self.user_agent = BROWSER_USER_AGENT.into();
764        self.browser_headers = true;
765        self
766    }
767
768    /// Follow redirects to other public hosts as well. Each hop is still
769    /// checked against the private-network policy.
770    pub fn follow_public_redirects(mut self) -> Self {
771        self.redirects = Redirects::Public;
772        self
773    }
774
775    /// Turn off the private-network policy, for a tool that is meant to reach
776    /// local services.
777    pub fn allow_private_hosts(mut self) -> Self {
778        self.allow_private = true;
779        self
780    }
781
782    /// Replace the model-facing descriptions.
783    pub fn with_text(mut self, text: ToolText) -> Self {
784        self.text = text;
785        self
786    }
787
788    fn build_client(&self, hops: Hops) -> Result<Client, String> {
789        let guarded = !self.allow_private;
790        let allowed = move |url: &str| !guarded || validate_url_for_ssrf(url).is_ok();
791        let policy = match hops {
792            Hops::None => Policy::none(),
793            Hops::Public => Policy::custom(move |attempt| {
794                if !allowed(attempt.url().as_str()) || attempt.previous().len() >= 10 {
795                    attempt.stop()
796                } else {
797                    attempt.follow()
798                }
799            }),
800            Hops::SameHost(host) => Policy::custom(move |attempt| {
801                if attempt.previous().len() >= 10 {
802                    attempt.error("too many redirects")
803                } else if attempt.url().host_str() == Some(host.as_str())
804                    && matches!(attempt.url().scheme(), "http" | "https")
805                    && allowed(attempt.url().as_str())
806                {
807                    attempt.follow()
808                } else {
809                    attempt.stop()
810                }
811            }),
812        };
813        let mut builder = Client::builder()
814            .timeout(self.timeout)
815            .redirect(policy)
816            .user_agent(&self.user_agent);
817        if guarded {
818            builder = builder.dns_resolver(std::sync::Arc::new(PublicOnlyResolver));
819        }
820        if self.browser_headers {
821            builder = builder.default_headers(browser_headers());
822        }
823        if !self.use_proxy {
824            builder = builder.no_proxy();
825        }
826        builder
827            .build()
828            .map_err(|error| format!("cannot build HTTP client: {error}"))
829    }
830
831    fn client_for(&self, url: &str, follow: bool) -> anyhow::Result<Client> {
832        let cached = |cell: &OnceLock<Result<Client, String>>, hops| {
833            cell.get_or_init(|| self.build_client(hops)).clone()
834        };
835        let client = match (follow, self.redirects) {
836            (false, _) => cached(&self.no_redirect_client, Hops::None),
837            (true, Redirects::Public) => cached(&self.public_client, Hops::Public),
838            (true, Redirects::SameHost) => {
839                let host = Url::parse(url)?.host_str().unwrap_or_default().to_string();
840                self.build_client(Hops::SameHost(host))
841            }
842        };
843        client.map_err(anyhow::Error::msg)
844    }
845
846    /// Check the policy, send the request and read the capped body.
847    async fn fetch(&self, url: &str, follow: bool, read_error_body: bool) -> anyhow::Result<Fetch> {
848        if !self.allow_private
849            && let Err(reason) = validate_url_for_ssrf(url)
850        {
851            return Ok(Fetch::Blocked(reason));
852        }
853        let response = self.client_for(url, follow)?.get(url).send().await?;
854        let status = response.status();
855        let final_url = response.url().to_string();
856        let header = |name| {
857            response
858                .headers()
859                .get(name)
860                .and_then(|value: &reqwest::header::HeaderValue| value.to_str().ok())
861                .map(str::to_string)
862        };
863        let content_type = header(reqwest::header::CONTENT_TYPE).unwrap_or_default();
864        let location = header(reqwest::header::LOCATION);
865        let (body, body_truncated) = if status.is_success() || read_error_body {
866            read_body_capped(response, MAX_FETCH_BODY_BYTES).await?
867        } else {
868            (Vec::new(), false)
869        };
870        Ok(Fetch::Response(Fetched {
871            status,
872            final_url,
873            content_type,
874            location,
875            body,
876            body_truncated,
877        }))
878    }
879}
880
881enum Fetch {
882    Blocked(String),
883    Response(Fetched),
884}
885
886struct Fetched {
887    status: StatusCode,
888    final_url: String,
889    content_type: String,
890    location: Option<String>,
891    body: Vec<u8>,
892    body_truncated: bool,
893}
894
895fn browser_headers() -> reqwest::header::HeaderMap {
896    let mut h = reqwest::header::HeaderMap::new();
897    h.insert(
898        "Accept",
899        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
900            .parse()
901            .unwrap(),
902    );
903    h.insert("Accept-Language", "en-US,en;q=0.5".parse().unwrap());
904    h.insert("Accept-Encoding", "gzip, deflate, br".parse().unwrap());
905    h.insert("DNT", "1".parse().unwrap());
906    h.insert("Upgrade-Insecure-Requests", "1".parse().unwrap());
907    h.insert("Sec-Fetch-Dest", "document".parse().unwrap());
908    h.insert("Sec-Fetch-Mode", "navigate".parse().unwrap());
909    h.insert("Sec-Fetch-Site", "none".parse().unwrap());
910    h.insert("Sec-Fetch-User", "?1".parse().unwrap());
911    h.insert("Sec-GPC", "1".parse().unwrap());
912    h
913}
914
915/// An HTTP client with browser-like headers whose redirects are re-validated
916/// against the private-network policy.
917pub fn build_browser_client() -> Client {
918    WebFetch::new()
919        .browser_identity()
920        .build_client(Hops::Public)
921        .expect("failed to build browser HTTP client")
922}
923
924fn parse_url(raw: &str) -> Result<Url, String> {
925    let url = Url::parse(raw.trim()).map_err(|e| {
926        format!("invalid URL `{raw}`: {e}. Give a full URL such as https://example.com/page")
927    })?;
928    match url.scheme() {
929        "http" | "https" => {}
930        other => return Err(format!("unsupported scheme `{other}`; only http and https")),
931    }
932    if url.host_str().is_none() {
933        return Err(format!("URL `{raw}` has no host"));
934    }
935    Ok(url)
936}
937
938/// The one effect of fetching `url`.
939fn url_effect(url: &Url) -> Option<EffectKey> {
940    // `Url` brackets an IPv6 host; the effect target does not.
941    let host = url
942        .host_str()?
943        .trim_start_matches('[')
944        .trim_end_matches(']');
945    Some(EffectKey::egress(url.scheme(), host, url.port()))
946}
947
948#[derive(Deserialize)]
949#[serde(deny_unknown_fields)]
950struct FetchArgs {
951    url: String,
952    max_chars: Option<usize>,
953    #[serde(default)]
954    offset: usize,
955}
956
957#[async_trait]
958impl OutcomeTool for WebFetch {
959    fn name(&self) -> &str {
960        "web_fetch"
961    }
962
963    fn description(&self) -> &str {
964        &self.text.short
965    }
966
967    fn schema(&self) -> Value {
968        json!({
969            "name": "web_fetch",
970            "description": self.text.schema,
971            "parameters": {
972                "type": "object",
973                "properties": {
974                    "url": {
975                        "type": "string",
976                        "description": "The URL to fetch"
977                    },
978                    "max_chars": {
979                        "type": "integer",
980                        "description": "Maximum characters to return (default 20000, max 50000)"
981                    },
982                    "offset": {
983                        "type": "integer",
984                        "description": "Characters of page text to skip, to read past a truncated reply"
985                    }
986                },
987                "required": ["url"],
988                "additionalProperties": false
989            }
990        })
991    }
992
993    async fn execute(
994        &self,
995        arguments: &str,
996        facts: &ToolCallContext,
997    ) -> anyhow::Result<ToolCallOutcome> {
998        let args: Value = serde_json::from_str(arguments)?;
999        let url = args["url"]
1000            .as_str()
1001            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: url"))?;
1002        let max_chars = args["max_chars"]
1003            .as_u64()
1004            .map(|n| n as usize)
1005            .unwrap_or(self.max_chars)
1006            .clamp(1, MAX_MAX_CHARS);
1007
1008        let offset = args["offset"].as_u64().unwrap_or(0) as usize;
1009
1010        let fetched = match self.fetch(url, !facts.mandate_execution, true).await? {
1011            Fetch::Blocked(reason) => {
1012                return Ok(ToolCallOutcome::from_output(format!(
1013                    "Request blocked: {reason}"
1014                )));
1015            }
1016            Fetch::Response(fetched) => fetched,
1017        };
1018        let reply = fetch_reply(&fetched, max_chars, offset);
1019        let output = if reply.ok {
1020            format!("{}\n{}", fetch_header(url, &fetched), reply.text)
1021        } else {
1022            reply.text
1023        };
1024        Ok(ToolCallOutcome {
1025            output,
1026            metadata: ToolCallMetadata {
1027                truncation: reply.truncation,
1028                ..Default::default()
1029            },
1030            finish: None,
1031        })
1032    }
1033}
1034
1035#[async_trait]
1036impl Tool for WebFetch {
1037    fn spec(&self) -> aidaemon_core::ToolSpec {
1038        spec_of(self)
1039    }
1040
1041    /// A read, but the request (its URL, query included) leaves the
1042    /// machine, so outbound policies such as an egress secret scan see it.
1043    fn annotations(&self) -> ToolAnnotations {
1044        ToolAnnotations {
1045            egress: true,
1046            ..ToolAnnotations::READ_ONLY
1047        }
1048    }
1049
1050    fn outbound(&self, arguments: &Value) -> aidaemon_core::Outbound {
1051        outbound_of_url(arguments)
1052    }
1053
1054    /// The host contacted. An unparsable URL is refused by `validate` before
1055    /// any policy runs; its effects are unknown.
1056    fn effects(&self, arguments: &Value) -> CallEffects {
1057        arguments
1058            .get("url")
1059            .and_then(Value::as_str)
1060            .and_then(|url| parse_url(url).ok())
1061            .and_then(|url| url_effect(&url))
1062            .map_or_else(CallEffects::unknown, |key| CallEffects {
1063                keys: vec![key],
1064                complete: true,
1065                understood: false,
1066            })
1067    }
1068
1069    fn validate(&self, arguments: &Value) -> Result<(), String> {
1070        let url = arguments
1071            .get("url")
1072            .and_then(Value::as_str)
1073            .ok_or("`url` is required and must be a string")?;
1074        parse_url(url).map(|_| ())
1075    }
1076
1077    fn access(&self, arguments: &Value) -> AccessManifest {
1078        let host = arguments
1079            .get("url")
1080            .and_then(Value::as_str)
1081            .and_then(|u| parse_url(u).ok())
1082            .and_then(|u| u.host_str().map(str::to_string));
1083        AccessManifest {
1084            hosts: host.into_iter().collect(),
1085            ..Default::default()
1086        }
1087    }
1088
1089    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
1090        let args: FetchArgs = match parse_args("web_fetch", arguments) {
1091            Ok(a) => a,
1092            Err(e) => return Ok(fail(e)),
1093        };
1094        let url = match parse_url(&args.url) {
1095            Ok(u) => u,
1096            Err(e) => return Ok(fail(e)),
1097        };
1098        let max_chars = args
1099            .max_chars
1100            .unwrap_or(self.max_chars)
1101            .clamp(1, MAX_MAX_CHARS.max(self.max_chars));
1102        let host = url.host_str().unwrap_or_default().to_string();
1103        let result = tokio::select! {
1104            result = self.fetch(url.as_str(), true, true) => result,
1105            _ = ctx.cancel.cancelled() => return Ok(fail("cancelled")),
1106        };
1107        let fetched = match result {
1108            Ok(Fetch::Blocked(reason)) => {
1109                return Ok(fail(format!("Request blocked: {reason}"))
1110                    .with_details(json!({"url": url.as_str(), "host": host})));
1111            }
1112            Ok(Fetch::Response(fetched)) => fetched,
1113            Err(e) => {
1114                return Ok(fail(format!("request to {url} failed: {e}"))
1115                    .with_details(json!({"url": url.as_str(), "host": host})));
1116            }
1117        };
1118        let Fetched {
1119            status,
1120            final_url,
1121            content_type,
1122            location,
1123            body,
1124            body_truncated,
1125        } = fetched;
1126
1127        let mut details = json!({
1128            "url": url.as_str(),
1129            "final_url": final_url,
1130            "host": host,
1131            "status": status.as_u16(),
1132            "content_type": content_type,
1133            "bytes": body.len(),
1134        });
1135
1136        if status.is_redirection() {
1137            let target = location.unwrap_or_else(|| "(no Location header)".into());
1138            details["location"] = json!(target);
1139            return Ok(fail(format!(
1140                "HTTP {status}: {final_url} redirects to {target}, which was not followed. \
1141                 Fetch that URL explicitly if it is the page you want."
1142            ))
1143            .with_details(details));
1144        }
1145
1146        let fetched = Fetched {
1147            status,
1148            final_url,
1149            content_type,
1150            location: None,
1151            body,
1152            body_truncated,
1153        };
1154        let reply = fetch_reply(&fetched, max_chars, args.offset);
1155        let cut = reply.truncation.is_some() || fetched.body_truncated;
1156        details["truncated"] = json!(cut);
1157        if !reply.ok {
1158            return Ok(fail(reply.text).with_details(details));
1159        }
1160        let mut text = reply.text;
1161        if let Some(info) = &reply.truncation {
1162            text.push_str(&format!(
1163                "\n\n[Content truncated to {max_chars} characters. Fetch again with offset={} \
1164                 for the next part ({} characters in all).]",
1165                args.offset + info.shown_chars,
1166                info.total_chars
1167            ));
1168        } else if fetched.body_truncated {
1169            text.push_str(&format!(
1170                "\n\n[Content truncated: the body was larger than {MAX_FETCH_BODY_BYTES} bytes.]"
1171            ));
1172        }
1173        Ok(
1174            ToolOutput::text(format!("{}\n{text}", fetch_header(url.as_str(), &fetched)))
1175                .with_details(details),
1176        )
1177    }
1178}
1179
1180/// A fetch sends its URL and nothing else.
1181fn outbound_of_url(arguments: &Value) -> aidaemon_core::Outbound {
1182    match arguments.get("url").and_then(Value::as_str) {
1183        Some(url) => aidaemon_core::Outbound::Exact(vec![url.to_string()]),
1184        None => aidaemon_core::Outbound::Composed,
1185    }
1186}
1187
1188impl crate::semantics::ToolSemantics for WebFetch {
1189    fn call_outbound(&self, arguments: &str) -> aidaemon_core::Outbound {
1190        serde_json::from_str::<Value>(arguments).map_or(aidaemon_core::Outbound::Composed, |args| {
1191            outbound_of_url(&args)
1192        })
1193    }
1194
1195    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
1196        crate::semantics::ToolDispatchFacts {
1197            offering: crate::semantics::Offering::Core,
1198            network_reach: crate::semantics::NetworkReach::PublicOnly,
1199            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
1200            recap: crate::semantics::RecapKind::ExternalRead,
1201            activity: crate::semantics::ToolActivity::Fixed(aidaemon_core::card::ActivityKind::Web),
1202            status_label: Some("fetching a page"),
1203            result_fit: crate::semantics::ResultFit {
1204                compact_json: true,
1205                ..Default::default()
1206            },
1207            evidence: crate::semantics::EvidenceSource::RemoteRead,
1208            semantic_scope: Some(crate::semantics::ToolSemanticScope::ExternalRemote),
1209            ..Default::default()
1210        }
1211    }
1212
1213    fn capabilities(&self) -> ToolCapabilities {
1214        ToolCapabilities {
1215            read_only: true,
1216            external_side_effect: true,
1217            needs_approval: false,
1218            idempotent: true,
1219            high_impact_write: false,
1220        }
1221    }
1222
1223    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
1224        let url = serde_json::from_str::<Value>(arguments)
1225            .ok()
1226            .and_then(|args| {
1227                args.get("url")
1228                    .and_then(|value| value.as_str())
1229                    .map(str::to_string)
1230            })
1231            .unwrap_or_default();
1232
1233        ToolCallSemantics::observation()
1234            .with_operation(crate::semantics::ToolCallOperation::Get)
1235            .with_verification_mode(ToolVerificationMode::ResultContent)
1236            .with_target_hint(ToolTargetHintKind::Url, url)
1237    }
1238
1239    /// The page's host.
1240    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
1241        serde_json::from_str::<Value>(arguments)
1242            .ok()
1243            .and_then(|args| url_effect(&parse_url(args.get("url")?.as_str()?).ok()?))
1244            .map_or_else(aidaemon_core::CallEffects::unknown, |key| {
1245                aidaemon_core::CallEffects {
1246                    keys: vec![key],
1247                    complete: true,
1248                    understood: false,
1249                }
1250            })
1251    }
1252}
1253
1254fn looks_like_html(body: &[u8]) -> bool {
1255    let head = String::from_utf8_lossy(&body[..body.len().min(512)]).to_ascii_lowercase();
1256    head.contains("<html") || head.contains("<!doctype html")
1257}
1258
1259/// What a fetched body is: by its declared type, sniffed when undeclared.
1260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1261enum BodyKind {
1262    Html,
1263    Text,
1264    Pdf,
1265    Binary,
1266}
1267
1268fn body_kind(content_type: &str, body: &[u8]) -> BodyKind {
1269    let lower = content_type.to_ascii_lowercase();
1270    if lower.contains("pdf") || (lower.is_empty() && body.starts_with(b"%PDF-")) {
1271        BodyKind::Pdf
1272    } else if lower.contains("html") || (lower.is_empty() && looks_like_html(body)) {
1273        BodyKind::Html
1274    } else if lower.starts_with("text/")
1275        || lower.contains("json")
1276        || lower.contains("xml")
1277        || lower.contains("javascript")
1278        || (lower.is_empty() && std::str::from_utf8(&body[..body.len().min(1024)]).is_ok())
1279    {
1280        BodyKind::Text
1281    } else {
1282        BodyKind::Binary
1283    }
1284}
1285
1286/// The model's view of one fetch, for both entry points: the page's text
1287/// (from `offset`, cut at `max_chars`, with the cut as metadata), or an
1288/// error that says why there is no text.
1289struct FetchReply {
1290    ok: bool,
1291    text: String,
1292    truncation: Option<crate::semantics::TruncationInfo>,
1293}
1294
1295fn fetch_reply(fetched: &Fetched, max_chars: usize, offset: usize) -> FetchReply {
1296    let url = fetched.final_url.as_str();
1297    let status = fetched.status;
1298    let error = |text: String| FetchReply {
1299        ok: false,
1300        text,
1301        truncation: None,
1302    };
1303    if status.is_redirection() {
1304        let target = fetched
1305            .location
1306            .as_deref()
1307            .unwrap_or("(no Location header)");
1308        return error(format!(
1309            "HTTP {status}: {url} redirects to {target}, which was not followed. Fetch that URL \
1310             explicitly if it is the page you want."
1311        ));
1312    }
1313    let kind = body_kind(&fetched.content_type, &fetched.body);
1314    let bytes = fetched.body.len();
1315    let content_type = if fetched.content_type.is_empty() {
1316        "an undeclared type"
1317    } else {
1318        fetched.content_type.as_str()
1319    };
1320    match kind {
1321        BodyKind::Pdf if status.is_success() => {
1322            return error(format!(
1323                "{url} is a PDF document ({bytes} bytes, {content_type}). web_fetch does not \
1324                 extract PDF text: download the file to the workspace and read it with read_file, \
1325                 which says how to extract its text."
1326            ));
1327        }
1328        BodyKind::Binary if status.is_success() => {
1329            return error(format!(
1330                "{url} returned binary content, {bytes} bytes, type {content_type}, which is not \
1331                 text and cannot be shown."
1332            ));
1333        }
1334        _ => {}
1335    }
1336    let raw = String::from_utf8_lossy(&fetched.body);
1337    if !status.is_success() {
1338        let text = match kind {
1339            BodyKind::Html => extract_page_text(&raw, url),
1340            BodyKind::Text => raw.into_owned(),
1341            BodyKind::Pdf | BodyKind::Binary => String::new(),
1342        };
1343        let (snippet, _) = truncate_chars(text.trim(), 2000);
1344        return error(format!("HTTP {status} from {url}.\n\n{snippet}"));
1345    }
1346    let (text, truncation) = match kind {
1347        BodyKind::Html => build_fetch_reply_at(url, &raw, max_chars, offset),
1348        _ => format_fetch_window(url, &raw, max_chars, offset),
1349    };
1350    FetchReply {
1351        ok: true,
1352        text,
1353        truncation,
1354    }
1355}
1356
1357/// Extracted text shorter than this (on a large page) means extraction
1358/// failed, not that the page is thin.
1359const MIN_EXTRACTED_CHARS: usize = 200;
1360/// Only pages at least this large trigger the extraction-failure check —
1361/// genuinely tiny pages legitimately yield little text.
1362const MIN_HTML_FOR_EXTRACTION_CHECK: usize = 10_000;
1363
1364/// Full fetch-reply pipeline: strip non-visible blocks, extract readable
1365/// text, detect failed extraction, format with truncation honesty.
1366#[cfg(test)]
1367fn build_fetch_reply(
1368    url: &str,
1369    html: &str,
1370    max_chars: usize,
1371) -> (String, Option<crate::semantics::TruncationInfo>) {
1372    build_fetch_reply_at(url, html, max_chars, 0)
1373}
1374
1375fn build_fetch_reply_at(
1376    url: &str,
1377    html: &str,
1378    max_chars: usize,
1379    offset: usize,
1380) -> (String, Option<crate::semantics::TruncationInfo>) {
1381    let text = extract_page_text(html, url);
1382    let trimmed = text.trim();
1383    if trimmed.chars().count() < MIN_EXTRACTED_CHARS && html.len() >= MIN_HTML_FOR_EXTRACTION_CHECK
1384    {
1385        // A large page that yields almost no readable text is the signature
1386        // of a JavaScript-rendered (or bot-walled) page. Without this notice
1387        // the model treats the empty result as the page's actual content —
1388        // or worse, re-fetches the same URL expecting a different outcome.
1389        // This is a distinct extraction-failure signal, not truncation, so it
1390        // stays an embedded instructional marker (no TruncationInfo applies).
1391        return (
1392            format!(
1393                "Content from {}:\n\n{}\n\n[⚠ EXTRACTION FAILED — this {} KB page yielded only {} \
1394                 characters of readable text; it is likely JavaScript-rendered or blocking \
1395                 non-browser clients. Do NOT treat this as the page's content, and do NOT re-fetch \
1396                 this same URL — the result will not change. Fetch a different source URL from your \
1397                 search results, or use a browser-based tool on this URL if one is available.]",
1398                url,
1399                trimmed,
1400                html.len() / 1024,
1401                trimmed.chars().count(),
1402            ),
1403            None,
1404        );
1405    }
1406    format_fetch_window(url, &text, max_chars, offset)
1407}
1408
1409/// Extract readable page text: readability first, raw-HTML-to-markdown
1410/// fallback. `<script>`/`<style>`/`<noscript>` blocks are stripped FIRST —
1411/// both paths can leak inline script bodies into the "text" (observed:
1412/// Wikipedia fetches returning JS soup that consumed the whole max_chars
1413/// window before any article content).
1414fn extract_page_text(html: &str, url: &str) -> String {
1415    let text = extract_page_body(html, url);
1416    // Readability keeps the article body and drops a heading that repeats
1417    // the page title, so a page whose one heading is its title came back
1418    // without it (live 2026-11-20: every "what is the page's heading?" turn
1419    // re-fetched the page with curl two or three times to find it). The
1420    // page's heading leads the text when the text lacks it.
1421    match page_heading(html) {
1422        Some(heading) if !text.contains(&heading) => format!("# {heading}\n\n{text}"),
1423        _ => text,
1424    }
1425}
1426
1427/// The page's main heading as plain text: its first `<h1>`, else its
1428/// `<title>` (HTML markup, a machine format).
1429fn page_heading(html: &str) -> Option<String> {
1430    let cleaned = strip_nonvisible_blocks(html);
1431    ["h1", "title"]
1432        .into_iter()
1433        .find_map(|tag| first_element_text(&cleaned, tag))
1434}
1435
1436/// The text inside the first `<tag ...>...</tag>`, tags removed, entities
1437/// decoded and whitespace collapsed; `None` when absent or empty.
1438fn first_element_text(html: &str, tag: &str) -> Option<String> {
1439    let bytes = html.as_bytes();
1440    let open = format!("<{tag}");
1441    let mut from = 0;
1442    let start = loop {
1443        let at = find_ascii_ci(bytes, open.as_bytes(), from)?;
1444        // "<h1" must end the tag name ("<h10" or "<titles" is another tag).
1445        if matches!(
1446            bytes.get(at + open.len()),
1447            Some(b' ') | Some(b'>') | Some(b'\t') | Some(b'\n') | Some(b'\r')
1448        ) {
1449            break at;
1450        }
1451        from = at + open.len();
1452    };
1453    let inner_start = start + html[start..].find('>')? + 1;
1454    let close = format!("</{tag}");
1455    let inner_end = find_ascii_ci(bytes, close.as_bytes(), inner_start)?;
1456    let inner = htmd::convert(&html[inner_start..inner_end]).unwrap_or_default();
1457    let text = inner
1458        .replace(['*', '_', '#', '`'], "")
1459        .split_whitespace()
1460        .collect::<Vec<_>>()
1461        .join(" ");
1462    (!text.is_empty()).then_some(text)
1463}
1464
1465/// [`extract_page_text`] before the page's heading is added.
1466fn extract_page_body(html: &str, url: &str) -> String {
1467    let cleaned = strip_nonvisible_blocks(html);
1468    let parsed_url = reqwest::Url::parse(url)
1469        .unwrap_or_else(|_| reqwest::Url::parse("http://example.com").unwrap());
1470    let mut cursor = Cursor::new(cleaned.as_bytes());
1471    let full_page = || htmd::convert(&cleaned).unwrap_or_else(|_| cleaned.clone());
1472    match llm_readability::extractor::extract(&mut cursor, &parsed_url) {
1473        Ok(product) if !product.text.trim().is_empty() => {
1474            // Readability's plain text runs its blocks together ("Example
1475            // DomainThis domain ..."); its HTML as markdown keeps headings
1476            // and paragraphs apart.
1477            let article = htmd::convert(&strip_nonvisible_blocks(&product.content))
1478                .ok()
1479                .filter(|markdown| !markdown.trim().is_empty())
1480                .unwrap_or_else(|| product.text.clone());
1481            // Readability keeps one block. On an article that is the content;
1482            // on a listing page (downloads, release lists, tables) it is a
1483            // side section, and the answer is in what it dropped. A short
1484            // extract cut from a much larger page gets the whole page.
1485            let article_chars = article.trim().chars().count();
1486            if article_chars >= MIN_ARTICLE_CHARS {
1487                return article;
1488            }
1489            let full = full_page();
1490            let full_chars = full.trim().chars().count();
1491            if (article_chars as f64) >= MIN_ARTICLE_COVERAGE * full_chars as f64 {
1492                article
1493            } else {
1494                full
1495            }
1496        }
1497        _ => full_page(),
1498    }
1499}
1500
1501/// Readability output at least this long is an article in its own right.
1502const MIN_ARTICLE_CHARS: usize = 8_000;
1503/// A shorter extract must cover at least this share of the page's text to
1504/// count as its main content.
1505const MIN_ARTICLE_COVERAGE: f64 = 0.35;
1506
1507/// Remove `<script>`, `<style>`, and `<noscript>` blocks (case-insensitive,
1508/// unclosed blocks dropped to end-of-input).
1509fn strip_nonvisible_blocks(html: &str) -> String {
1510    let mut out = html.to_string();
1511    for tag in ["script", "style", "noscript"] {
1512        out = strip_tag_blocks(&out, tag);
1513    }
1514    out
1515}
1516
1517fn strip_tag_blocks(html: &str, tag: &str) -> String {
1518    let open = format!("<{}", tag);
1519    let close = format!("</{}>", tag);
1520    let bytes = html.as_bytes();
1521    let mut out = String::with_capacity(html.len());
1522    let mut pos = 0;
1523    while let Some(start) = find_ascii_ci(bytes, open.as_bytes(), pos) {
1524        // The byte after "<tag" must terminate the tag name, else "<scriptx"
1525        // or a "<style-like" element would match.
1526        let after = bytes.get(start + open.len());
1527        if !matches!(
1528            after,
1529            Some(b' ') | Some(b'>') | Some(b'\t') | Some(b'\n') | Some(b'/')
1530        ) {
1531            out.push_str(&html[pos..start + open.len()]);
1532            pos = start + open.len();
1533            continue;
1534        }
1535        out.push_str(&html[pos..start]);
1536        match find_ascii_ci(bytes, close.as_bytes(), start) {
1537            Some(end) => pos = end + close.len(),
1538            None => {
1539                pos = html.len();
1540                break;
1541            }
1542        }
1543    }
1544    out.push_str(&html[pos..]);
1545    out
1546}
1547
1548/// ASCII-case-insensitive substring search from `from`. Byte positions are
1549/// safe to slice with because the needles are pure ASCII.
1550fn find_ascii_ci(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
1551    if from >= haystack.len() || needle.is_empty() {
1552        return None;
1553    }
1554    haystack[from..]
1555        .windows(needle.len())
1556        .position(|w| w.eq_ignore_ascii_case(needle))
1557        .map(|i| i + from)
1558}
1559
1560/// Format extracted page text, truncating to `max_chars` (bytes, floored to a
1561/// char boundary). Truncation is reported via the returned `TruncationInfo`,
1562/// not embedded in the text — the agent loop renders the instructional
1563/// notice from that metadata (see `crate::utils::render_truncation_notice`),
1564/// so text-scanning consumers (classifiers, summaries) always see clean
1565/// output. A passive "[Truncated]" marker baked into the text is routinely
1566/// ignored and the model fabricates the omitted content (e.g. inventing the
1567/// rest of a roster) — this is why the notice must reach the model through
1568/// the loop's instructional rendering rather than raw tool output.
1569#[cfg(test)]
1570fn format_fetch_result(
1571    url: &str,
1572    text: &str,
1573    max_chars: usize,
1574) -> (String, Option<crate::semantics::TruncationInfo>) {
1575    format_fetch_window(url, text, max_chars, 0)
1576}
1577
1578/// One line stating what a fetch reached: status, content type, the final
1579/// URL (and the URL asked for when a redirect moved it) and the page title,
1580/// so the model need not check them with another request (live 2026-11-14
1581/// to 11-20: 51 curl status checks, 9 right after a fetch).
1582fn fetch_header(requested: &str, fetched: &Fetched) -> String {
1583    let same = |a: &str, b: &str| a.trim_end_matches('/') == b.trim_end_matches('/');
1584    let mut parts = vec![
1585        format!("HTTP {}", fetched.status.as_u16()),
1586        fetched.content_type.clone(),
1587    ];
1588    if same(requested, &fetched.final_url) {
1589        parts.push(fetched.final_url.clone());
1590    } else {
1591        parts.push(format!(
1592            "{} (redirected from {requested})",
1593            fetched.final_url
1594        ));
1595    }
1596    if fetched.content_type.contains("html")
1597        && let Some(title) = first_element_text(&String::from_utf8_lossy(&fetched.body), "title")
1598    {
1599        parts.push(format!("title \"{title}\""));
1600    }
1601    parts.join(" \u{b7} ")
1602}
1603
1604/// `max_chars` of `text` starting at character `offset`. A cut is reported
1605/// as metadata, with the offset that continues it.
1606fn format_fetch_window(
1607    url: &str,
1608    text: &str,
1609    max_chars: usize,
1610    offset: usize,
1611) -> (String, Option<crate::semantics::TruncationInfo>) {
1612    let total_chars = text.chars().count();
1613    let mut result = format!("Content from {}:\n\n", url);
1614    if offset >= total_chars && offset > 0 {
1615        result.push_str(&format!(
1616            "[offset {offset} is past the end: the page text has {total_chars} characters.]"
1617        ));
1618        return (result, None);
1619    }
1620    let window: String = text.chars().skip(offset).take(max_chars).collect();
1621    let shown_chars = window.chars().count();
1622    result.push_str(&window);
1623    if offset + shown_chars < total_chars {
1624        let truncation = crate::semantics::TruncationInfo {
1625            shown_chars,
1626            total_chars,
1627            remediation_hint: Some(format!(
1628                "If the answer may be in the omitted part, fetch again with offset={} (or a \
1629                 larger max_chars, up to 50000), or fetch a more specific page; if the full \
1630                 content is still not visible, tell the user the page was longer than you \
1631                 could read.",
1632                offset + shown_chars
1633            )),
1634        };
1635        (result, Some(truncation))
1636    } else {
1637        (result, None)
1638    }
1639}
1640
1641#[cfg(test)]
1642mod tests {
1643    use super::*;
1644
1645    #[tokio::test]
1646    async fn a_name_resolving_to_a_blocked_address_is_refused_at_connection() {
1647        use reqwest::dns::Resolve;
1648        use std::str::FromStr;
1649        let name = reqwest::dns::Name::from_str("localhost").unwrap();
1650        let error = match PublicOnlyResolver.resolve(name).await {
1651            Ok(_) => panic!("localhost must not resolve"),
1652            Err(error) => error.to_string(),
1653        };
1654        assert!(error.contains("blocked address"), "{error}");
1655    }
1656    use crate::testutil::ctx;
1657    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1658
1659    /// Addresses that reach a private or local host through an embedding
1660    /// (IPv4-compatible, NAT64, 6to4) or a reserved range are blocked;
1661    /// ordinary public addresses are not.
1662    #[test]
1663    fn embedded_and_reserved_addresses_are_blocked() {
1664        for blocked in [
1665            "100.100.100.100",
1666            "0.1.2.3",
1667            "198.18.0.1",
1668            "224.0.0.1",
1669            "240.0.0.1",
1670            "::127.0.0.1",
1671            "::ffff:10.0.0.1",
1672            "64:ff9b::a9fe:a9fe",
1673            "64:ff9b::7f00:1",
1674            "64:ff9b:1::1",
1675            "2002:7f00:1::1",
1676            "2002:a9fe:a9fe::",
1677            "2001:0:4136:e378:8000:63bf:3fff:fdd2",
1678            "fec0::1",
1679            "ff02::1",
1680            "100::1",
1681        ] {
1682            let ip: IpAddr = blocked.parse().unwrap();
1683            assert!(is_blocked_ip(ip), "{blocked}");
1684        }
1685        for public in [
1686            "93.184.216.34",
1687            "2606:4700::6810:84e5",
1688            "64:ff9b::5db8:d822",
1689            "2002:5db8:d822::1",
1690        ] {
1691            let ip: IpAddr = public.parse().unwrap();
1692            assert!(!is_blocked_ip(ip), "{public}");
1693        }
1694    }
1695
1696    #[test]
1697    fn web_fetch_declares_its_egress_host() {
1698        let tool = WebFetch::new();
1699        assert!(tool.annotations().egress);
1700        assert!(tool.annotations().read_only);
1701        let effects = tool.effects(&json!({"url": "https://Docs.Example.Invalid/guide?q=1"}));
1702        assert!(effects.complete);
1703        assert_eq!(
1704            effects.keys,
1705            vec![EffectKey::egress("https", "docs.example.invalid", None)]
1706        );
1707        let local = tool.effects(&json!({"url": "http://[::1]:8765/status"}));
1708        assert_eq!(
1709            local.keys,
1710            vec![EffectKey::egress("http", "::1", Some(8765))]
1711        );
1712        assert!(!tool.effects(&json!({"url": "not a url"})).complete);
1713    }
1714
1715    /// Serve canned responses on a local port: path -> (status line, content type, body).
1716    async fn serve(routes: Vec<(&'static str, &'static str, &'static str, String)>) -> String {
1717        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1718        let addr = listener.local_addr().unwrap();
1719        tokio::spawn(async move {
1720            loop {
1721                let Ok((mut sock, _)) = listener.accept().await else {
1722                    break;
1723                };
1724                let routes = routes.clone();
1725                tokio::spawn(async move {
1726                    let mut buf = vec![0u8; 4096];
1727                    let n = sock.read(&mut buf).await.unwrap_or(0);
1728                    let req = String::from_utf8_lossy(&buf[..n]);
1729                    let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();
1730                    let (status, ctype, body) = routes
1731                        .iter()
1732                        .find(|(p, ..)| *p == path)
1733                        .map(|(_, s, c, b)| (*s, *c, b.clone()))
1734                        .unwrap_or(("404 Not Found", "text/plain", "missing".to_string()));
1735                    let extra = if status.starts_with("302") {
1736                        format!("Location: {body}\r\n")
1737                    } else {
1738                        String::new()
1739                    };
1740                    let resp = format!(
1741                        "HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
1742                        body.len()
1743                    );
1744                    let _ = sock.write_all(resp.as_bytes()).await;
1745                    let _ = sock.shutdown().await;
1746                });
1747            }
1748        });
1749        format!("http://127.0.0.1:{}", addr.port())
1750    }
1751
1752    /// The reply's first line says what the fetch reached: status, type,
1753    /// final URL (with the URL asked for when a redirect moved it) and
1754    /// title, on both entry points.
1755    #[tokio::test]
1756    async fn a_fetch_reports_status_final_url_and_title() {
1757        let base = serve(vec![
1758            (
1759                "/page",
1760                "200 OK",
1761                "text/html; charset=utf-8",
1762                "<html><head><title>Synthetic Shop</title></head><body><p>Hello.</p></body></html>"
1763                    .into(),
1764            ),
1765            ("/hop", "302 Found", "text/plain", "/page".into()),
1766        ])
1767        .await;
1768        let tool = WebFetch::new().without_proxy().allow_private_hosts();
1769        let out = tool
1770            .call(json!({"url": format!("{base}/page")}), &ctx())
1771            .await
1772            .unwrap();
1773        let first = out.content.lines().next().unwrap_or("").to_string();
1774        assert!(first.starts_with("HTTP 200 \u{b7} text/html"), "{first}");
1775        assert!(first.contains(&format!("{base}/page")), "{first}");
1776        assert!(first.contains("title \"Synthetic Shop\""), "{first}");
1777        assert!(!first.contains("redirected"), "{first}");
1778
1779        let hop = format!("{base}/hop");
1780        let out = tool.call(json!({"url": hop}), &ctx()).await.unwrap();
1781        let first = out.content.lines().next().unwrap_or("").to_string();
1782        assert!(
1783            first.contains(&format!("{base}/page (redirected from {hop})")),
1784            "{first}"
1785        );
1786
1787        // The daemon's entry point carries the same line.
1788        let outcome = OutcomeTool::execute(
1789            &tool,
1790            &json!({"url": hop}).to_string(),
1791            &ToolCallContext::default(),
1792        )
1793        .await
1794        .unwrap();
1795        let first = outcome.output.lines().next().unwrap_or("").to_string();
1796        assert!(first.starts_with("HTTP 200"), "{first}");
1797        assert!(first.contains("redirected from"), "{first}");
1798        assert!(first.contains("Synthetic Shop"), "{first}");
1799    }
1800
1801    #[tokio::test]
1802    async fn fetches_html_as_markdown() {
1803        let base = serve(vec![
1804            (
1805                "/page",
1806                "200 OK",
1807                "text/html; charset=utf-8",
1808                "<html><head><title>T</title><script>evil()</script></head><body><h1>Synthetic Title</h1><p>Hello <b>world</b>.</p></body></html>".into(),
1809            ),
1810            ("/big", "200 OK", "text/plain", "x".repeat(5000)),
1811            ("/gone", "404 Not Found", "text/html", "<p>no such page</p>".into()),
1812            ("/away", "302 Found", "text/plain", "http://elsewhere.invalid/".into()),
1813            ("/img", "200 OK", "image/png", "\u{1}PNG".into()),
1814        ])
1815        .await;
1816        let tool = WebFetch::new()
1817            .without_proxy()
1818            .allow_private_hosts()
1819            .max_chars(1000);
1820
1821        let url = format!("{base}/page");
1822        let out = tool.call(json!({"url": url}), &ctx()).await.unwrap();
1823        assert!(!out.is_error, "{}", out.content);
1824        assert!(out.content.contains("Hello"), "{}", out.content);
1825        assert!(!out.content.contains("evil"));
1826        assert_eq!(out.details["status"], 200);
1827
1828        let out = tool
1829            .call(json!({"url": format!("{base}/big")}), &ctx())
1830            .await
1831            .unwrap();
1832        assert!(
1833            out.content
1834                .contains("[Content truncated to 1000 characters. Fetch again with offset=1000")
1835        );
1836        assert_eq!(out.details["truncated"], true);
1837
1838        let out = tool
1839            .call(json!({"url": format!("{base}/gone")}), &ctx())
1840            .await
1841            .unwrap();
1842        assert!(out.is_error);
1843        assert_eq!(out.details["status"], 404);
1844        assert!(out.content.contains("404") && out.content.contains("no such page"));
1845
1846        let out = tool
1847            .call(json!({"url": format!("{base}/away")}), &ctx())
1848            .await
1849            .unwrap();
1850        assert!(out.is_error && out.content.contains("elsewhere.invalid"));
1851        assert_eq!(out.details["status"], 302);
1852
1853        let out = tool
1854            .call(json!({"url": format!("{base}/img")}), &ctx())
1855            .await
1856            .unwrap();
1857        assert!(out.is_error && out.content.contains("image/png"));
1858    }
1859
1860    /// Both entry points build the same reply: a PDF and a PNG are
1861    /// described, not decoded into junk text; a long page continues at
1862    /// `offset`; a JavaScript-only page says extraction failed.
1863    #[tokio::test]
1864    async fn both_paths_describe_binary_and_continue_at_an_offset() {
1865        let js_only = format!(
1866            "<html><head><script>{}</script></head><body><div id=\"root\"></div></body></html>",
1867            "z".repeat(20_000)
1868        );
1869        let base = serve(vec![
1870            (
1871                "/doc",
1872                "200 OK",
1873                "application/pdf",
1874                "%PDF-1.7 synthetic".into(),
1875            ),
1876            ("/img", "200 OK", "image/png", "\u{1}PNG".into()),
1877            (
1878                "/long",
1879                "200 OK",
1880                "text/plain",
1881                format!("{}{}", "a".repeat(1000), "b".repeat(500)),
1882            ),
1883            ("/spa", "200 OK", "text/html", js_only),
1884        ])
1885        .await;
1886        let tool = WebFetch::new()
1887            .without_proxy()
1888            .allow_private_hosts()
1889            .max_chars(1000);
1890        let facts = crate::semantics::ToolCallContext::default();
1891        let daemon = |args: Value| {
1892            let tool = &tool;
1893            let facts = &facts;
1894            async move {
1895                OutcomeTool::execute(tool, &args.to_string(), facts)
1896                    .await
1897                    .unwrap()
1898            }
1899        };
1900
1901        let pdf = daemon(json!({"url": format!("{base}/doc")})).await.output;
1902        assert!(
1903            pdf.contains("PDF document") && pdf.contains("read_file"),
1904            "{pdf}"
1905        );
1906        assert!(!pdf.contains("%PDF"), "{pdf}");
1907        let out = tool
1908            .call(json!({"url": format!("{base}/doc")}), &ctx())
1909            .await
1910            .unwrap();
1911        assert!(out.is_error && out.content.contains("PDF document"));
1912
1913        let png = daemon(json!({"url": format!("{base}/img")})).await.output;
1914        assert!(
1915            png.contains("binary content, 4 bytes, type image/png"),
1916            "{png}"
1917        );
1918
1919        let first = daemon(json!({"url": format!("{base}/long")})).await;
1920        let info = first.metadata.truncation.expect("cut");
1921        assert_eq!((info.shown_chars, info.total_chars), (1000, 1500));
1922        assert!(info.remediation_hint.unwrap().contains("offset=1000"));
1923        let rest = daemon(json!({"url": format!("{base}/long"), "offset": 1000})).await;
1924        assert!(rest.output.ends_with(&"b".repeat(500)), "{}", rest.output);
1925        assert!(!rest.output.contains('a'.to_string().repeat(2).as_str()));
1926        assert!(rest.metadata.truncation.is_none());
1927        let out = tool
1928            .call(
1929                json!({"url": format!("{base}/long"), "offset": 1000}),
1930                &ctx(),
1931            )
1932            .await
1933            .unwrap();
1934        assert!(out.content.contains(&"b".repeat(500)) && !out.content.contains("aa"));
1935
1936        let spa = daemon(json!({"url": format!("{base}/spa")})).await.output;
1937        assert!(spa.contains("EXTRACTION FAILED"), "{spa}");
1938    }
1939
1940    #[tokio::test]
1941    async fn private_hosts_are_blocked_by_default() {
1942        let base = serve(vec![("/page", "200 OK", "text/plain", "private".into())]).await;
1943        let tool = WebFetch::new().without_proxy();
1944        let out = tool
1945            .call(json!({"url": format!("{base}/page")}), &ctx())
1946            .await
1947            .unwrap();
1948        assert!(
1949            out.is_error && out.content.contains("Request blocked"),
1950            "{}",
1951            out.content
1952        );
1953        assert!(!out.content.contains("private\n"));
1954    }
1955
1956    #[tokio::test]
1957    async fn a_cross_host_redirect_is_reported_not_followed() {
1958        let base = serve(vec![(
1959            "/away",
1960            "302 Found",
1961            "text/plain",
1962            "http://localhost:9/landing".into(),
1963        )])
1964        .await;
1965        let tool = WebFetch::new().without_proxy().allow_private_hosts();
1966        let out = tool
1967            .call(json!({"url": format!("{base}/away")}), &ctx())
1968            .await
1969            .unwrap();
1970        assert!(
1971            out.is_error && out.content.contains("localhost:9"),
1972            "{}",
1973            out.content
1974        );
1975    }
1976
1977    #[tokio::test]
1978    async fn mandate_execution_never_follows_a_redirect() {
1979        let base = serve(vec![
1980            ("/away", "302 Found", "text/plain", "/landing".into()),
1981            ("/landing", "200 OK", "text/html", "<p>arrived</p>".into()),
1982        ])
1983        .await;
1984        let tool = WebFetch::new()
1985            .without_proxy()
1986            .allow_private_hosts()
1987            .follow_public_redirects();
1988        let arguments = json!({"url": format!("{base}/away")}).to_string();
1989
1990        let followed = tool
1991            .execute(&arguments, &ToolCallContext::default())
1992            .await
1993            .unwrap();
1994        assert!(followed.output.contains("arrived"), "{}", followed.output);
1995
1996        let facts = ToolCallContext {
1997            mandate_execution: true,
1998            ..ToolCallContext::default()
1999        };
2000        let stopped = tool.execute(&arguments, &facts).await.unwrap();
2001        assert!(stopped.output.contains("HTTP 302"), "{}", stopped.output);
2002    }
2003
2004    #[test]
2005    fn metadata_endpoints_are_refused_for_every_reach() {
2006        for target in [
2007            "169.254.169.254:80",
2008            "metadata.google.internal:80",
2009            "metadata.goog:443",
2010            "fe80::1:80",
2011            "fd00:ec2::254:80",
2012        ] {
2013            for reach in [
2014                NetworkReach::Any,
2015                NetworkReach::PublicAndLoopback,
2016                NetworkReach::PublicOnly,
2017            ] {
2018                assert!(
2019                    network_refusal(reach, target).is_some(),
2020                    "{target} {reach:?}"
2021                );
2022            }
2023        }
2024    }
2025
2026    #[test]
2027    fn reach_decides_private_and_loopback() {
2028        use NetworkReach::*;
2029        // A shell still reaches the owner's own network and internal names.
2030        for target in ["10.0.0.5:22", "localhost:3000", "db.internal:5432"] {
2031            assert_eq!(network_refusal(Any, target), None, "{target}");
2032        }
2033        assert_eq!(network_refusal(PublicAndLoopback, "localhost:3000"), None);
2034        assert_eq!(
2035            network_refusal(PublicAndLoopback, "shop.localhost:80"),
2036            None
2037        );
2038        assert!(network_refusal(PublicAndLoopback, "10.0.0.5:80").is_some());
2039        assert!(network_refusal(PublicOnly, "localhost:3000").is_some());
2040        assert!(network_refusal(PublicOnly, "::1:80").is_some());
2041        assert_eq!(network_refusal(PublicOnly, "8.8.8.8:443"), None);
2042    }
2043
2044    #[test]
2045    fn a_refusal_names_the_class_not_the_target() {
2046        let label = network_refusal(NetworkReach::PublicOnly, "10.1.2.3:8443").unwrap();
2047        assert!(!label.contains("10.1.2.3"));
2048    }
2049
2050    #[test]
2051    fn validates_scheme_and_declares_host() {
2052        let tool = WebFetch::new();
2053        assert!(
2054            tool.validate(&json!({"url": "file:///etc/passwd"}))
2055                .is_err()
2056        );
2057        assert!(tool.validate(&json!({"url": "not a url"})).is_err());
2058        assert!(
2059            tool.validate(&json!({"url": "https://example.com/x"}))
2060                .is_ok()
2061        );
2062        assert_eq!(
2063            tool.access(&json!({"url": "https://docs.example.com/a?b=c"}))
2064                .hosts,
2065            vec!["docs.example.com"]
2066        );
2067        assert!(tool.annotations().read_only);
2068    }
2069}
2070
2071#[cfg(test)]
2072mod ssrf_policy_tests {
2073    use super::*;
2074
2075    /// Every URL the shared classifier marks blocked must ALSO be rejected by
2076    /// `validate_url_for_ssrf`, and the class must match the expected category.
2077    /// This is the single-source-of-truth invariant: the browser tool's
2078    /// host-class classifier and the web_fetch validator never diverge.
2079    fn assert_blocked(url: &str, expected: BlockedHostClass) {
2080        let class = classify_blocked_host(url);
2081        assert_eq!(
2082            class,
2083            Some(expected),
2084            "expected {url} blocked as {expected:?}, got {class:?}"
2085        );
2086        assert!(
2087            validate_url_for_ssrf(url).is_err(),
2088            "validate_url_for_ssrf must also reject {url}"
2089        );
2090        // Secret-safety: the label must never echo the URL.
2091        let label = expected.label();
2092        assert!(
2093            !url.contains(label) || label.is_empty(),
2094            "label must be a fixed class string, not derived from the url"
2095        );
2096    }
2097
2098    fn assert_allowed(url: &str) {
2099        assert_eq!(
2100            classify_blocked_host(url),
2101            None,
2102            "{url} should be allowed (public)"
2103        );
2104    }
2105
2106    #[test]
2107    fn loopback_is_blocked() {
2108        assert_blocked("http://127.0.0.1/", BlockedHostClass::Loopback);
2109        assert_blocked("http://127.0.0.1:8080/admin", BlockedHostClass::Loopback);
2110        assert_blocked("http://127.5.6.7/", BlockedHostClass::Loopback); // 127/8
2111        assert_blocked("http://localhost/", BlockedHostClass::Loopback);
2112        assert_blocked("http://[::1]/", BlockedHostClass::Loopback);
2113        assert_blocked("http://0.0.0.0/", BlockedHostClass::Loopback);
2114    }
2115
2116    #[test]
2117    fn rfc1918_private_ranges_are_blocked() {
2118        assert_blocked("http://10.0.0.1/", BlockedHostClass::PrivateNetwork);
2119        assert_blocked("http://10.255.255.255/", BlockedHostClass::PrivateNetwork);
2120        assert_blocked("http://172.16.0.1/", BlockedHostClass::PrivateNetwork);
2121        assert_blocked("http://172.31.255.255/", BlockedHostClass::PrivateNetwork);
2122        assert_blocked("http://192.168.1.1/", BlockedHostClass::PrivateNetwork);
2123        // CGNAT shared space.
2124        assert_blocked("http://100.64.0.1/", BlockedHostClass::PrivateNetwork);
2125    }
2126
2127    #[test]
2128    fn link_local_and_cloud_metadata_are_blocked() {
2129        assert_blocked(
2130            "http://169.254.169.254/latest/meta-data/",
2131            BlockedHostClass::LinkLocalMetadata,
2132        );
2133        assert_blocked("http://169.254.0.1/", BlockedHostClass::LinkLocalMetadata);
2134        assert_blocked(
2135            "http://metadata.google.internal/",
2136            BlockedHostClass::LinkLocalMetadata,
2137        );
2138        assert_blocked(
2139            "http://anything.internal/",
2140            BlockedHostClass::LinkLocalMetadata,
2141        );
2142    }
2143
2144    #[test]
2145    fn ipv4_mapped_ipv6_is_blocked_by_embedded_class() {
2146        // ::ffff:127.0.0.1 → loopback
2147        assert_blocked("http://[::ffff:127.0.0.1]/", BlockedHostClass::Loopback);
2148        // ::ffff:10.0.0.1 → private network
2149        assert_blocked(
2150            "http://[::ffff:10.0.0.1]/",
2151            BlockedHostClass::PrivateNetwork,
2152        );
2153        // ::ffff:169.254.169.254 → link-local/metadata
2154        assert_blocked(
2155            "http://[::ffff:169.254.169.254]/",
2156            BlockedHostClass::LinkLocalMetadata,
2157        );
2158    }
2159
2160    #[test]
2161    fn ipv6_unique_local_and_link_local_are_blocked() {
2162        assert_blocked("http://[fc00::1]/", BlockedHostClass::PrivateNetwork);
2163        assert_blocked("http://[fd12:3456::1]/", BlockedHostClass::PrivateNetwork);
2164        assert_blocked("http://[fe80::1]/", BlockedHostClass::LinkLocalMetadata);
2165    }
2166
2167    #[test]
2168    fn disallowed_schemes_are_blocked() {
2169        assert_blocked("file:///etc/passwd", BlockedHostClass::DisallowedScheme);
2170        assert_blocked("ftp://example.com/", BlockedHostClass::DisallowedScheme);
2171        assert_blocked(
2172            "data:text/html,<h1>hi</h1>",
2173            BlockedHostClass::DisallowedScheme,
2174        );
2175    }
2176
2177    #[test]
2178    fn malformed_urls_are_blocked() {
2179        assert_eq!(
2180            classify_blocked_host("not a url"),
2181            Some(BlockedHostClass::Malformed)
2182        );
2183        assert_eq!(
2184            classify_blocked_host("http://"),
2185            Some(BlockedHostClass::Malformed)
2186        );
2187    }
2188
2189    #[test]
2190    fn resolve_path_classifies_private_targets() {
2191        // A raw-IP host with an explicit port exercises the resolve→classify
2192        // path (to_socket_addrs succeeds and yields the embedded IP). This is
2193        // the same code path a DNS-rebinding host would hit when it resolves to
2194        // a private address — deterministic in CI because no real DNS is needed.
2195        assert_blocked("http://10.1.2.3:8443/x", BlockedHostClass::PrivateNetwork);
2196        assert_blocked("http://127.0.0.1:9000/x", BlockedHostClass::Loopback);
2197        // An unresolvable non-IP host is NOT falsely reported as blocked here —
2198        // the validator lets such a request fail naturally at connect time. This
2199        // documents that pure DNS-rebinding (public name → private A-record at
2200        // request time) is only catchable at request time (see browser
2201        // request-interception deferral), not by this pre-flight check.
2202        assert_eq!(
2203            classify_blocked_host("http://nonexistent-host.invalid/"),
2204            None,
2205            "unresolvable host is not pre-flight blocked (request-time only)"
2206        );
2207    }
2208
2209    #[test]
2210    fn public_urls_are_allowed() {
2211        assert_allowed("https://example.com/");
2212        assert_allowed("https://www.rust-lang.org/learn");
2213        assert_allowed("http://93.184.216.34/"); // example.com public IP
2214        assert_allowed("https://8.8.8.8/");
2215    }
2216
2217    #[test]
2218    fn labels_are_fixed_and_leak_no_data() {
2219        // Every label is a fixed class string with no caller data.
2220        for class in [
2221            BlockedHostClass::Loopback,
2222            BlockedHostClass::PrivateNetwork,
2223            BlockedHostClass::LinkLocalMetadata,
2224            BlockedHostClass::DisallowedScheme,
2225            BlockedHostClass::Malformed,
2226            BlockedHostClass::OtherReserved,
2227        ] {
2228            let label = class.label();
2229            assert!(!label.is_empty());
2230            // No URL syntax, no scheme, no query, no credentials.
2231            for forbidden in ["://", "?", "=", "@", "127.", "169.254", "secret"] {
2232                assert!(
2233                    !label.contains(forbidden),
2234                    "label {label:?} must not contain {forbidden:?}"
2235                );
2236            }
2237        }
2238    }
2239}
2240
2241#[cfg(test)]
2242mod format_tests {
2243    use super::*;
2244
2245    #[test]
2246    fn truncated_fetch_carries_instructional_notice() {
2247        let text = "a".repeat(120);
2248        let (out, truncation) = format_fetch_result("https://example.com/page", &text, 50);
2249        assert!(out.contains("Content from https://example.com/page"));
2250        // The notice is metadata, not embedded text — text-scanning consumers
2251        // (classifiers, summaries) must see clean output.
2252        assert!(!out.contains("OUTPUT TRUNCATED"));
2253        assert!(!out.contains("[Truncated]"));
2254        let info = truncation.expect("truncation info");
2255        assert_eq!(info.total_chars, 120);
2256        assert_eq!(info.shown_chars, 50);
2257        // Remediation hint must be fetch-flavored, not terminal-flavored, and
2258        // preserved verbatim.
2259        let hint = info.remediation_hint.expect("remediation hint");
2260        assert!(hint.contains("max_chars"));
2261        assert!(!hint.contains("wc -l"));
2262    }
2263
2264    /// A synthetic download page: a short release list, one long prose
2265    /// section and a lot of navigation, shaped like real listing pages.
2266    fn listing_page() -> String {
2267        let nav: String = (0..400)
2268            .map(|i| format!("<li><a href=\"/nav/{i}\">Section {i} overview</a></li>"))
2269            .collect();
2270        let prose: String = (0..12)
2271            .map(|i| {
2272                format!(
2273                    "<p>Paragraph {i} explains how release artifacts are signed and how a \
2274                     careful user can check that a downloaded installer is genuine before \
2275                     running it on their machine, step by step.</p>"
2276                )
2277            })
2278            .collect();
2279        format!(
2280            "<html><body><nav><ul>{nav}</ul></nav>\
2281             <div class=\"releases\"><h2>Downloads</h2><ul>\
2282             <li><a href=\"/r/9.4.2\">Download Acme 9.4.2</a></li>\
2283             <li><a href=\"/r/9.4.1\">Acme 9.4.1</a></li></ul></div>\
2284             <div class=\"article\"><h2>Verifying downloads</h2>{prose}</div>\
2285             </body></html>"
2286        )
2287    }
2288
2289    /// A page whose one heading is its title keeps that heading: readability
2290    /// drops it, and the model would fetch the page again to find it.
2291    #[test]
2292    fn the_page_heading_survives_extraction() {
2293        // Shaped like example.com: a title, no heading, one paragraph.
2294        let html = "<!doctype html><html lang=en><head><meta charset=utf-8>\
2295                    <title>Example Domain</title><style>body{margin:auto}</style></head>\
2296                    <body><p>This domain is for use in synthetic documentation examples \
2297                    without needing permission.</p><script src=/s.js></script></body></html>";
2298        let text = extract_page_text(html, "https://example.com/");
2299        let first = text
2300            .lines()
2301            .find(|line| !line.trim().is_empty())
2302            .unwrap_or("");
2303        assert!(first.contains("Example Domain"), "{text}");
2304        assert!(text.contains("synthetic documentation"), "{text}");
2305        assert!(!text.contains("isReaderPage"), "{text}");
2306        // A heading in the body stays apart from the paragraph after it, and
2307        // is not added again.
2308        let html = "<html><head><title>Example Domain</title></head><body><div>\
2309                    <h1>Example Domain</h1><p>This domain is for use in synthetic \
2310                    documentation examples without needing permission.</p></div></body></html>";
2311        let text = extract_page_text(html, "https://example.com/");
2312        assert!(text.contains("# Example Domain"), "{text}");
2313        assert!(text.matches("Example Domain").count() <= 2, "{text}");
2314        assert!(!text.contains("DomainThis"), "{text}");
2315        // A title only, and a heading with markup inside.
2316        assert_eq!(
2317            page_heading("<title> Synthetic  Page </title><p>x</p>").as_deref(),
2318            Some("Synthetic Page")
2319        );
2320        assert_eq!(
2321            page_heading("<h10>no</h10><h1 class=\"t\">A <b>bold</b> &amp; plain</h1>").as_deref(),
2322            Some("A bold & plain")
2323        );
2324        assert_eq!(page_heading("<p>nothing</p>"), None);
2325    }
2326
2327    #[test]
2328    fn listing_page_keeps_content_readability_would_drop() {
2329        let text = extract_page_text(&listing_page(), "https://acme.example/downloads/");
2330        assert!(
2331            text.contains("Download Acme 9.4.2"),
2332            "{}",
2333            &text[..text.len().min(400)]
2334        );
2335    }
2336
2337    #[test]
2338    fn long_article_still_uses_readability() {
2339        let nav: String = (0..200)
2340            .map(|i| format!("<li><a href=\"/nav/{i}\">Menu entry {i}</a></li>"))
2341            .collect();
2342        let body: String = (0..120)
2343            .map(|i| {
2344                format!(
2345                    "<p>Paragraph {i} of a long synthetic article about mountain cities, \
2346                     their climate, history and the people who live there today.</p>"
2347                )
2348            })
2349            .collect();
2350        let html = format!(
2351            "<html><body><nav><ul>{nav}</ul></nav><article><h1>Mountain cities</h1>{body}</article></body></html>"
2352        );
2353        let text = extract_page_text(&html, "https://wiki.example/mountain");
2354        assert!(text.contains("Paragraph 119"));
2355        assert!(
2356            !text.contains("Menu entry 150"),
2357            "navigation leaked into an article"
2358        );
2359    }
2360
2361    #[test]
2362    fn untruncated_fetch_has_no_notice() {
2363        let (out, truncation) = format_fetch_result("https://example.com", "short content", 1000);
2364        assert!(out.contains("short content"));
2365        assert!(!out.contains("OUTPUT TRUNCATED"));
2366        assert!(truncation.is_none());
2367    }
2368
2369    #[test]
2370    fn truncation_respects_char_boundaries() {
2371        // 4-byte emoji straddling the cap must not panic.
2372        let text = format!("{}🦀🦀🦀", "x".repeat(49));
2373        let (_out, truncation) = format_fetch_result("https://example.com", &text, 51);
2374        assert!(truncation.is_some());
2375    }
2376
2377    #[test]
2378    fn fetch_result_truncation_is_metadata_not_text() {
2379        let long = "y".repeat(9000);
2380        let (text, truncation) = format_fetch_result("https://example.com", &long, 4000);
2381        assert!(!text.contains("OUTPUT TRUNCATED"));
2382        let info = truncation.expect("truncation info");
2383        assert_eq!(info.total_chars, 9000);
2384        assert!(
2385            info.remediation_hint
2386                .as_deref()
2387                .unwrap_or("")
2388                .contains("max_chars")
2389        );
2390    }
2391}
2392
2393#[cfg(test)]
2394mod extraction_tests {
2395    use super::*;
2396    use crate::semantics::ToolSemantics;
2397
2398    /// Mimics the observed Wikipedia failure: a large inline <script> block
2399    /// ahead of the real content leaked into the "extracted" text and
2400    /// consumed the whole max_chars window.
2401    fn script_heavy_page() -> String {
2402        format!(
2403            "<html><head><title>Ecuador national football team - Wikipedia</title>\
2404             <script>(function(){{var className=\"client-js vector-feature-language-{}\";}})();</script>\
2405             <style>.mw-parser{{display:none}}{}</style></head>\
2406             <body><h1>Squad</h1><p>{}</p>\
2407             <table><tr><td>Willian Pacho</td></tr><tr><td>Moises Caicedo</td></tr></table>\
2408             </body></html>",
2409            "x".repeat(8_000),
2410            "y".repeat(8_000),
2411            "The current squad was announced ahead of the tournament. ".repeat(20),
2412        )
2413    }
2414
2415    #[test]
2416    fn script_and_style_blocks_never_reach_the_model() {
2417        let (reply, _truncation) = build_fetch_reply(
2418            "https://en.wikipedia.org/wiki/X",
2419            &script_heavy_page(),
2420            2_000,
2421        );
2422        assert!(
2423            !reply.contains("var className"),
2424            "script body leaked: {}",
2425            reply
2426        );
2427        assert!(
2428            !reply.contains("display:none"),
2429            "style body leaked: {}",
2430            reply
2431        );
2432        assert!(reply.contains("Willian Pacho") || reply.contains("current squad"));
2433    }
2434
2435    #[test]
2436    fn near_empty_extraction_gets_instructional_notice() {
2437        // Big page, no readable text — the JS-rendered-page signature.
2438        let html = format!(
2439            "<html><head><script>{}</script></head><body><div id=\"root\"></div></body></html>",
2440            "z".repeat(20_000)
2441        );
2442        let (reply, truncation) = build_fetch_reply("https://spa.example.com", &html, 20_000);
2443        assert!(
2444            reply.contains("EXTRACTION FAILED"),
2445            "missing notice: {}",
2446            reply
2447        );
2448        assert!(reply.contains("different source"));
2449        // Must not pretend the page was read.
2450        assert!(!reply.contains("OUTPUT TRUNCATED"));
2451        assert!(truncation.is_none());
2452    }
2453
2454    #[test]
2455    fn normal_page_has_no_extraction_notice() {
2456        let (reply, _truncation) =
2457            build_fetch_reply("https://example.com", &script_heavy_page(), 20_000);
2458        assert!(!reply.contains("EXTRACTION FAILED"));
2459    }
2460
2461    #[test]
2462    fn small_thin_pages_are_not_flagged() {
2463        // A genuinely tiny page is not an extraction failure.
2464        let (reply, _truncation) = build_fetch_reply(
2465            "https://example.com",
2466            "<html><body><p>hi</p></body></html>",
2467            20_000,
2468        );
2469        assert!(!reply.contains("EXTRACTION FAILED"));
2470    }
2471
2472    #[test]
2473    fn append_capped_respects_byte_ceiling() {
2474        // Under the cap: whole chunk appended, not truncated.
2475        let mut buf = Vec::new();
2476        assert!(!append_capped(&mut buf, b"hello", 100));
2477        assert_eq!(buf, b"hello");
2478
2479        // Exactly at the cap: still appended fully, not truncated.
2480        let mut buf = vec![0u8; 8];
2481        assert!(!append_capped(&mut buf, &[1u8, 2u8], 10));
2482        assert_eq!(buf.len(), 10);
2483
2484        // Over the cap: partial copy up to the ceiling, truncated reported.
2485        let mut buf = vec![0u8; 8];
2486        assert!(append_capped(&mut buf, &[1, 2, 3, 4], 10));
2487        assert_eq!(buf.len(), 10);
2488
2489        // Already full: nothing copied, truncation reported.
2490        let mut buf = vec![0u8; 10];
2491        assert!(append_capped(&mut buf, b"x", 10));
2492        assert_eq!(buf.len(), 10);
2493    }
2494
2495    #[test]
2496    fn append_capped_truncation_is_utf8_safe() {
2497        // "€" is 3 bytes (E2 82 AC); capping at 3 keeps "ab" + 1 byte of it.
2498        // Decoding the capped bytes with from_utf8_lossy must not panic.
2499        let mut buf = Vec::new();
2500        assert!(append_capped(&mut buf, "ab€".as_bytes(), 3));
2501        assert_eq!(buf.len(), 3);
2502        let s = String::from_utf8_lossy(&buf);
2503        assert!(s.starts_with("ab"));
2504    }
2505
2506    #[test]
2507    fn web_fetch_declares_egress_host() {
2508        let tool = WebFetch::new();
2509        let effects =
2510            tool.call_effects(&json!({"url": "https://Docs.Example.Invalid/guide"}).to_string());
2511        assert!(effects.complete);
2512        assert_eq!(
2513            effects.keys,
2514            vec![aidaemon_core::EffectKey::egress(
2515                "https",
2516                "docs.example.invalid",
2517                None
2518            )]
2519        );
2520        let bad = tool.call_effects(&json!({"url": "::"}).to_string());
2521        assert!(!bad.complete);
2522    }
2523}