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