1use crate::security::SecurityPolicy;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use futures_util::StreamExt;
7use serde_json::json;
8use std::sync::Arc;
9use std::time::Duration;
10
11pub struct WebFetchTool {
20 security: Arc<SecurityPolicy>,
21 allowed_domains: Vec<String>,
22 blocked_domains: Vec<String>,
23 max_response_size: usize,
24 timeout_secs: u64,
25}
26
27impl WebFetchTool {
28 pub fn new(
29 security: Arc<SecurityPolicy>,
30 allowed_domains: Vec<String>,
31 blocked_domains: Vec<String>,
32 max_response_size: usize,
33 timeout_secs: u64,
34 ) -> Self {
35 Self {
36 security,
37 allowed_domains: normalize_allowed_domains(allowed_domains),
38 blocked_domains: normalize_allowed_domains(blocked_domains),
39 max_response_size,
40 timeout_secs,
41 }
42 }
43
44 fn validate_url(&self, raw_url: &str) -> anyhow::Result<String> {
45 validate_target_url(
46 raw_url,
47 &self.allowed_domains,
48 &self.blocked_domains,
49 "web_fetch",
50 )
51 }
52
53 fn truncate_response(&self, text: &str) -> String {
54 if text.len() > self.max_response_size {
55 let mut truncated = text
56 .chars()
57 .take(self.max_response_size)
58 .collect::<String>();
59 truncated.push_str("\n\n... [Response truncated due to size limit] ...");
60 truncated
61 } else {
62 text.to_string()
63 }
64 }
65
66 async fn read_response_text_limited(
67 &self,
68 response: reqwest::Response,
69 ) -> anyhow::Result<String> {
70 let mut bytes_stream = response.bytes_stream();
71 let hard_cap = self.max_response_size.saturating_add(1);
72 let mut bytes = Vec::new();
73
74 while let Some(chunk_result) = bytes_stream.next().await {
75 let chunk = chunk_result?;
76 if append_chunk_with_cap(&mut bytes, &chunk, hard_cap) {
77 break;
78 }
79 }
80
81 Ok(String::from_utf8_lossy(&bytes).into_owned())
82 }
83}
84
85#[async_trait]
86impl Tool for WebFetchTool {
87 fn category(&self) -> ToolCategory {
88 ToolCategory::Read
89 }
90
91 fn name(&self) -> &str {
92 "web_fetch"
93 }
94
95 fn description(&self) -> &str {
96 "Fetch a web page and return its content as clean plain text. \
97 HTML pages are automatically converted to readable text. \
98 JSON and plain text responses are returned as-is. \
99 Only GET requests; follows redirects. \
100 Security: allowlist-only domains, no local/private hosts."
101 }
102
103 fn parameters_schema(&self) -> serde_json::Value {
104 json!({
105 "type": "object",
106 "properties": {
107 "url": {
108 "type": "string",
109 "description": "The HTTP or HTTPS URL to fetch"
110 }
111 },
112 "required": ["url"]
113 })
114 }
115
116 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
117 let url = args
118 .get("url")
119 .and_then(|v| v.as_str())
120 .ok_or_else(|| anyhow::anyhow!("Missing 'url' parameter"))?;
121
122 if !self.security.can_act() {
123 return Ok(ToolResult {
124 success: false,
125 output: String::new(),
126 error: Some("Action blocked: autonomy is read-only".into()),
127 });
128 }
129
130 if !self.security.record_action() {
131 return Ok(ToolResult {
132 success: false,
133 output: String::new(),
134 error: Some("Action blocked: rate limit exceeded".into()),
135 });
136 }
137
138 let url = match self.validate_url(url) {
139 Ok(v) => v,
140 Err(e) => {
141 return Ok(ToolResult {
142 success: false,
143 output: String::new(),
144 error: Some(e.to_string()),
145 });
146 }
147 };
148
149 let timeout_secs = if self.timeout_secs == 0 {
151 tracing::warn!("web_fetch: timeout_secs is 0, using safe default of 30s");
152 30
153 } else {
154 self.timeout_secs
155 };
156
157 let allowed_domains = self.allowed_domains.clone();
158 let blocked_domains = self.blocked_domains.clone();
159 let redirect_policy = reqwest::redirect::Policy::custom(move |attempt| {
160 if attempt.previous().len() >= 10 {
161 return attempt.error(std::io::Error::other("Too many redirects (max 10)"));
162 }
163
164 if let Err(err) = validate_target_url(
165 attempt.url().as_str(),
166 &allowed_domains,
167 &blocked_domains,
168 "web_fetch",
169 ) {
170 return attempt.error(std::io::Error::new(
171 std::io::ErrorKind::PermissionDenied,
172 format!("Blocked redirect target: {err}"),
173 ));
174 }
175
176 attempt.follow()
177 });
178
179 let builder = reqwest::Client::builder()
180 .timeout(Duration::from_secs(timeout_secs))
181 .connect_timeout(Duration::from_secs(10))
182 .redirect(redirect_policy)
183 .user_agent("Nenjo/0.1 (web_fetch)");
184 let client = match builder.build() {
185 Ok(c) => c,
186 Err(e) => {
187 return Ok(ToolResult {
188 success: false,
189 output: String::new(),
190 error: Some(format!("Failed to build HTTP client: {e}")),
191 });
192 }
193 };
194
195 let response = match client.get(&url).send().await {
196 Ok(r) => r,
197 Err(e) => {
198 return Ok(ToolResult {
199 success: false,
200 output: String::new(),
201 error: Some(format!("HTTP request failed: {e}")),
202 });
203 }
204 };
205
206 let status = response.status();
207 if !status.is_success() {
208 return Ok(ToolResult {
209 success: false,
210 output: String::new(),
211 error: Some(format!(
212 "HTTP {} {}",
213 status.as_u16(),
214 status.canonical_reason().unwrap_or("Unknown")
215 )),
216 });
217 }
218
219 let content_type = response
221 .headers()
222 .get(reqwest::header::CONTENT_TYPE)
223 .and_then(|v| v.to_str().ok())
224 .unwrap_or("")
225 .to_lowercase();
226
227 let body_mode = if content_type.contains("text/html") || content_type.is_empty() {
228 "html"
229 } else if content_type.contains("text/plain")
230 || content_type.contains("text/markdown")
231 || content_type.contains("application/json")
232 {
233 "plain"
234 } else {
235 return Ok(ToolResult {
236 success: false,
237 output: String::new(),
238 error: Some(format!(
239 "Unsupported content type: {content_type}. \
240 web_fetch supports text/html, text/plain, text/markdown, and application/json."
241 )),
242 });
243 };
244
245 let body = match self.read_response_text_limited(response).await {
246 Ok(t) => t,
247 Err(e) => {
248 return Ok(ToolResult {
249 success: false,
250 output: String::new(),
251 error: Some(format!("Failed to read response body: {e}")),
252 });
253 }
254 };
255
256 let text = if body_mode == "html" {
257 nanohtml2text::html2text(&body)
258 } else {
259 body
260 };
261
262 let output = self.truncate_response(&text);
263
264 Ok(ToolResult {
265 success: true,
266 output,
267 error: None,
268 })
269 }
270}
271
272fn validate_target_url(
275 raw_url: &str,
276 allowed_domains: &[String],
277 blocked_domains: &[String],
278 tool_name: &str,
279) -> anyhow::Result<String> {
280 let url = raw_url.trim();
281
282 if url.is_empty() {
283 anyhow::bail!("URL cannot be empty");
284 }
285
286 if url.chars().any(char::is_whitespace) {
287 anyhow::bail!("URL cannot contain whitespace");
288 }
289
290 if !url.starts_with("http://") && !url.starts_with("https://") {
291 anyhow::bail!("Only http:// and https:// URLs are allowed");
292 }
293
294 if allowed_domains.is_empty() {
295 anyhow::bail!(
296 "{tool_name} tool is enabled but no allowed_domains are configured. \
297 Add [{tool_name}].allowed_domains in config.toml"
298 );
299 }
300
301 let host = extract_host(url)?;
302
303 if is_private_or_local_host(&host) {
304 anyhow::bail!("Blocked local/private host: {host}");
305 }
306
307 if host_matches_allowlist(&host, blocked_domains) {
308 anyhow::bail!("Host '{host}' is in {tool_name}.blocked_domains");
309 }
310
311 if !host_matches_allowlist(&host, allowed_domains) {
312 anyhow::bail!("Host '{host}' is not in {tool_name}.allowed_domains");
313 }
314
315 validate_resolved_host_is_public(&host)?;
316
317 Ok(url.to_string())
318}
319
320fn append_chunk_with_cap(buffer: &mut Vec<u8>, chunk: &[u8], hard_cap: usize) -> bool {
321 if buffer.len() >= hard_cap {
322 return true;
323 }
324
325 let remaining = hard_cap - buffer.len();
326 if chunk.len() > remaining {
327 buffer.extend_from_slice(&chunk[..remaining]);
328 return true;
329 }
330
331 buffer.extend_from_slice(chunk);
332 buffer.len() >= hard_cap
333}
334
335fn normalize_allowed_domains(domains: Vec<String>) -> Vec<String> {
336 let mut normalized = domains
337 .into_iter()
338 .filter_map(|d| normalize_domain(&d))
339 .collect::<Vec<_>>();
340 normalized.sort_unstable();
341 normalized.dedup();
342 normalized
343}
344
345fn normalize_domain(raw: &str) -> Option<String> {
346 let mut d = raw.trim().to_lowercase();
347 if d.is_empty() {
348 return None;
349 }
350
351 if let Some(stripped) = d.strip_prefix("https://") {
352 d = stripped.to_string();
353 } else if let Some(stripped) = d.strip_prefix("http://") {
354 d = stripped.to_string();
355 }
356
357 if let Some((host, _)) = d.split_once('/') {
358 d = host.to_string();
359 }
360
361 d = d.trim_start_matches('.').trim_end_matches('.').to_string();
362
363 if let Some((host, _)) = d.split_once(':') {
364 d = host.to_string();
365 }
366
367 if d.is_empty() || d.chars().any(char::is_whitespace) {
368 return None;
369 }
370
371 Some(d)
372}
373
374fn extract_host(url: &str) -> anyhow::Result<String> {
375 let rest = url
376 .strip_prefix("http://")
377 .or_else(|| url.strip_prefix("https://"))
378 .ok_or_else(|| anyhow::anyhow!("Only http:// and https:// URLs are allowed"))?;
379
380 let authority = rest
381 .split(['/', '?', '#'])
382 .next()
383 .ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
384
385 if authority.is_empty() {
386 anyhow::bail!("URL must include a host");
387 }
388
389 if authority.contains('@') {
390 anyhow::bail!("URL userinfo is not allowed");
391 }
392
393 if authority.starts_with('[') {
394 anyhow::bail!("IPv6 hosts are not supported in web_fetch");
395 }
396
397 let host = authority
398 .split(':')
399 .next()
400 .unwrap_or_default()
401 .trim()
402 .trim_end_matches('.')
403 .to_lowercase();
404
405 if host.is_empty() {
406 anyhow::bail!("URL must include a valid host");
407 }
408
409 Ok(host)
410}
411
412fn host_matches_allowlist(host: &str, allowed_domains: &[String]) -> bool {
413 if allowed_domains.iter().any(|domain| domain == "*") {
414 return true;
415 }
416
417 allowed_domains.iter().any(|domain| {
418 host == domain
419 || host
420 .strip_suffix(domain)
421 .is_some_and(|prefix| prefix.ends_with('.'))
422 })
423}
424
425fn is_private_or_local_host(host: &str) -> bool {
426 let bare = host
427 .strip_prefix('[')
428 .and_then(|h| h.strip_suffix(']'))
429 .unwrap_or(host);
430
431 let has_local_tld = bare
432 .rsplit('.')
433 .next()
434 .is_some_and(|label| label == "local");
435
436 if bare == "localhost" || bare.ends_with(".localhost") || has_local_tld {
437 return true;
438 }
439
440 if let Ok(ip) = bare.parse::<std::net::IpAddr>() {
441 return match ip {
442 std::net::IpAddr::V4(v4) => is_non_global_v4(v4),
443 std::net::IpAddr::V6(v6) => is_non_global_v6(v6),
444 };
445 }
446
447 false
448}
449
450#[cfg(not(test))]
451fn validate_resolved_host_is_public(host: &str) -> anyhow::Result<()> {
452 use std::net::ToSocketAddrs;
453
454 let ips = (host, 0)
455 .to_socket_addrs()
456 .map_err(|e| anyhow::anyhow!("Failed to resolve host '{host}': {e}"))?
457 .map(|addr| addr.ip())
458 .collect::<Vec<_>>();
459
460 validate_resolved_ips_are_public(host, &ips)
461}
462
463#[cfg(test)]
464fn validate_resolved_host_is_public(_host: &str) -> anyhow::Result<()> {
465 Ok(())
467}
468
469fn validate_resolved_ips_are_public(host: &str, ips: &[std::net::IpAddr]) -> anyhow::Result<()> {
470 if ips.is_empty() {
471 anyhow::bail!("Failed to resolve host '{host}'");
472 }
473
474 for ip in ips {
475 let non_global = match ip {
476 std::net::IpAddr::V4(v4) => is_non_global_v4(*v4),
477 std::net::IpAddr::V6(v6) => is_non_global_v6(*v6),
478 };
479 if non_global {
480 anyhow::bail!("Blocked host '{host}' resolved to non-global address {ip}");
481 }
482 }
483
484 Ok(())
485}
486
487fn is_non_global_v4(v4: std::net::Ipv4Addr) -> bool {
488 let [a, b, c, _] = v4.octets();
489 v4.is_loopback()
490 || v4.is_private()
491 || v4.is_link_local()
492 || v4.is_unspecified()
493 || v4.is_broadcast()
494 || v4.is_multicast()
495 || (a == 100 && (64..=127).contains(&b))
496 || a >= 240
497 || (a == 192 && b == 0 && (c == 0 || c == 2))
498 || (a == 198 && b == 51)
499 || (a == 203 && b == 0)
500 || (a == 198 && (18..=19).contains(&b))
501}
502
503fn is_non_global_v6(v6: std::net::Ipv6Addr) -> bool {
504 let segs = v6.segments();
505 v6.is_loopback()
506 || v6.is_unspecified()
507 || v6.is_multicast()
508 || (segs[0] & 0xfe00) == 0xfc00
509 || (segs[0] & 0xffc0) == 0xfe80
510 || (segs[0] == 0x2001 && segs[1] == 0x0db8)
511 || v6.to_ipv4_mapped().is_some_and(is_non_global_v4)
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517 use crate::security::{AutonomyLevel, SecurityPolicy};
518
519 fn test_tool(allowed_domains: Vec<&str>) -> WebFetchTool {
520 test_tool_with_blocklist(allowed_domains, vec![])
521 }
522
523 fn test_tool_with_blocklist(
524 allowed_domains: Vec<&str>,
525 blocked_domains: Vec<&str>,
526 ) -> WebFetchTool {
527 let security = Arc::new(SecurityPolicy {
528 autonomy: AutonomyLevel::Supervised,
529 ..SecurityPolicy::default()
530 });
531 WebFetchTool::new(
532 security,
533 allowed_domains.into_iter().map(String::from).collect(),
534 blocked_domains.into_iter().map(String::from).collect(),
535 500_000,
536 30,
537 )
538 }
539
540 #[test]
543 fn name_is_web_fetch() {
544 let tool = test_tool(vec!["example.com"]);
545 assert_eq!(tool.name(), "web_fetch");
546 }
547
548 #[test]
549 fn parameters_schema_requires_url() {
550 let tool = test_tool(vec!["example.com"]);
551 let schema = tool.parameters_schema();
552 assert!(schema["properties"]["url"].is_object());
553 let required = schema["required"].as_array().unwrap();
554 assert!(required.iter().any(|v| v.as_str() == Some("url")));
555 }
556
557 #[test]
560 fn html_to_text_conversion() {
561 let html = "<html><body><h1>Title</h1><p>Hello <b>world</b></p></body></html>";
562 let text = nanohtml2text::html2text(html);
563 assert!(text.contains("Title"));
564 assert!(text.contains("Hello"));
565 assert!(text.contains("world"));
566 assert!(!text.contains("<h1>"));
567 assert!(!text.contains("<p>"));
568 }
569
570 #[test]
573 fn validate_accepts_exact_domain() {
574 let tool = test_tool(vec!["example.com"]);
575 let got = tool.validate_url("https://example.com/page").unwrap();
576 assert_eq!(got, "https://example.com/page");
577 }
578
579 #[test]
580 fn validate_accepts_subdomain() {
581 let tool = test_tool(vec!["example.com"]);
582 assert!(tool.validate_url("https://docs.example.com/guide").is_ok());
583 }
584
585 #[test]
586 fn validate_accepts_wildcard() {
587 let tool = test_tool(vec!["*"]);
588 assert!(tool.validate_url("https://news.ycombinator.com").is_ok());
589 }
590
591 #[test]
592 fn validate_rejects_empty_url() {
593 let tool = test_tool(vec!["example.com"]);
594 let err = tool.validate_url("").unwrap_err().to_string();
595 assert!(err.contains("empty"));
596 }
597
598 #[test]
599 fn validate_rejects_missing_url() {
600 let tool = test_tool(vec!["example.com"]);
601 let err = tool.validate_url(" ").unwrap_err().to_string();
602 assert!(err.contains("empty"));
603 }
604
605 #[test]
606 fn validate_rejects_ftp_scheme() {
607 let tool = test_tool(vec!["example.com"]);
608 let err = tool
609 .validate_url("ftp://example.com")
610 .unwrap_err()
611 .to_string();
612 assert!(err.contains("http://") || err.contains("https://"));
613 }
614
615 #[test]
616 fn validate_rejects_allowlist_miss() {
617 let tool = test_tool(vec!["example.com"]);
618 let err = tool
619 .validate_url("https://google.com")
620 .unwrap_err()
621 .to_string();
622 assert!(err.contains("allowed_domains"));
623 }
624
625 #[test]
626 fn validate_requires_allowlist() {
627 let security = Arc::new(SecurityPolicy::default());
628 let tool = WebFetchTool::new(security, vec![], vec![], 500_000, 30);
629 let err = tool
630 .validate_url("https://example.com")
631 .unwrap_err()
632 .to_string();
633 assert!(err.contains("allowed_domains"));
634 }
635
636 #[test]
639 fn ssrf_blocks_localhost() {
640 let tool = test_tool(vec!["localhost"]);
641 let err = tool
642 .validate_url("https://localhost:8080")
643 .unwrap_err()
644 .to_string();
645 assert!(err.contains("local/private"));
646 }
647
648 #[test]
649 fn ssrf_blocks_private_ipv4() {
650 let tool = test_tool(vec!["192.168.1.5"]);
651 let err = tool
652 .validate_url("https://192.168.1.5")
653 .unwrap_err()
654 .to_string();
655 assert!(err.contains("local/private"));
656 }
657
658 #[test]
659 fn ssrf_blocks_loopback() {
660 assert!(is_private_or_local_host("127.0.0.1"));
661 assert!(is_private_or_local_host("127.0.0.2"));
662 }
663
664 #[test]
665 fn ssrf_blocks_rfc1918() {
666 assert!(is_private_or_local_host("10.0.0.1"));
667 assert!(is_private_or_local_host("172.16.0.1"));
668 assert!(is_private_or_local_host("192.168.1.1"));
669 }
670
671 #[test]
672 fn ssrf_wildcard_still_blocks_private() {
673 let tool = test_tool(vec!["*"]);
674 let err = tool
675 .validate_url("https://localhost:8080")
676 .unwrap_err()
677 .to_string();
678 assert!(err.contains("local/private"));
679 }
680
681 #[test]
682 fn redirect_target_validation_allows_permitted_host() {
683 let allowed = vec!["example.com".to_string()];
684 let blocked = vec![];
685 assert!(
686 validate_target_url(
687 "https://docs.example.com/page",
688 &allowed,
689 &blocked,
690 "web_fetch"
691 )
692 .is_ok()
693 );
694 }
695
696 #[test]
697 fn redirect_target_validation_blocks_private_host() {
698 let allowed = vec!["example.com".to_string()];
699 let blocked = vec![];
700 let err = validate_target_url("https://127.0.0.1/admin", &allowed, &blocked, "web_fetch")
701 .unwrap_err()
702 .to_string();
703 assert!(err.contains("local/private"));
704 }
705
706 #[test]
707 fn redirect_target_validation_blocks_blocklisted_host() {
708 let allowed = vec!["*".to_string()];
709 let blocked = vec!["evil.com".to_string()];
710 let err = validate_target_url("https://evil.com/phish", &allowed, &blocked, "web_fetch")
711 .unwrap_err()
712 .to_string();
713 assert!(err.contains("blocked_domains"));
714 }
715
716 #[tokio::test]
719 async fn blocks_readonly_mode() {
720 let security = Arc::new(SecurityPolicy {
721 autonomy: AutonomyLevel::ReadOnly,
722 ..SecurityPolicy::default()
723 });
724 let tool = WebFetchTool::new(security, vec!["example.com".into()], vec![], 500_000, 30);
725 let result = tool
726 .execute(json!({"url": "https://example.com"}))
727 .await
728 .unwrap();
729 assert!(!result.success);
730 assert!(result.error.unwrap().contains("read-only"));
731 }
732
733 #[tokio::test]
734 async fn blocks_rate_limited() {
735 let security = Arc::new(SecurityPolicy {
736 max_actions_per_hour: 0,
737 ..SecurityPolicy::default()
738 });
739 let tool = WebFetchTool::new(security, vec!["example.com".into()], vec![], 500_000, 30);
740 let result = tool
741 .execute(json!({"url": "https://example.com"}))
742 .await
743 .unwrap();
744 assert!(!result.success);
745 assert!(result.error.unwrap().contains("rate limit"));
746 }
747
748 #[test]
751 fn truncate_within_limit() {
752 let tool = test_tool(vec!["example.com"]);
753 let text = "hello world";
754 assert_eq!(tool.truncate_response(text), "hello world");
755 }
756
757 #[test]
758 fn truncate_over_limit() {
759 let tool = WebFetchTool::new(
760 Arc::new(SecurityPolicy::default()),
761 vec!["example.com".into()],
762 vec![],
763 10,
764 30,
765 );
766 let text = "hello world this is long";
767 let truncated = tool.truncate_response(text);
768 assert!(truncated.contains("[Response truncated"));
769 }
770
771 #[test]
774 fn normalize_domain_strips_scheme_and_case() {
775 let got = normalize_domain(" HTTPS://Docs.Example.com/path ").unwrap();
776 assert_eq!(got, "docs.example.com");
777 }
778
779 #[test]
780 fn normalize_deduplicates() {
781 let got = normalize_allowed_domains(vec![
782 "example.com".into(),
783 "EXAMPLE.COM".into(),
784 "https://example.com/".into(),
785 ]);
786 assert_eq!(got, vec!["example.com".to_string()]);
787 }
788
789 #[test]
792 fn blocklist_rejects_exact_match() {
793 let tool = test_tool_with_blocklist(vec!["*"], vec!["evil.com"]);
794 let err = tool
795 .validate_url("https://evil.com/page")
796 .unwrap_err()
797 .to_string();
798 assert!(err.contains("blocked_domains"));
799 }
800
801 #[test]
802 fn blocklist_rejects_subdomain() {
803 let tool = test_tool_with_blocklist(vec!["*"], vec!["evil.com"]);
804 let err = tool
805 .validate_url("https://api.evil.com/v1")
806 .unwrap_err()
807 .to_string();
808 assert!(err.contains("blocked_domains"));
809 }
810
811 #[test]
812 fn blocklist_wins_over_allowlist() {
813 let tool = test_tool_with_blocklist(vec!["evil.com"], vec!["evil.com"]);
814 let err = tool
815 .validate_url("https://evil.com")
816 .unwrap_err()
817 .to_string();
818 assert!(err.contains("blocked_domains"));
819 }
820
821 #[test]
822 fn blocklist_allows_non_blocked() {
823 let tool = test_tool_with_blocklist(vec!["*"], vec!["evil.com"]);
824 assert!(tool.validate_url("https://example.com").is_ok());
825 }
826
827 #[test]
828 fn append_chunk_with_cap_truncates_and_stops() {
829 let mut buffer = Vec::new();
830 assert!(!append_chunk_with_cap(&mut buffer, b"hello", 8));
831 assert!(append_chunk_with_cap(&mut buffer, b"world", 8));
832 assert_eq!(buffer, b"hellowor");
833 }
834
835 #[test]
836 fn resolved_private_ip_is_rejected() {
837 let ips = vec!["127.0.0.1".parse().unwrap()];
838 let err = validate_resolved_ips_are_public("example.com", &ips)
839 .unwrap_err()
840 .to_string();
841 assert!(err.contains("non-global address"));
842 }
843
844 #[test]
845 fn resolved_mixed_ips_are_rejected() {
846 let ips = vec![
847 "93.184.216.34".parse().unwrap(),
848 "10.0.0.1".parse().unwrap(),
849 ];
850 let err = validate_resolved_ips_are_public("example.com", &ips)
851 .unwrap_err()
852 .to_string();
853 assert!(err.contains("non-global address"));
854 }
855
856 #[test]
857 fn resolved_public_ips_are_allowed() {
858 let ips = vec!["93.184.216.34".parse().unwrap(), "1.1.1.1".parse().unwrap()];
859 assert!(validate_resolved_ips_are_public("example.com", &ips).is_ok());
860 }
861}