Skip to main content

merry_tools/web_fetch/
mod.rs

1//! Lightweight HTTP fetcher with dual-gate SSRF protection and HTML-to-Markdown conversion.
2
3use crate::ssrf::{check_ssrf_url, check_ssrf_url_static, is_explicit_local_host, strip_brackets};
4use merry_core::{ErrorInfo, PendingToolCall};
5use merry_runtime::{
6    LivePolicyHandle, NetworkAccessDecision, PermissionedAction, RegisteredTool,
7    RequestedCapability, ToolActionKind, ToolBuildError, ToolExecutionContext, ToolExecutionError,
8    ToolExecutionOutcome, ToolExecutor, ToolExecutorFuture, ToolPermissionRequirement,
9    normalize_network_domain,
10};
11use schemars::JsonSchema;
12use serde::Deserialize;
13use serde_json::json;
14use std::{net::SocketAddr, sync::Arc, time::Duration};
15use url::Url;
16
17mod html;
18
19/// Registered tool name for lightweight HTTP/HTML fetching.
20pub const WEB_FETCH_TOOL: &str = "web_fetch";
21
22const DEFAULT_TIMEOUT_SECS: u64 = 20;
23const DEFAULT_MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
24const DEFAULT_MAX_OUTPUT_CHARS: usize = 32_000;
25const MAX_REDIRECTS: usize = 10;
26
27/// Configuration for [`WebFetchTool`].
28#[derive(Debug, Clone)]
29pub struct WebFetchConfig {
30    allow_local: bool,
31    timeout: Duration,
32    max_response_bytes: usize,
33    max_output_chars: usize,
34    live_network_policy: Option<LivePolicyHandle>,
35}
36
37impl Default for WebFetchConfig {
38    fn default() -> Self {
39        Self {
40            allow_local: true,
41            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
42            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
43            max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
44            live_network_policy: None,
45        }
46    }
47}
48
49impl WebFetchConfig {
50    /// Sets whether explicit loopback targets (`localhost`, `127.0.0.1`, `::1`) are permitted.
51    #[must_use]
52    pub fn with_allow_local(mut self, allow_local: bool) -> Self {
53        self.allow_local = allow_local;
54        self
55    }
56
57    /// Attaches the live unified [`LivePolicyHandle`] shared with
58    /// session permissions, workspace `allowed_domains`, and `network` policy.
59    #[must_use]
60    pub fn with_live_network_policy(mut self, policy: LivePolicyHandle) -> Self {
61        self.live_network_policy = Some(policy);
62        self
63    }
64
65    /// Overrides the per-request timeout.
66    #[must_use]
67    pub fn with_timeout(mut self, timeout: Duration) -> Self {
68        self.timeout = timeout;
69        self
70    }
71
72    /// Overrides the maximum response body size downloaded in bytes.
73    #[must_use]
74    pub fn with_max_response_bytes(mut self, max_response_bytes: usize) -> Self {
75        self.max_response_bytes = max_response_bytes;
76        self
77    }
78
79    /// Overrides the maximum model-visible output characters.
80    #[must_use]
81    pub fn with_max_output_chars(mut self, max_output_chars: usize) -> Self {
82        self.max_output_chars = max_output_chars;
83        self
84    }
85}
86
87#[merry_tools_macros::tool(
88    crate = "crate",
89    name = "web_fetch",
90    description = "Fetch a static web page, API JSON endpoint, or plain text document over HTTP/HTTPS and return clean extracted Markdown or text. Use this instead of browser tools when reading documentation or non-interactive URLs. Authenticated or private URLs fail. An SSRF refusal is final for that URL. Cross-host redirects stop and return the redirect URL instead of following automatically."
91)]
92#[derive(Debug, Deserialize, JsonSchema)]
93#[serde(deny_unknown_fields)]
94struct WebFetchInput {
95    #[schemars(
96        description = "Target http:// or https:// URL to fetch.",
97        length(min = 1)
98    )]
99    url: String,
100    #[serde(default)]
101    #[schemars(
102        description = "Optional maximum character length for returned extracted content.",
103        range(min = 100)
104    )]
105    max_chars: Option<usize>,
106}
107
108/// Built-in SSRF-guarded HTTP/HTML fetch tool.
109#[derive(Debug, Clone)]
110pub struct WebFetchTool {
111    config: Arc<WebFetchConfig>,
112}
113
114impl WebFetchTool {
115    /// Creates a `web_fetch` tool with the supplied configuration.
116    #[must_use]
117    pub fn new(config: WebFetchConfig) -> Self {
118        Self {
119            config: Arc::new(config),
120        }
121    }
122
123    /// Converts this tool into a registered runtime tool.
124    pub fn into_registered_tool(self) -> Result<RegisteredTool, ToolBuildError> {
125        let spec = WebFetchInput::tool_spec()?;
126        Ok(
127            RegisteredTool::new(spec, Arc::new(self), ToolActionKind::Network)
128                .with_permissioned_network_lane()
129                .with_parallel_safe_execution(),
130        )
131    }
132}
133
134impl Default for WebFetchTool {
135    fn default() -> Self {
136        Self::new(WebFetchConfig::default())
137    }
138}
139
140impl ToolExecutor for WebFetchTool {
141    fn execute<'a>(
142        &'a self,
143        call: PendingToolCall,
144        context: ToolExecutionContext,
145    ) -> ToolExecutorFuture<'a> {
146        Box::pin(async move {
147            if context.cancellation_token().is_cancelled() {
148                return Err(ToolExecutionError::Cancelled);
149            }
150            let input: WebFetchInput = match call.arguments().deserialize_as() {
151                Ok(input) => input,
152                Err(error) => {
153                    return Ok(web_fetch_failed(
154                        "web_fetch_invalid_arguments",
155                        format!("invalid web_fetch arguments: {error}"),
156                        None,
157                    ));
158                }
159            };
160            tokio::select! {
161                biased;
162                () = context.cancellation_token().cancelled() => Err(ToolExecutionError::Cancelled),
163                result = execute_fetch(&self.config, input, context.approved_network_domains()) => result,
164            }
165        })
166    }
167}
168
169async fn execute_fetch(
170    config: &WebFetchConfig,
171    input: WebFetchInput,
172    approved_once_domains: &[String],
173) -> Result<ToolExecutionOutcome, ToolExecutionError> {
174    let mut url = match Url::parse(input.url.trim()) {
175        Ok(url) => url,
176        Err(error) => {
177            return Ok(web_fetch_failed(
178                "web_fetch_invalid_url",
179                format!("invalid URL {:?}: {error}", input.url),
180                None,
181            ));
182        }
183    };
184
185    if url.scheme() == "http"
186        && let Some(host) = url.host_str()
187        && !is_explicit_local_host(host)
188    {
189        let _ = url.set_scheme("https");
190    }
191
192    let effective_allow_local = config.allow_local
193        && config
194            .live_network_policy
195            .as_ref()
196            .is_none_or(LivePolicyHandle::network_allow_local);
197
198    // 1. Unbypassable static SSRF checks before any policy prompt or DNS lookup.
199    if let Err(reason) = check_ssrf_url_static(&url, effective_allow_local) {
200        return Ok(web_fetch_failed(
201            "web_fetch_ssrf_blocked",
202            reason,
203            Some(url.as_str()),
204        ));
205    }
206
207    // 2. Unified network & domain admission before issuing DNS or HTTP traffic.
208    if let Some(policy) = config.live_network_policy.as_ref()
209        && let Some(raw_host) = url.host_str()
210    {
211        match policy.evaluate_network_host(raw_host, approved_once_domains) {
212            NetworkAccessDecision::Allow => {}
213            NetworkAccessDecision::Deny => {
214                return Ok(web_fetch_failed(
215                    "web_fetch_network_denied",
216                    format!(
217                        "outbound network access to {:?} is denied by current network policy",
218                        raw_host
219                    ),
220                    Some(url.as_str()),
221                ));
222            }
223            NetworkAccessDecision::RequireReview => {
224                let normalized_host =
225                    normalize_network_domain(raw_host).unwrap_or_else(|| raw_host.to_owned());
226                return Err(ToolExecutionError::permission_required(
227                    ToolPermissionRequirement::new(
228                        PermissionedAction::NetworkUrl {
229                            tool: WEB_FETCH_TOOL.to_owned(),
230                            url: url.to_string(),
231                            host: normalized_host.clone(),
232                        },
233                        vec![RequestedCapability::NetworkDomain(normalized_host)],
234                        Some(format!("Fetch {url}")),
235                    ),
236                ));
237            }
238        }
239    }
240
241    // 3. Full DNS-resolving SSRF gate and pinned connection.
242    let initial_addrs = match check_ssrf_url(&url, effective_allow_local).await {
243        Ok(addrs) => addrs,
244        Err(reason) => {
245            return Ok(web_fetch_failed(
246                "web_fetch_ssrf_blocked",
247                reason,
248                Some(url.as_str()),
249            ));
250        }
251    };
252
253    let client = match build_pinned_client(config, &url, &initial_addrs) {
254        Ok(client) => client,
255        Err(error) => {
256            return Ok(web_fetch_failed(
257                "web_fetch_client_error",
258                error,
259                Some(url.as_str()),
260            ));
261        }
262    };
263
264    let mut current_url = url.clone();
265    let response = match follow_same_host_redirects(
266        &client,
267        effective_allow_local,
268        &mut current_url,
269    )
270    .await
271    {
272        Ok(RedirectStep::Response(resp)) => resp,
273        Ok(RedirectStep::CrossHostRedirect {
274            status_code,
275            redirect_url,
276        }) => {
277            let summary = format!(
278                "Stopped at cross-host redirect ({status_code}) from {current_url} to {redirect_url}. Inspect the destination URL and fetch it directly if intended."
279            );
280            return Ok(ToolExecutionOutcome::succeeded_text(summary));
281        }
282        Err(outcome) => return Ok(*outcome),
283    };
284
285    let status_code = response.status().as_u16();
286    let content_type = response
287        .headers()
288        .get(reqwest::header::CONTENT_TYPE)
289        .and_then(|value| value.to_str().ok())
290        .map(str::to_owned);
291
292    let (raw_bytes, body_truncated) =
293        match read_bounded_body(response, config.max_response_bytes).await {
294            Ok(data) => data,
295            Err(error) => {
296                return Ok(web_fetch_failed(
297                    "web_fetch_read_failed",
298                    error,
299                    Some(current_url.as_str()),
300                ));
301            }
302        };
303
304    let (title, full_extracted) = format_response_content(&raw_bytes, content_type.as_deref());
305    let limit = input
306        .max_chars
307        .unwrap_or(config.max_output_chars)
308        .min(config.max_output_chars);
309    let (model_body, text_truncated) = truncate_chars(&full_extracted, limit);
310    let truncated = body_truncated || text_truncated;
311
312    if status_code >= 400 {
313        let detail = format!("HTTP {status_code} fetching {current_url}\n\n{model_body}");
314        return Ok(web_fetch_failed(
315            "web_fetch_http_error",
316            detail,
317            Some(current_url.as_str()),
318        ));
319    }
320
321    let mut model_summary = format!("URL: {current_url}\nStatus: {status_code}\n");
322    if let Some(title_text) = title.as_deref() {
323        model_summary.push_str(&format!("Title: {title_text}\n"));
324    }
325    model_summary.push('\n');
326    model_summary.push_str(&model_body);
327    if truncated {
328        model_summary.push_str("\n\n[truncated]");
329    }
330
331    Ok(ToolExecutionOutcome::succeeded_text(model_summary))
332}
333
334enum RedirectStep {
335    Response(reqwest::Response),
336    CrossHostRedirect {
337        status_code: u16,
338        redirect_url: String,
339    },
340}
341
342async fn follow_same_host_redirects(
343    client: &reqwest::Client,
344    allow_local: bool,
345    current_url: &mut Url,
346) -> Result<RedirectStep, Box<ToolExecutionOutcome>> {
347    for hop in 0..=MAX_REDIRECTS {
348        let response = client
349            .get(current_url.clone())
350            .send()
351            .await
352            .map_err(|error| {
353                Box::new(web_fetch_failed(
354                    "web_fetch_request_failed",
355                    format!("HTTP request failed: {error}"),
356                    Some(current_url.as_str()),
357                ))
358            })?;
359        let status = response.status();
360        if !status.is_redirection() {
361            return Ok(RedirectStep::Response(response));
362        }
363        let Some(location) = response
364            .headers()
365            .get(reqwest::header::LOCATION)
366            .and_then(|value| value.to_str().ok())
367        else {
368            return Ok(RedirectStep::Response(response));
369        };
370        let next_url = current_url.join(location).map_err(|error| {
371            Box::new(web_fetch_failed(
372                "web_fetch_invalid_redirect",
373                format!("invalid redirect location {location:?}: {error}"),
374                Some(current_url.as_str()),
375            ))
376        })?;
377        let https_downgrade = current_url.scheme() == "https"
378            && next_url.scheme() == "http"
379            && !next_url.host_str().is_some_and(is_explicit_local_host);
380        if !same_host(current_url, &next_url) || https_downgrade {
381            return Ok(RedirectStep::CrossHostRedirect {
382                status_code: status.as_u16(),
383                redirect_url: next_url.to_string(),
384            });
385        }
386        if hop == MAX_REDIRECTS {
387            return Err(Box::new(web_fetch_failed(
388                "web_fetch_too_many_redirects",
389                format!("exceeded {MAX_REDIRECTS} same-host redirects"),
390                Some(next_url.as_str()),
391            )));
392        }
393        if let Err(reason) = check_ssrf_url(&next_url, allow_local).await {
394            return Err(Box::new(web_fetch_failed(
395                "web_fetch_ssrf_blocked",
396                reason,
397                Some(next_url.as_str()),
398            )));
399        }
400        *current_url = next_url;
401    }
402    unreachable!("redirect loop returns within bounded hops")
403}
404
405fn build_pinned_client(
406    config: &WebFetchConfig,
407    url: &Url,
408    addrs: &[SocketAddr],
409) -> Result<reqwest::Client, String> {
410    let mut builder = reqwest::Client::builder()
411        .redirect(reqwest::redirect::Policy::none())
412        .timeout(config.timeout)
413        .user_agent("MerryWebFetch/0.1");
414
415    if let Some(host) = url.host_str()
416        && !addrs.is_empty()
417    {
418        builder = builder.resolve_to_addrs(strip_brackets(host), addrs);
419    }
420
421    builder
422        .build()
423        .map_err(|error| format!("failed to build HTTP client: {error}"))
424}
425
426fn same_host(a: &Url, b: &Url) -> bool {
427    let normalize = |u: &Url| u.host_str().and_then(normalize_network_domain);
428    matches!((normalize(a), normalize(b)), (Some(left), Some(right)) if left == right)
429}
430
431async fn read_bounded_body(
432    mut response: reqwest::Response,
433    max_bytes: usize,
434) -> Result<(Vec<u8>, bool), String> {
435    let mut out = Vec::new();
436    let mut truncated = false;
437    while let Some(chunk) = response
438        .chunk()
439        .await
440        .map_err(|error| format!("error reading response body: {error}"))?
441    {
442        let remaining = max_bytes.saturating_sub(out.len());
443        if remaining == 0 {
444            truncated = true;
445            break;
446        }
447        if chunk.len() > remaining {
448            out.extend_from_slice(&chunk[..remaining]);
449            truncated = true;
450            break;
451        }
452        out.extend_from_slice(&chunk);
453    }
454    Ok((out, truncated))
455}
456
457fn format_response_content(bytes: &[u8], content_type: Option<&str>) -> (Option<String>, String) {
458    let mime = content_type
459        .unwrap_or("text/plain")
460        .split(';')
461        .next()
462        .unwrap_or("text/plain")
463        .trim()
464        .to_ascii_lowercase();
465
466    let text = String::from_utf8_lossy(bytes);
467    if mime == "text/html" || mime == "application/xhtml+xml" {
468        let title = html::extract_html_title(&text);
469        let md = html::html_to_markdown(&text);
470        let content = if md.trim().is_empty() {
471            "[HTML page had no extractable text content]".to_owned()
472        } else {
473            md
474        };
475        return (title, content);
476    }
477    if mime == "application/json" || mime.ends_with("+json") {
478        let formatted = serde_json::from_slice::<serde_json::Value>(bytes)
479            .and_then(|v| serde_json::to_string_pretty(&v))
480            .unwrap_or_else(|_| text.into_owned());
481        return (None, html::strip_base64_data_uris(&formatted));
482    }
483    if mime.starts_with("text/")
484        || mime.contains("xml")
485        || mime.contains("javascript")
486        || mime.contains("yaml")
487    {
488        let cleaned = html::strip_base64_data_uris(&text);
489        let content = if cleaned.trim().is_empty() {
490            "[empty text response]".to_owned()
491        } else {
492            cleaned
493        };
494        return (None, content);
495    }
496    (
497        None,
498        format!("[non-text content type={mime} bytes={}]", bytes.len()),
499    )
500}
501
502fn truncate_chars(text: &str, max_chars: usize) -> (String, bool) {
503    if text.chars().count() <= max_chars {
504        return (text.to_owned(), false);
505    }
506    let truncated: String = text.chars().take(max_chars).collect();
507    (truncated, true)
508}
509
510fn web_fetch_failed(
511    code: &'static str,
512    message: String,
513    url: Option<&str>,
514) -> ToolExecutionOutcome {
515    let payload = json!({
516        "ok": false,
517        "tool": WEB_FETCH_TOOL,
518        "url": url,
519        "error": {
520            "code": code,
521            "message": message,
522        }
523    });
524    let safe_diag_msg: String = message
525        .chars()
526        .filter(|c| !c.is_control())
527        .take(512)
528        .collect();
529    let diagnostic = ErrorInfo::new(
530        code,
531        if safe_diag_msg.trim().is_empty() {
532            "web_fetch failed"
533        } else {
534            &safe_diag_msg
535        },
536    )
537    .expect("sanitized web_fetch diagnostic is valid");
538    ToolExecutionOutcome::failed_json(payload.to_string(), diagnostic)
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use axum::{
545        Router,
546        http::StatusCode,
547        response::{Html, IntoResponse, Redirect},
548        routing::get,
549    };
550    use merry_core::{
551        PendingToolCall, ToolCallArguments, ToolCallId, ToolCallResultStatus, ToolName,
552    };
553    use tokio::net::TcpListener;
554    use tokio_util::sync::CancellationToken;
555
556    fn test_call(args: serde_json::Value) -> PendingToolCall {
557        PendingToolCall::new(
558            ToolCallId::new("call-web-fetch").expect("valid id"),
559            ToolName::new(WEB_FETCH_TOOL).expect("valid name"),
560            ToolCallArguments::try_from(args).expect("object args"),
561        )
562    }
563
564    #[tokio::test]
565    async fn blocks_ssrf_targets_and_fetches_loopback_html_when_allowed() {
566        let blocked_tool = WebFetchTool::new(WebFetchConfig::default().with_allow_local(false));
567        let blocked = blocked_tool
568            .execute(
569                test_call(json!({"url": "http://127.0.0.1:8080/"})),
570                ToolExecutionContext::new(CancellationToken::new()),
571            )
572            .await
573            .expect("returns failed outcome");
574        assert_eq!(blocked.status(), ToolCallResultStatus::Failed);
575        assert_eq!(
576            blocked.diagnostic().expect("diag").code(),
577            "web_fetch_ssrf_blocked"
578        );
579
580        let app = Router::new()
581            .route(
582                "/docs",
583                get(|| async {
584                    Html("<html><head><title>Test Page</title></head><body><h1>Hello</h1><p>World</p><script>bad()</script></body></html>")
585                }),
586            )
587            .route(
588                "/bounce",
589                get(|| async { Redirect::temporary("https://other.example.com/target").into_response() }),
590            )
591            .route(
592                "/local-redirect",
593                get(|| async { (StatusCode::FOUND, [("location", "/docs")]).into_response() }),
594            );
595        let listener = TcpListener::bind("127.0.0.1:0")
596            .await
597            .expect("bind loopback");
598        let addr = listener.local_addr().expect("addr");
599        let server = tokio::spawn(async move {
600            axum::serve(listener, app).await.expect("serve");
601        });
602
603        let local_tool = WebFetchTool::default();
604        let ok = local_tool
605            .execute(
606                test_call(
607                    json!({"url": format!("http://127.0.0.1:{}/local-redirect", addr.port())}),
608                ),
609                ToolExecutionContext::new(CancellationToken::new()),
610            )
611            .await
612            .expect("fetch succeeds");
613        assert_eq!(ok.status(), ToolCallResultStatus::Succeeded);
614        assert!(ok.model_content().is_none());
615        let text = ok.content().as_str();
616        assert!(text.contains("Title: Test Page"));
617        assert!(text.contains("# Hello"));
618        assert!(!text.contains("bad()"));
619
620        let cross_host = local_tool
621            .execute(
622                test_call(json!({"url": format!("http://127.0.0.1:{}/bounce", addr.port())})),
623                ToolExecutionContext::new(CancellationToken::new()),
624            )
625            .await
626            .expect("cross-host redirect returns cleanly");
627        assert_eq!(cross_host.status(), ToolCallResultStatus::Succeeded);
628        assert!(cross_host.model_content().is_none());
629        assert!(
630            cross_host
631                .content()
632                .as_str()
633                .contains("https://other.example.com/target")
634        );
635
636        server.abort();
637    }
638
639    #[tokio::test]
640    async fn web_fetch_enforces_live_network_policy_domain_grants_and_ssrf_floor() {
641        use merry_core::CapabilityPolicy;
642        use merry_runtime::{
643            LivePolicyHandle, NetworkAccessPolicy, PermissionedAction, ProcessSessionPermissions,
644            RequestedCapability, ToolExecutionError,
645        };
646
647        // 1. network = "deny" hard-denies external domains before review (and without DNS).
648        let deny_policy =
649            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Deny, true));
650        let deny_tool =
651            WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(deny_policy));
652        let denied = deny_tool
653            .execute(
654                test_call(json!({"url": "https://docs.rs/serde"})),
655                ToolExecutionContext::new(CancellationToken::new()),
656            )
657            .await
658            .expect("network deny returns failed outcome without review");
659        assert_eq!(denied.status(), ToolCallResultStatus::Failed);
660        assert_eq!(
661            denied.diagnostic().expect("diag").code(),
662            "web_fetch_network_denied"
663        );
664
665        // 2. network = "ask" triggers structured domain-level PermissionRequired.
666        let session_permissions = ProcessSessionPermissions::new();
667        let ask_policy = LivePolicyHandle::for_network(
668            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true)
669                .with_session_permissions(session_permissions.view()),
670        );
671        let ask_tool = WebFetchTool::new(
672            WebFetchConfig::default().with_live_network_policy(ask_policy.clone()),
673        );
674        let err = ask_tool
675            .execute(
676                test_call(json!({"url": "https://Docs.RS/serde"})),
677                ToolExecutionContext::new(CancellationToken::new()),
678            )
679            .await
680            .expect_err("ask policy should require domain approval");
681        match err {
682            ToolExecutionError::PermissionRequired(requirement) => {
683                assert_eq!(
684                    requirement.action(),
685                    &PermissionedAction::NetworkUrl {
686                        tool: WEB_FETCH_TOOL.to_owned(),
687                        url: "https://docs.rs/serde".to_owned(),
688                        host: "docs.rs".to_owned(),
689                    }
690                );
691                assert_eq!(
692                    requirement.requested(),
693                    &[RequestedCapability::NetworkDomain("docs.rs".to_owned())]
694                );
695            }
696            other => panic!("expected PermissionRequired, got {other:?}"),
697        }
698
699        // 3. Exact hostname match only: approving docs.rs does NOT approve www.docs.rs.
700        session_permissions
701            .retain_domain_grants(["docs.rs".to_owned()])
702            .expect("domain grant recorded");
703        let www_err = ask_tool
704            .execute(
705                test_call(json!({"url": "https://www.docs.rs/serde"})),
706                ToolExecutionContext::new(CancellationToken::new()),
707            )
708            .await
709            .expect_err("www.docs.rs must not inherit docs.rs grant");
710        assert!(matches!(www_err, ToolExecutionError::PermissionRequired(_)));
711
712        // 4. SSRF floor cannot be bypassed even when network = "allow".
713        let allow_policy =
714            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, true));
715        let allow_tool =
716            WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(allow_policy));
717        for blocked_url in [
718            "file:///etc/passwd",
719            "http://169.254.169.254/latest/meta-data",
720            "http://10.0.0.1/secret",
721        ] {
722            let outcome = allow_tool
723                .execute(
724                    test_call(json!({"url": blocked_url})),
725                    ToolExecutionContext::new(CancellationToken::new()),
726                )
727                .await
728                .expect("ssrf returns failed outcome");
729            assert_eq!(outcome.status(), ToolCallResultStatus::Failed);
730            assert!(
731                matches!(
732                    outcome.diagnostic().expect("diag").code(),
733                    "web_fetch_ssrf_blocked" | "web_fetch_invalid_url"
734                ),
735                "unexpected code for {blocked_url}: {:?}",
736                outcome.diagnostic()
737            );
738        }
739
740        // 5. allow_local = true still permits explicit loopback even when network = "deny".
741        let app = Router::new().route("/ping", get(|| async { Html("<h1>pong</h1>") }));
742        let listener = TcpListener::bind("127.0.0.1:0")
743            .await
744            .expect("bind loopback");
745        let addr = listener.local_addr().expect("addr");
746        let server = tokio::spawn(async move {
747            axum::serve(listener, app).await.expect("serve");
748        });
749        let local_ok = deny_tool
750            .execute(
751                test_call(json!({"url": format!("http://127.0.0.1:{}/ping", addr.port())})),
752                ToolExecutionContext::new(CancellationToken::new()),
753            )
754            .await
755            .expect("loopback stays allowed when allow_local=true");
756        assert_eq!(local_ok.status(), ToolCallResultStatus::Succeeded);
757        assert!(local_ok.content().as_str().contains("pong"));
758
759        // 6. Disabling allow_local in the live network policy blocks loopback.
760        let no_local_policy =
761            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, false));
762        let no_local_tool =
763            WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(no_local_policy));
764        let local_blocked = no_local_tool
765            .execute(
766                test_call(json!({"url": format!("http://127.0.0.1:{}/ping", addr.port())})),
767                ToolExecutionContext::new(CancellationToken::new()),
768            )
769            .await
770            .expect("loopback denied when allow_local=false");
771        assert_eq!(local_blocked.status(), ToolCallResultStatus::Failed);
772        assert_eq!(
773            local_blocked.diagnostic().expect("diag").code(),
774            "web_fetch_ssrf_blocked"
775        );
776        server.abort();
777    }
778}