1use std::net::{IpAddr, SocketAddr};
20use std::sync::Arc;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::time::{Duration, Instant};
23
24use schemars::JsonSchema;
25use serde::Deserialize;
26use url::Url;
27
28use zeph_common::ToolName;
29
30use crate::audit::{AuditEntry, AuditLogger, AuditResult, EgressEvent, chrono_now};
31use crate::config::{EgressConfig, ScrapeConfig};
32use crate::executor::{
33 ClaimSource, ToolCall, ToolError, ToolExecutor, ToolOutput, deserialize_params,
34};
35use crate::net::is_private_ip;
36
37fn redact_url_for_log(url: &str) -> String {
41 let Ok(mut parsed) = Url::parse(url) else {
42 return url.to_owned();
43 };
44 let _ = parsed.set_username("");
46 let _ = parsed.set_password(None);
47 let sensitive = [
49 "token", "key", "secret", "password", "auth", "sig", "api_key", "apikey",
50 ];
51 let filtered: Vec<(String, String)> = parsed
52 .query_pairs()
53 .filter(|(k, _)| {
54 let lower = k.to_lowercase();
55 !sensitive.iter().any(|s| lower.contains(s))
56 })
57 .map(|(k, v)| (k.into_owned(), v.into_owned()))
58 .collect();
59 if filtered.is_empty() {
60 parsed.set_query(None);
61 } else {
62 let q: String = filtered
63 .iter()
64 .map(|(k, v)| format!("{k}={v}"))
65 .collect::<Vec<_>>()
66 .join("&");
67 parsed.set_query(Some(&q));
68 }
69 parsed.to_string()
70}
71
72#[derive(Debug, Deserialize, JsonSchema)]
73struct FetchParams {
74 url: String,
76}
77
78#[derive(Debug, Deserialize, JsonSchema)]
79struct ScrapeInstruction {
80 url: String,
82 select: String,
84 #[serde(default = "default_extract")]
86 extract: String,
87 limit: Option<usize>,
89}
90
91fn default_extract() -> String {
92 "text".into()
93}
94
95#[derive(Debug)]
96enum ExtractMode {
97 Text,
98 Html,
99 Attr(String),
100}
101
102impl ExtractMode {
103 fn parse(s: &str) -> Self {
104 match s {
105 "text" => Self::Text,
106 "html" => Self::Html,
107 attr if attr.starts_with("attr:") => {
108 Self::Attr(attr.strip_prefix("attr:").unwrap_or(attr).to_owned())
109 }
110 _ => Self::Text,
111 }
112 }
113}
114
115#[derive(Debug)]
154pub struct WebScrapeExecutor {
155 timeout: Duration,
156 max_body_bytes: usize,
157 allowed_domains: Vec<String>,
158 denied_domains: Vec<String>,
159 audit_logger: Option<Arc<AuditLogger>>,
160 egress_config: EgressConfig,
161 egress_tx: Option<tokio::sync::mpsc::Sender<EgressEvent>>,
162 egress_dropped: Arc<AtomicU64>,
163}
164
165impl WebScrapeExecutor {
166 #[must_use]
170 pub fn new(config: &ScrapeConfig) -> Self {
171 Self {
172 timeout: Duration::from_secs(config.timeout),
173 max_body_bytes: config.max_body_bytes,
174 allowed_domains: config.allowed_domains.clone(),
175 denied_domains: config.denied_domains.clone(),
176 audit_logger: None,
177 egress_config: EgressConfig::default(),
178 egress_tx: None,
179 egress_dropped: Arc::new(AtomicU64::new(0)),
180 }
181 }
182
183 #[must_use]
185 pub fn with_audit(mut self, logger: Arc<AuditLogger>) -> Self {
186 self.audit_logger = Some(logger);
187 self
188 }
189
190 #[must_use]
192 pub fn with_egress_config(mut self, config: EgressConfig) -> Self {
193 self.egress_config = config;
194 self
195 }
196
197 #[must_use]
202 pub fn with_egress_tx(
203 mut self,
204 tx: tokio::sync::mpsc::Sender<EgressEvent>,
205 dropped: Arc<AtomicU64>,
206 ) -> Self {
207 self.egress_tx = Some(tx);
208 self.egress_dropped = dropped;
209 self
210 }
211
212 #[must_use]
214 pub fn egress_dropped(&self) -> Arc<AtomicU64> {
215 Arc::clone(&self.egress_dropped)
216 }
217
218 fn build_client(&self, host: &str, addrs: &[SocketAddr]) -> reqwest::Client {
219 let mut builder = reqwest::Client::builder()
220 .timeout(self.timeout)
221 .redirect(reqwest::redirect::Policy::none());
222 builder = builder.resolve_to_addrs(host, addrs);
223 builder.build().unwrap_or_default()
224 }
225}
226
227impl ToolExecutor for WebScrapeExecutor {
228 fn tool_definitions(&self) -> Vec<crate::registry::ToolDef> {
229 use crate::registry::{InvocationHint, ToolDef};
230 vec![
231 ToolDef {
232 id: "web_scrape".into(),
233 description: "Extract structured data from a web page using CSS selectors.\n\nONLY call this tool when the user has explicitly provided a URL in their message, or when a prior tool call returned a URL to retrieve. NEVER construct, guess, or infer a URL from entity names, brand knowledge, or domain patterns.\n\nParameters: url (string, required) - HTTPS URL; select (string, required) - CSS selector; extract (string, optional) - \"text\", \"html\", or \"attr:<name>\"; limit (integer, optional) - max results\nReturns: extracted text/HTML/attribute values, one per line\nErrors: InvalidParams if URL is not HTTPS or selector is empty; Timeout after configured seconds; connection/DNS failures".into(),
234 schema: schemars::schema_for!(ScrapeInstruction),
235 invocation: InvocationHint::FencedBlock("scrape"),
236 output_schema: None,
237 },
238 ToolDef {
239 id: "fetch".into(),
240 description: "Fetch a URL and return the response body as plain text.\n\nONLY call this tool when the user has explicitly provided a URL in their message, or when a prior tool call returned a URL to retrieve. NEVER construct, guess, or infer a URL from entity names, brand knowledge, or domain patterns. If no URL is present in the conversation, do not call this tool.\n\nParameters: url (string, required) - HTTPS URL to fetch\nReturns: response body as UTF-8 text, truncated if exceeding max body size\nErrors: InvalidParams if URL is not HTTPS; Timeout; SSRF-blocked private IPs; connection failures".into(),
241 schema: schemars::schema_for!(FetchParams),
242 invocation: InvocationHint::ToolCall,
243 output_schema: None,
244 },
245 ]
246 }
247
248 async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
249 let blocks = extract_scrape_blocks(response);
250 if blocks.is_empty() {
251 return Ok(None);
252 }
253
254 let mut outputs = Vec::with_capacity(blocks.len());
255 #[allow(clippy::cast_possible_truncation)]
256 let blocks_executed = blocks.len() as u32;
257
258 for block in &blocks {
259 let instruction: ScrapeInstruction = serde_json::from_str(block).map_err(|e| {
260 ToolError::Execution(std::io::Error::new(
261 std::io::ErrorKind::InvalidData,
262 e.to_string(),
263 ))
264 })?;
265 let correlation_id = EgressEvent::new_correlation_id();
266 let start = Instant::now();
267 let scrape_result = self
268 .scrape_instruction(&instruction, &correlation_id, None)
269 .await;
270 #[allow(clippy::cast_possible_truncation)]
271 let duration_ms = start.elapsed().as_millis() as u64;
272 match scrape_result {
273 Ok(output) => {
274 self.log_audit(
275 "web_scrape",
276 &instruction.url,
277 AuditResult::Success,
278 duration_ms,
279 None,
280 None,
281 Some(correlation_id),
282 )
283 .await;
284 outputs.push(output);
285 }
286 Err(e) => {
287 let audit_result = tool_error_to_audit_result(&e);
288 self.log_audit(
289 "web_scrape",
290 &instruction.url,
291 audit_result,
292 duration_ms,
293 Some(&e),
294 None,
295 Some(correlation_id),
296 )
297 .await;
298 return Err(e);
299 }
300 }
301 }
302
303 Ok(Some(ToolOutput {
304 tool_name: ToolName::new("web-scrape"),
305 summary: outputs.join("\n\n"),
306 blocks_executed,
307 filter_stats: None,
308 diff: None,
309 streamed: false,
310 terminal_id: None,
311 locations: None,
312 raw_response: None,
313 claim_source: Some(ClaimSource::WebScrape),
314 }))
315 }
316
317 #[cfg_attr(
318 feature = "profiling",
319 tracing::instrument(name = "tool.web_scrape", skip_all)
320 )]
321 #[allow(clippy::too_many_lines)]
322 async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
323 match call.tool_id.as_str() {
324 "web_scrape" => {
325 let instruction: ScrapeInstruction = deserialize_params(&call.params)?;
326 let correlation_id = EgressEvent::new_correlation_id();
327 let start = Instant::now();
328 let result = self
329 .scrape_instruction(&instruction, &correlation_id, call.caller_id.clone())
330 .await;
331 #[allow(clippy::cast_possible_truncation)]
332 let duration_ms = start.elapsed().as_millis() as u64;
333 match result {
334 Ok(output) => {
335 self.log_audit(
336 "web_scrape",
337 &instruction.url,
338 AuditResult::Success,
339 duration_ms,
340 None,
341 call.caller_id.clone(),
342 Some(correlation_id),
343 )
344 .await;
345 Ok(Some(ToolOutput {
346 tool_name: ToolName::new("web-scrape"),
347 summary: output,
348 blocks_executed: 1,
349 filter_stats: None,
350 diff: None,
351 streamed: false,
352 terminal_id: None,
353 locations: None,
354 raw_response: None,
355 claim_source: Some(ClaimSource::WebScrape),
356 }))
357 }
358 Err(e) => {
359 let audit_result = tool_error_to_audit_result(&e);
360 self.log_audit(
361 "web_scrape",
362 &instruction.url,
363 audit_result,
364 duration_ms,
365 Some(&e),
366 call.caller_id.clone(),
367 Some(correlation_id),
368 )
369 .await;
370 Err(e)
371 }
372 }
373 }
374 "fetch" => {
375 let p: FetchParams = deserialize_params(&call.params)?;
376 let correlation_id = EgressEvent::new_correlation_id();
377 let start = Instant::now();
378 let result = self
379 .handle_fetch(&p, &correlation_id, call.caller_id.clone())
380 .await;
381 #[allow(clippy::cast_possible_truncation)]
382 let duration_ms = start.elapsed().as_millis() as u64;
383 match result {
384 Ok(output) => {
385 self.log_audit(
386 "fetch",
387 &p.url,
388 AuditResult::Success,
389 duration_ms,
390 None,
391 call.caller_id.clone(),
392 Some(correlation_id),
393 )
394 .await;
395 Ok(Some(ToolOutput {
396 tool_name: ToolName::new("fetch"),
397 summary: output,
398 blocks_executed: 1,
399 filter_stats: None,
400 diff: None,
401 streamed: false,
402 terminal_id: None,
403 locations: None,
404 raw_response: None,
405 claim_source: Some(ClaimSource::WebScrape),
406 }))
407 }
408 Err(e) => {
409 let audit_result = tool_error_to_audit_result(&e);
410 self.log_audit(
411 "fetch",
412 &p.url,
413 audit_result,
414 duration_ms,
415 Some(&e),
416 call.caller_id.clone(),
417 Some(correlation_id),
418 )
419 .await;
420 Err(e)
421 }
422 }
423 }
424 _ => Ok(None),
425 }
426 }
427
428 fn is_tool_retryable(&self, tool_id: &str) -> bool {
429 matches!(tool_id, "web_scrape" | "fetch")
430 }
431}
432
433fn tool_error_to_audit_result(e: &ToolError) -> AuditResult {
434 match e {
435 ToolError::Blocked { command } => AuditResult::Blocked {
436 reason: command.clone(),
437 },
438 ToolError::Timeout { .. } => AuditResult::Timeout,
439 _ => AuditResult::Error {
440 message: e.to_string(),
441 },
442 }
443}
444
445impl WebScrapeExecutor {
446 #[allow(clippy::too_many_arguments)]
447 async fn log_audit(
448 &self,
449 tool: &str,
450 command: &str,
451 result: AuditResult,
452 duration_ms: u64,
453 error: Option<&ToolError>,
454 caller_id: Option<String>,
455 correlation_id: Option<String>,
456 ) {
457 if let Some(ref logger) = self.audit_logger {
458 let (error_category, error_domain, error_phase) =
459 error.map_or((None, None, None), |e| {
460 let cat = e.category();
461 (
462 Some(cat.label().to_owned()),
463 Some(cat.domain().label().to_owned()),
464 Some(cat.phase().label().to_owned()),
465 )
466 });
467 let entry = AuditEntry {
468 timestamp: chrono_now(),
469 tool: tool.into(),
470 command: command.into(),
471 result,
472 duration_ms,
473 error_category,
474 error_domain,
475 error_phase,
476 claim_source: Some(ClaimSource::WebScrape),
477 mcp_server_id: None,
478 injection_flagged: false,
479 embedding_anomalous: false,
480 cross_boundary_mcp_to_acp: false,
481 adversarial_policy_decision: None,
482 exit_code: None,
483 truncated: false,
484 caller_id,
485 policy_match: None,
486 correlation_id,
487 vigil_risk: None,
488 };
489 logger.log(&entry).await;
490 }
491 }
492
493 fn send_egress_event(&self, event: EgressEvent) {
494 if let Some(ref tx) = self.egress_tx {
495 match tx.try_send(event) {
496 Ok(()) => {}
497 Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
498 self.egress_dropped.fetch_add(1, Ordering::Relaxed);
499 }
500 Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
501 tracing::debug!("egress channel closed; executor continuing without telemetry");
502 }
503 }
504 }
505 }
506
507 async fn log_egress_event(&self, event: &EgressEvent) {
508 if let Some(ref logger) = self.audit_logger {
509 logger.log_egress(event).await;
510 }
511 self.send_egress_event(event.clone());
512 }
513
514 async fn handle_fetch(
515 &self,
516 params: &FetchParams,
517 correlation_id: &str,
518 caller_id: Option<String>,
519 ) -> Result<String, ToolError> {
520 let parsed = validate_url(¶ms.url);
521 let host_str = parsed
522 .as_ref()
523 .map(|u| u.host_str().unwrap_or("").to_owned())
524 .unwrap_or_default();
525
526 if let Err(ref _e) = parsed {
527 if self.egress_config.enabled && self.egress_config.log_blocked {
528 let event = Self::make_blocked_event(
529 "fetch",
530 ¶ms.url,
531 &host_str,
532 correlation_id,
533 caller_id.clone(),
534 "scheme",
535 );
536 self.log_egress_event(&event).await;
537 }
538 return Err(parsed.unwrap_err());
539 }
540 let parsed = parsed.unwrap();
541
542 if let Err(e) = check_domain_policy(
543 parsed.host_str().unwrap_or(""),
544 &self.allowed_domains,
545 &self.denied_domains,
546 ) {
547 if self.egress_config.enabled && self.egress_config.log_blocked {
548 let event = Self::make_blocked_event(
549 "fetch",
550 ¶ms.url,
551 parsed.host_str().unwrap_or(""),
552 correlation_id,
553 caller_id.clone(),
554 "blocklist",
555 );
556 self.log_egress_event(&event).await;
557 }
558 return Err(e);
559 }
560
561 let (host, addrs) = match resolve_and_validate(&parsed).await {
562 Ok(v) => v,
563 Err(e) => {
564 if self.egress_config.enabled && self.egress_config.log_blocked {
565 let event = Self::make_blocked_event(
566 "fetch",
567 ¶ms.url,
568 parsed.host_str().unwrap_or(""),
569 correlation_id,
570 caller_id.clone(),
571 "ssrf",
572 );
573 self.log_egress_event(&event).await;
574 }
575 return Err(e);
576 }
577 };
578
579 self.fetch_html(
580 ¶ms.url,
581 &host,
582 &addrs,
583 "fetch",
584 correlation_id,
585 caller_id,
586 )
587 .await
588 }
589
590 async fn scrape_instruction(
591 &self,
592 instruction: &ScrapeInstruction,
593 correlation_id: &str,
594 caller_id: Option<String>,
595 ) -> Result<String, ToolError> {
596 let parsed = validate_url(&instruction.url);
597 let host_str = parsed
598 .as_ref()
599 .map(|u| u.host_str().unwrap_or("").to_owned())
600 .unwrap_or_default();
601
602 if let Err(ref _e) = parsed {
603 if self.egress_config.enabled && self.egress_config.log_blocked {
604 let event = Self::make_blocked_event(
605 "web_scrape",
606 &instruction.url,
607 &host_str,
608 correlation_id,
609 caller_id.clone(),
610 "scheme",
611 );
612 self.log_egress_event(&event).await;
613 }
614 return Err(parsed.unwrap_err());
615 }
616 let parsed = parsed.unwrap();
617
618 if let Err(e) = check_domain_policy(
619 parsed.host_str().unwrap_or(""),
620 &self.allowed_domains,
621 &self.denied_domains,
622 ) {
623 if self.egress_config.enabled && self.egress_config.log_blocked {
624 let event = Self::make_blocked_event(
625 "web_scrape",
626 &instruction.url,
627 parsed.host_str().unwrap_or(""),
628 correlation_id,
629 caller_id.clone(),
630 "blocklist",
631 );
632 self.log_egress_event(&event).await;
633 }
634 return Err(e);
635 }
636
637 let (host, addrs) = match resolve_and_validate(&parsed).await {
638 Ok(v) => v,
639 Err(e) => {
640 if self.egress_config.enabled && self.egress_config.log_blocked {
641 let event = Self::make_blocked_event(
642 "web_scrape",
643 &instruction.url,
644 parsed.host_str().unwrap_or(""),
645 correlation_id,
646 caller_id.clone(),
647 "ssrf",
648 );
649 self.log_egress_event(&event).await;
650 }
651 return Err(e);
652 }
653 };
654
655 let html = self
656 .fetch_html(
657 &instruction.url,
658 &host,
659 &addrs,
660 "web_scrape",
661 correlation_id,
662 caller_id,
663 )
664 .await?;
665 let selector = instruction.select.clone();
666 let extract = ExtractMode::parse(&instruction.extract);
667 let limit = instruction.limit.unwrap_or(10);
668 tokio::task::spawn_blocking(move || parse_and_extract(&html, &selector, &extract, limit))
669 .await
670 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?
671 }
672
673 fn make_blocked_event(
674 tool: &str,
675 url: &str,
676 host: &str,
677 correlation_id: &str,
678 caller_id: Option<String>,
679 block_reason: &'static str,
680 ) -> EgressEvent {
681 EgressEvent {
682 timestamp: chrono_now(),
683 kind: "egress",
684 correlation_id: correlation_id.to_owned(),
685 tool: tool.into(),
686 url: redact_url_for_log(url),
687 host: host.to_owned(),
688 method: "GET".to_owned(),
689 status: None,
690 duration_ms: 0,
691 response_bytes: 0,
692 blocked: true,
693 block_reason: Some(block_reason),
694 caller_id,
695 hop: 0,
696 }
697 }
698
699 #[allow(clippy::too_many_lines, clippy::too_many_arguments)]
710 async fn fetch_html(
711 &self,
712 url: &str,
713 host: &str,
714 addrs: &[SocketAddr],
715 tool: &str,
716 correlation_id: &str,
717 caller_id: Option<String>,
718 ) -> Result<String, ToolError> {
719 const MAX_REDIRECTS: usize = 3;
720
721 let mut current_url = url.to_owned();
722 let mut current_host = host.to_owned();
723 let mut current_addrs = addrs.to_vec();
724
725 for hop in 0..=MAX_REDIRECTS {
726 let hop_start = Instant::now();
727 let client = self.build_client(¤t_host, ¤t_addrs);
729 let resp = client
730 .get(¤t_url)
731 .send()
732 .await
733 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())));
734
735 let resp = match resp {
736 Ok(r) => r,
737 Err(e) => {
738 if self.egress_config.enabled {
739 #[allow(clippy::cast_possible_truncation)]
740 let duration_ms = hop_start.elapsed().as_millis() as u64;
741 let event = EgressEvent {
742 timestamp: chrono_now(),
743 kind: "egress",
744 correlation_id: correlation_id.to_owned(),
745 tool: tool.into(),
746 url: redact_url_for_log(¤t_url),
747 host: current_host.clone(),
748 method: "GET".to_owned(),
749 status: None,
750 duration_ms,
751 response_bytes: 0,
752 blocked: false,
753 block_reason: None,
754 caller_id: caller_id.clone(),
755 #[allow(clippy::cast_possible_truncation)]
756 hop: hop as u8,
757 };
758 self.log_egress_event(&event).await;
759 }
760 return Err(e);
761 }
762 };
763
764 let status = resp.status();
765
766 if status.is_redirection() {
767 if hop == MAX_REDIRECTS {
768 return Err(ToolError::Execution(std::io::Error::other(
769 "too many redirects",
770 )));
771 }
772
773 let location = resp
774 .headers()
775 .get(reqwest::header::LOCATION)
776 .and_then(|v| v.to_str().ok())
777 .ok_or_else(|| {
778 ToolError::Execution(std::io::Error::other("redirect with no Location"))
779 })?;
780
781 let base = Url::parse(¤t_url)
783 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
784 let next_url = base
785 .join(location)
786 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
787
788 let validated = validate_url(next_url.as_str());
789 if let Err(ref _e) = validated {
790 if self.egress_config.enabled && self.egress_config.log_blocked {
791 #[allow(clippy::cast_possible_truncation)]
792 let duration_ms = hop_start.elapsed().as_millis() as u64;
793 let next_host = next_url.host_str().unwrap_or("").to_owned();
794 let event = EgressEvent {
795 timestamp: chrono_now(),
796 kind: "egress",
797 correlation_id: correlation_id.to_owned(),
798 tool: tool.into(),
799 url: redact_url_for_log(next_url.as_str()),
800 host: next_host,
801 method: "GET".to_owned(),
802 status: None,
803 duration_ms,
804 response_bytes: 0,
805 blocked: true,
806 block_reason: Some("ssrf"),
807 caller_id: caller_id.clone(),
808 #[allow(clippy::cast_possible_truncation)]
809 hop: (hop + 1) as u8,
810 };
811 self.log_egress_event(&event).await;
812 }
813 return Err(validated.unwrap_err());
814 }
815 let validated = validated.unwrap();
816 let resolve_result = resolve_and_validate(&validated).await;
817 if let Err(ref _e) = resolve_result {
818 if self.egress_config.enabled && self.egress_config.log_blocked {
819 #[allow(clippy::cast_possible_truncation)]
820 let duration_ms = hop_start.elapsed().as_millis() as u64;
821 let next_host = next_url.host_str().unwrap_or("").to_owned();
822 let event = EgressEvent {
823 timestamp: chrono_now(),
824 kind: "egress",
825 correlation_id: correlation_id.to_owned(),
826 tool: tool.into(),
827 url: redact_url_for_log(next_url.as_str()),
828 host: next_host,
829 method: "GET".to_owned(),
830 status: None,
831 duration_ms,
832 response_bytes: 0,
833 blocked: true,
834 block_reason: Some("ssrf"),
835 caller_id: caller_id.clone(),
836 #[allow(clippy::cast_possible_truncation)]
837 hop: (hop + 1) as u8,
838 };
839 self.log_egress_event(&event).await;
840 }
841 return Err(resolve_result.unwrap_err());
842 }
843 let (next_host, next_addrs) = resolve_result.unwrap();
844
845 current_url = next_url.to_string();
846 current_host = next_host;
847 current_addrs = next_addrs;
848 continue;
849 }
850
851 if !status.is_success() {
852 if self.egress_config.enabled {
853 #[allow(clippy::cast_possible_truncation)]
854 let duration_ms = hop_start.elapsed().as_millis() as u64;
855 let event = EgressEvent {
856 timestamp: chrono_now(),
857 kind: "egress",
858 correlation_id: correlation_id.to_owned(),
859 tool: tool.into(),
860 url: current_url.clone(),
861 host: current_host.clone(),
862 method: "GET".to_owned(),
863 status: Some(status.as_u16()),
864 duration_ms,
865 response_bytes: 0,
866 blocked: false,
867 block_reason: None,
868 caller_id: caller_id.clone(),
869 #[allow(clippy::cast_possible_truncation)]
870 hop: hop as u8,
871 };
872 self.log_egress_event(&event).await;
873 }
874 return Err(ToolError::Http {
875 status: status.as_u16(),
876 message: status.canonical_reason().unwrap_or("unknown").to_owned(),
877 });
878 }
879
880 let bytes = resp
881 .bytes()
882 .await
883 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
884
885 if bytes.len() > self.max_body_bytes {
886 if self.egress_config.enabled {
887 #[allow(clippy::cast_possible_truncation)]
888 let duration_ms = hop_start.elapsed().as_millis() as u64;
889 let event = EgressEvent {
890 timestamp: chrono_now(),
891 kind: "egress",
892 correlation_id: correlation_id.to_owned(),
893 tool: tool.into(),
894 url: current_url.clone(),
895 host: current_host.clone(),
896 method: "GET".to_owned(),
897 status: Some(status.as_u16()),
898 duration_ms,
899 response_bytes: bytes.len(),
900 blocked: false,
901 block_reason: None,
902 caller_id: caller_id.clone(),
903 #[allow(clippy::cast_possible_truncation)]
904 hop: hop as u8,
905 };
906 self.log_egress_event(&event).await;
907 }
908 return Err(ToolError::Execution(std::io::Error::other(format!(
909 "response too large: {} bytes (max: {})",
910 bytes.len(),
911 self.max_body_bytes,
912 ))));
913 }
914
915 if self.egress_config.enabled {
917 #[allow(clippy::cast_possible_truncation)]
918 let duration_ms = hop_start.elapsed().as_millis() as u64;
919 let response_bytes = if self.egress_config.log_response_bytes {
920 bytes.len()
921 } else {
922 0
923 };
924 let event = EgressEvent {
925 timestamp: chrono_now(),
926 kind: "egress",
927 correlation_id: correlation_id.to_owned(),
928 tool: tool.into(),
929 url: current_url.clone(),
930 host: current_host.clone(),
931 method: "GET".to_owned(),
932 status: Some(status.as_u16()),
933 duration_ms,
934 response_bytes,
935 blocked: false,
936 block_reason: None,
937 caller_id: caller_id.clone(),
938 #[allow(clippy::cast_possible_truncation)]
939 hop: hop as u8,
940 };
941 self.log_egress_event(&event).await;
942 }
943
944 return String::from_utf8(bytes.to_vec())
945 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())));
946 }
947
948 Err(ToolError::Execution(std::io::Error::other(
949 "too many redirects",
950 )))
951 }
952}
953
954fn extract_scrape_blocks(text: &str) -> Vec<&str> {
955 crate::executor::extract_fenced_blocks(text, "scrape")
956}
957
958fn check_domain_policy(
970 host: &str,
971 allowed_domains: &[String],
972 denied_domains: &[String],
973) -> Result<(), ToolError> {
974 if denied_domains.iter().any(|p| domain_matches(p, host)) {
975 return Err(ToolError::Blocked {
976 command: format!("domain blocked by denylist: {host}"),
977 });
978 }
979 if !allowed_domains.is_empty() {
980 let is_ip = host.parse::<std::net::IpAddr>().is_ok()
982 || (host.starts_with('[') && host.ends_with(']'));
983 if is_ip {
984 return Err(ToolError::Blocked {
985 command: format!(
986 "bare IP address not allowed when domain allowlist is active: {host}"
987 ),
988 });
989 }
990 if !allowed_domains.iter().any(|p| domain_matches(p, host)) {
991 return Err(ToolError::Blocked {
992 command: format!("domain not in allowlist: {host}"),
993 });
994 }
995 }
996 Ok(())
997}
998
999use crate::domain_match::domain_matches;
1001
1002fn validate_url(raw: &str) -> Result<Url, ToolError> {
1003 let parsed = Url::parse(raw).map_err(|_| ToolError::Blocked {
1004 command: format!("invalid URL: {raw}"),
1005 })?;
1006
1007 if parsed.scheme() != "https" {
1008 return Err(ToolError::Blocked {
1009 command: format!("scheme not allowed: {}", parsed.scheme()),
1010 });
1011 }
1012
1013 if let Some(host) = parsed.host()
1014 && is_private_host(&host)
1015 {
1016 return Err(ToolError::Blocked {
1017 command: format!(
1018 "private/local host blocked: {}",
1019 parsed.host_str().unwrap_or("")
1020 ),
1021 });
1022 }
1023
1024 Ok(parsed)
1025}
1026
1027fn is_private_host(host: &url::Host<&str>) -> bool {
1028 match host {
1029 url::Host::Domain(d) => {
1030 #[allow(clippy::case_sensitive_file_extension_comparisons)]
1033 {
1034 *d == "localhost"
1035 || d.ends_with(".localhost")
1036 || d.ends_with(".internal")
1037 || d.ends_with(".local")
1038 }
1039 }
1040 url::Host::Ipv4(v4) => is_private_ip(IpAddr::V4(*v4)),
1041 url::Host::Ipv6(v6) => is_private_ip(IpAddr::V6(*v6)),
1042 }
1043}
1044
1045async fn resolve_and_validate(url: &Url) -> Result<(String, Vec<SocketAddr>), ToolError> {
1051 let Some(host) = url.host_str() else {
1052 return Ok((String::new(), vec![]));
1053 };
1054 let port = url.port_or_known_default().unwrap_or(443);
1055 let addrs: Vec<SocketAddr> = tokio::net::lookup_host(format!("{host}:{port}"))
1056 .await
1057 .map_err(|e| ToolError::Blocked {
1058 command: format!("DNS resolution failed: {e}"),
1059 })?
1060 .collect();
1061 for addr in &addrs {
1062 if is_private_ip(addr.ip()) {
1063 return Err(ToolError::Blocked {
1064 command: format!("SSRF protection: private IP {} for host {host}", addr.ip()),
1065 });
1066 }
1067 }
1068 Ok((host.to_owned(), addrs))
1069}
1070
1071fn parse_and_extract(
1072 html: &str,
1073 selector: &str,
1074 extract: &ExtractMode,
1075 limit: usize,
1076) -> Result<String, ToolError> {
1077 let soup = scrape_core::Soup::parse(html);
1078
1079 let tags = soup.find_all(selector).map_err(|e| {
1080 ToolError::Execution(std::io::Error::new(
1081 std::io::ErrorKind::InvalidData,
1082 format!("invalid selector: {e}"),
1083 ))
1084 })?;
1085
1086 let mut results = Vec::new();
1087
1088 for tag in tags.into_iter().take(limit) {
1089 let value = match extract {
1090 ExtractMode::Text => tag.text(),
1091 ExtractMode::Html => tag.inner_html(),
1092 ExtractMode::Attr(name) => tag.get(name).unwrap_or_default().to_owned(),
1093 };
1094 if !value.trim().is_empty() {
1095 results.push(value.trim().to_owned());
1096 }
1097 }
1098
1099 if results.is_empty() {
1100 Ok(format!("No results for selector: {selector}"))
1101 } else {
1102 Ok(results.join("\n"))
1103 }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108 use super::*;
1109
1110 #[test]
1113 fn extract_single_block() {
1114 let text =
1115 "Here:\n```scrape\n{\"url\":\"https://example.com\",\"select\":\"h1\"}\n```\nDone.";
1116 let blocks = extract_scrape_blocks(text);
1117 assert_eq!(blocks.len(), 1);
1118 assert!(blocks[0].contains("example.com"));
1119 }
1120
1121 #[test]
1122 fn extract_multiple_blocks() {
1123 let text = "```scrape\n{\"url\":\"https://a.com\",\"select\":\"h1\"}\n```\ntext\n```scrape\n{\"url\":\"https://b.com\",\"select\":\"p\"}\n```";
1124 let blocks = extract_scrape_blocks(text);
1125 assert_eq!(blocks.len(), 2);
1126 }
1127
1128 #[test]
1129 fn no_blocks_returns_empty() {
1130 let blocks = extract_scrape_blocks("plain text, no code blocks");
1131 assert!(blocks.is_empty());
1132 }
1133
1134 #[test]
1135 fn unclosed_block_ignored() {
1136 let blocks = extract_scrape_blocks("```scrape\n{\"url\":\"https://x.com\"}");
1137 assert!(blocks.is_empty());
1138 }
1139
1140 #[test]
1141 fn non_scrape_block_ignored() {
1142 let text =
1143 "```bash\necho hi\n```\n```scrape\n{\"url\":\"https://x.com\",\"select\":\"h1\"}\n```";
1144 let blocks = extract_scrape_blocks(text);
1145 assert_eq!(blocks.len(), 1);
1146 assert!(blocks[0].contains("x.com"));
1147 }
1148
1149 #[test]
1150 fn multiline_json_block() {
1151 let text =
1152 "```scrape\n{\n \"url\": \"https://example.com\",\n \"select\": \"h1\"\n}\n```";
1153 let blocks = extract_scrape_blocks(text);
1154 assert_eq!(blocks.len(), 1);
1155 let instr: ScrapeInstruction = serde_json::from_str(blocks[0]).unwrap();
1156 assert_eq!(instr.url, "https://example.com");
1157 }
1158
1159 #[test]
1162 fn parse_valid_instruction() {
1163 let json = r#"{"url":"https://example.com","select":"h1","extract":"text","limit":5}"#;
1164 let instr: ScrapeInstruction = serde_json::from_str(json).unwrap();
1165 assert_eq!(instr.url, "https://example.com");
1166 assert_eq!(instr.select, "h1");
1167 assert_eq!(instr.extract, "text");
1168 assert_eq!(instr.limit, Some(5));
1169 }
1170
1171 #[test]
1172 fn parse_minimal_instruction() {
1173 let json = r#"{"url":"https://example.com","select":"p"}"#;
1174 let instr: ScrapeInstruction = serde_json::from_str(json).unwrap();
1175 assert_eq!(instr.extract, "text");
1176 assert!(instr.limit.is_none());
1177 }
1178
1179 #[test]
1180 fn parse_attr_extract() {
1181 let json = r#"{"url":"https://example.com","select":"a","extract":"attr:href"}"#;
1182 let instr: ScrapeInstruction = serde_json::from_str(json).unwrap();
1183 assert_eq!(instr.extract, "attr:href");
1184 }
1185
1186 #[test]
1187 fn parse_invalid_json_errors() {
1188 let result = serde_json::from_str::<ScrapeInstruction>("not json");
1189 assert!(result.is_err());
1190 }
1191
1192 #[test]
1195 fn extract_mode_text() {
1196 assert!(matches!(ExtractMode::parse("text"), ExtractMode::Text));
1197 }
1198
1199 #[test]
1200 fn extract_mode_html() {
1201 assert!(matches!(ExtractMode::parse("html"), ExtractMode::Html));
1202 }
1203
1204 #[test]
1205 fn extract_mode_attr() {
1206 let mode = ExtractMode::parse("attr:href");
1207 assert!(matches!(mode, ExtractMode::Attr(ref s) if s == "href"));
1208 }
1209
1210 #[test]
1211 fn extract_mode_unknown_defaults_to_text() {
1212 assert!(matches!(ExtractMode::parse("unknown"), ExtractMode::Text));
1213 }
1214
1215 #[test]
1218 fn valid_https_url() {
1219 assert!(validate_url("https://example.com").is_ok());
1220 }
1221
1222 #[test]
1223 fn http_rejected() {
1224 let err = validate_url("http://example.com").unwrap_err();
1225 assert!(matches!(err, ToolError::Blocked { .. }));
1226 }
1227
1228 #[test]
1229 fn ftp_rejected() {
1230 let err = validate_url("ftp://files.example.com").unwrap_err();
1231 assert!(matches!(err, ToolError::Blocked { .. }));
1232 }
1233
1234 #[test]
1235 fn file_rejected() {
1236 let err = validate_url("file:///etc/passwd").unwrap_err();
1237 assert!(matches!(err, ToolError::Blocked { .. }));
1238 }
1239
1240 #[test]
1241 fn invalid_url_rejected() {
1242 let err = validate_url("not a url").unwrap_err();
1243 assert!(matches!(err, ToolError::Blocked { .. }));
1244 }
1245
1246 #[test]
1247 fn localhost_blocked() {
1248 let err = validate_url("https://localhost/path").unwrap_err();
1249 assert!(matches!(err, ToolError::Blocked { .. }));
1250 }
1251
1252 #[test]
1253 fn loopback_ip_blocked() {
1254 let err = validate_url("https://127.0.0.1/path").unwrap_err();
1255 assert!(matches!(err, ToolError::Blocked { .. }));
1256 }
1257
1258 #[test]
1259 fn private_10_blocked() {
1260 let err = validate_url("https://10.0.0.1/api").unwrap_err();
1261 assert!(matches!(err, ToolError::Blocked { .. }));
1262 }
1263
1264 #[test]
1265 fn private_172_blocked() {
1266 let err = validate_url("https://172.16.0.1/api").unwrap_err();
1267 assert!(matches!(err, ToolError::Blocked { .. }));
1268 }
1269
1270 #[test]
1271 fn private_192_blocked() {
1272 let err = validate_url("https://192.168.1.1/api").unwrap_err();
1273 assert!(matches!(err, ToolError::Blocked { .. }));
1274 }
1275
1276 #[test]
1277 fn ipv6_loopback_blocked() {
1278 let err = validate_url("https://[::1]/path").unwrap_err();
1279 assert!(matches!(err, ToolError::Blocked { .. }));
1280 }
1281
1282 #[test]
1283 fn public_ip_allowed() {
1284 assert!(validate_url("https://93.184.216.34/page").is_ok());
1285 }
1286
1287 #[test]
1290 fn extract_text_from_html() {
1291 let html = "<html><body><h1>Hello World</h1><p>Content</p></body></html>";
1292 let result = parse_and_extract(html, "h1", &ExtractMode::Text, 10).unwrap();
1293 assert_eq!(result, "Hello World");
1294 }
1295
1296 #[test]
1297 fn extract_multiple_elements() {
1298 let html = "<ul><li>A</li><li>B</li><li>C</li></ul>";
1299 let result = parse_and_extract(html, "li", &ExtractMode::Text, 10).unwrap();
1300 assert_eq!(result, "A\nB\nC");
1301 }
1302
1303 #[test]
1304 fn extract_with_limit() {
1305 let html = "<ul><li>A</li><li>B</li><li>C</li></ul>";
1306 let result = parse_and_extract(html, "li", &ExtractMode::Text, 2).unwrap();
1307 assert_eq!(result, "A\nB");
1308 }
1309
1310 #[test]
1311 fn extract_attr_href() {
1312 let html = r#"<a href="https://example.com">Link</a>"#;
1313 let result =
1314 parse_and_extract(html, "a", &ExtractMode::Attr("href".to_owned()), 10).unwrap();
1315 assert_eq!(result, "https://example.com");
1316 }
1317
1318 #[test]
1319 fn extract_inner_html() {
1320 let html = "<div><span>inner</span></div>";
1321 let result = parse_and_extract(html, "div", &ExtractMode::Html, 10).unwrap();
1322 assert!(result.contains("<span>inner</span>"));
1323 }
1324
1325 #[test]
1326 fn no_matches_returns_message() {
1327 let html = "<html><body><p>text</p></body></html>";
1328 let result = parse_and_extract(html, "h1", &ExtractMode::Text, 10).unwrap();
1329 assert!(result.starts_with("No results for selector:"));
1330 }
1331
1332 #[test]
1333 fn empty_text_skipped() {
1334 let html = "<ul><li> </li><li>A</li></ul>";
1335 let result = parse_and_extract(html, "li", &ExtractMode::Text, 10).unwrap();
1336 assert_eq!(result, "A");
1337 }
1338
1339 #[test]
1340 fn invalid_selector_errors() {
1341 let html = "<html><body></body></html>";
1342 let result = parse_and_extract(html, "[[[invalid", &ExtractMode::Text, 10);
1343 assert!(result.is_err());
1344 }
1345
1346 #[test]
1347 fn empty_html_returns_no_results() {
1348 let result = parse_and_extract("", "h1", &ExtractMode::Text, 10).unwrap();
1349 assert!(result.starts_with("No results for selector:"));
1350 }
1351
1352 #[test]
1353 fn nested_selector() {
1354 let html = "<div><span>inner</span></div><span>outer</span>";
1355 let result = parse_and_extract(html, "div > span", &ExtractMode::Text, 10).unwrap();
1356 assert_eq!(result, "inner");
1357 }
1358
1359 #[test]
1360 fn attr_missing_returns_empty() {
1361 let html = r"<a>No href</a>";
1362 let result =
1363 parse_and_extract(html, "a", &ExtractMode::Attr("href".to_owned()), 10).unwrap();
1364 assert!(result.starts_with("No results for selector:"));
1365 }
1366
1367 #[test]
1368 fn extract_html_mode() {
1369 let html = "<div><b>bold</b> text</div>";
1370 let result = parse_and_extract(html, "div", &ExtractMode::Html, 10).unwrap();
1371 assert!(result.contains("<b>bold</b>"));
1372 }
1373
1374 #[test]
1375 fn limit_zero_returns_no_results() {
1376 let html = "<ul><li>A</li><li>B</li></ul>";
1377 let result = parse_and_extract(html, "li", &ExtractMode::Text, 0).unwrap();
1378 assert!(result.starts_with("No results for selector:"));
1379 }
1380
1381 #[test]
1384 fn url_with_port_allowed() {
1385 assert!(validate_url("https://example.com:8443/path").is_ok());
1386 }
1387
1388 #[test]
1389 fn link_local_ip_blocked() {
1390 let err = validate_url("https://169.254.1.1/path").unwrap_err();
1391 assert!(matches!(err, ToolError::Blocked { .. }));
1392 }
1393
1394 #[test]
1395 fn url_no_scheme_rejected() {
1396 let err = validate_url("example.com/path").unwrap_err();
1397 assert!(matches!(err, ToolError::Blocked { .. }));
1398 }
1399
1400 #[test]
1401 fn unspecified_ipv4_blocked() {
1402 let err = validate_url("https://0.0.0.0/path").unwrap_err();
1403 assert!(matches!(err, ToolError::Blocked { .. }));
1404 }
1405
1406 #[test]
1407 fn broadcast_ipv4_blocked() {
1408 let err = validate_url("https://255.255.255.255/path").unwrap_err();
1409 assert!(matches!(err, ToolError::Blocked { .. }));
1410 }
1411
1412 #[test]
1413 fn ipv6_link_local_blocked() {
1414 let err = validate_url("https://[fe80::1]/path").unwrap_err();
1415 assert!(matches!(err, ToolError::Blocked { .. }));
1416 }
1417
1418 #[test]
1419 fn ipv6_unique_local_blocked() {
1420 let err = validate_url("https://[fd12::1]/path").unwrap_err();
1421 assert!(matches!(err, ToolError::Blocked { .. }));
1422 }
1423
1424 #[test]
1425 fn ipv4_mapped_ipv6_loopback_blocked() {
1426 let err = validate_url("https://[::ffff:127.0.0.1]/path").unwrap_err();
1427 assert!(matches!(err, ToolError::Blocked { .. }));
1428 }
1429
1430 #[test]
1431 fn ipv4_mapped_ipv6_private_blocked() {
1432 let err = validate_url("https://[::ffff:10.0.0.1]/path").unwrap_err();
1433 assert!(matches!(err, ToolError::Blocked { .. }));
1434 }
1435
1436 #[tokio::test]
1439 async fn executor_no_blocks_returns_none() {
1440 let config = ScrapeConfig::default();
1441 let executor = WebScrapeExecutor::new(&config);
1442 let result = executor.execute("plain text").await;
1443 assert!(result.unwrap().is_none());
1444 }
1445
1446 #[tokio::test]
1447 async fn executor_invalid_json_errors() {
1448 let config = ScrapeConfig::default();
1449 let executor = WebScrapeExecutor::new(&config);
1450 let response = "```scrape\nnot json\n```";
1451 let result = executor.execute(response).await;
1452 assert!(matches!(result, Err(ToolError::Execution(_))));
1453 }
1454
1455 #[tokio::test]
1456 async fn executor_blocked_url_errors() {
1457 let config = ScrapeConfig::default();
1458 let executor = WebScrapeExecutor::new(&config);
1459 let response = "```scrape\n{\"url\":\"http://example.com\",\"select\":\"h1\"}\n```";
1460 let result = executor.execute(response).await;
1461 assert!(matches!(result, Err(ToolError::Blocked { .. })));
1462 }
1463
1464 #[tokio::test]
1465 async fn executor_private_ip_blocked() {
1466 let config = ScrapeConfig::default();
1467 let executor = WebScrapeExecutor::new(&config);
1468 let response = "```scrape\n{\"url\":\"https://192.168.1.1/api\",\"select\":\"h1\"}\n```";
1469 let result = executor.execute(response).await;
1470 assert!(matches!(result, Err(ToolError::Blocked { .. })));
1471 }
1472
1473 #[tokio::test]
1474 async fn executor_unreachable_host_returns_error() {
1475 let config = ScrapeConfig {
1476 timeout: 1,
1477 max_body_bytes: 1_048_576,
1478 ..Default::default()
1479 };
1480 let executor = WebScrapeExecutor::new(&config);
1481 let response = "```scrape\n{\"url\":\"https://192.0.2.1:1/page\",\"select\":\"h1\"}\n```";
1482 let result = executor.execute(response).await;
1483 assert!(matches!(result, Err(ToolError::Execution(_))));
1484 }
1485
1486 #[tokio::test]
1487 async fn executor_localhost_url_blocked() {
1488 let config = ScrapeConfig::default();
1489 let executor = WebScrapeExecutor::new(&config);
1490 let response = "```scrape\n{\"url\":\"https://localhost:9999/api\",\"select\":\"h1\"}\n```";
1491 let result = executor.execute(response).await;
1492 assert!(matches!(result, Err(ToolError::Blocked { .. })));
1493 }
1494
1495 #[tokio::test]
1496 async fn executor_empty_text_returns_none() {
1497 let config = ScrapeConfig::default();
1498 let executor = WebScrapeExecutor::new(&config);
1499 let result = executor.execute("").await;
1500 assert!(result.unwrap().is_none());
1501 }
1502
1503 #[tokio::test]
1504 async fn executor_multiple_blocks_first_blocked() {
1505 let config = ScrapeConfig::default();
1506 let executor = WebScrapeExecutor::new(&config);
1507 let response = "```scrape\n{\"url\":\"http://evil.com\",\"select\":\"h1\"}\n```\n\
1508 ```scrape\n{\"url\":\"https://ok.com\",\"select\":\"h1\"}\n```";
1509 let result = executor.execute(response).await;
1510 assert!(result.is_err());
1511 }
1512
1513 #[test]
1514 fn validate_url_empty_string() {
1515 let err = validate_url("").unwrap_err();
1516 assert!(matches!(err, ToolError::Blocked { .. }));
1517 }
1518
1519 #[test]
1520 fn validate_url_javascript_scheme_blocked() {
1521 let err = validate_url("javascript:alert(1)").unwrap_err();
1522 assert!(matches!(err, ToolError::Blocked { .. }));
1523 }
1524
1525 #[test]
1526 fn validate_url_data_scheme_blocked() {
1527 let err = validate_url("data:text/html,<h1>hi</h1>").unwrap_err();
1528 assert!(matches!(err, ToolError::Blocked { .. }));
1529 }
1530
1531 #[test]
1532 fn is_private_host_public_domain_is_false() {
1533 let host: url::Host<&str> = url::Host::Domain("example.com");
1534 assert!(!is_private_host(&host));
1535 }
1536
1537 #[test]
1538 fn is_private_host_localhost_is_true() {
1539 let host: url::Host<&str> = url::Host::Domain("localhost");
1540 assert!(is_private_host(&host));
1541 }
1542
1543 #[test]
1544 fn is_private_host_ipv6_unspecified_is_true() {
1545 let host = url::Host::Ipv6(std::net::Ipv6Addr::UNSPECIFIED);
1546 assert!(is_private_host(&host));
1547 }
1548
1549 #[test]
1550 fn is_private_host_public_ipv6_is_false() {
1551 let host = url::Host::Ipv6("2001:db8::1".parse().unwrap());
1552 assert!(!is_private_host(&host));
1553 }
1554
1555 async fn mock_server_executor() -> (WebScrapeExecutor, wiremock::MockServer) {
1566 let server = wiremock::MockServer::start().await;
1567 let executor = WebScrapeExecutor {
1568 timeout: Duration::from_secs(5),
1569 max_body_bytes: 1_048_576,
1570 allowed_domains: vec![],
1571 denied_domains: vec![],
1572 audit_logger: None,
1573 egress_config: EgressConfig::default(),
1574 egress_tx: None,
1575 egress_dropped: Arc::new(AtomicU64::new(0)),
1576 };
1577 (executor, server)
1578 }
1579
1580 fn server_host_and_addr(server: &wiremock::MockServer) -> (String, Vec<std::net::SocketAddr>) {
1582 let uri = server.uri();
1583 let url = Url::parse(&uri).unwrap();
1584 let host = url.host_str().unwrap_or("127.0.0.1").to_owned();
1585 let port = url.port().unwrap_or(80);
1586 let addr: std::net::SocketAddr = format!("{host}:{port}").parse().unwrap();
1587 (host, vec![addr])
1588 }
1589
1590 async fn follow_redirects_raw(
1594 executor: &WebScrapeExecutor,
1595 start_url: &str,
1596 host: &str,
1597 addrs: &[std::net::SocketAddr],
1598 ) -> Result<String, ToolError> {
1599 const MAX_REDIRECTS: usize = 3;
1600 let mut current_url = start_url.to_owned();
1601 let mut current_host = host.to_owned();
1602 let mut current_addrs = addrs.to_vec();
1603
1604 for hop in 0..=MAX_REDIRECTS {
1605 let client = executor.build_client(¤t_host, ¤t_addrs);
1606 let resp = client
1607 .get(¤t_url)
1608 .send()
1609 .await
1610 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
1611
1612 let status = resp.status();
1613
1614 if status.is_redirection() {
1615 if hop == MAX_REDIRECTS {
1616 return Err(ToolError::Execution(std::io::Error::other(
1617 "too many redirects",
1618 )));
1619 }
1620
1621 let location = resp
1622 .headers()
1623 .get(reqwest::header::LOCATION)
1624 .and_then(|v| v.to_str().ok())
1625 .ok_or_else(|| {
1626 ToolError::Execution(std::io::Error::other("redirect with no Location"))
1627 })?;
1628
1629 let base = Url::parse(¤t_url)
1630 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
1631 let next_url = base
1632 .join(location)
1633 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
1634
1635 current_url = next_url.to_string();
1637 let _ = &mut current_host;
1639 let _ = &mut current_addrs;
1640 continue;
1641 }
1642
1643 if !status.is_success() {
1644 return Err(ToolError::Execution(std::io::Error::other(format!(
1645 "HTTP {status}",
1646 ))));
1647 }
1648
1649 let bytes = resp
1650 .bytes()
1651 .await
1652 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
1653
1654 if bytes.len() > executor.max_body_bytes {
1655 return Err(ToolError::Execution(std::io::Error::other(format!(
1656 "response too large: {} bytes (max: {})",
1657 bytes.len(),
1658 executor.max_body_bytes,
1659 ))));
1660 }
1661
1662 return String::from_utf8(bytes.to_vec())
1663 .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())));
1664 }
1665
1666 Err(ToolError::Execution(std::io::Error::other(
1667 "too many redirects",
1668 )))
1669 }
1670
1671 #[tokio::test]
1672 async fn fetch_html_success_returns_body() {
1673 use wiremock::matchers::{method, path};
1674 use wiremock::{Mock, ResponseTemplate};
1675
1676 let (executor, server) = mock_server_executor().await;
1677 Mock::given(method("GET"))
1678 .and(path("/page"))
1679 .respond_with(ResponseTemplate::new(200).set_body_string("<h1>OK</h1>"))
1680 .mount(&server)
1681 .await;
1682
1683 let (host, addrs) = server_host_and_addr(&server);
1684 let url = format!("{}/page", server.uri());
1685 let result = executor
1686 .fetch_html(&url, &host, &addrs, "fetch", "test-cid", None)
1687 .await;
1688 assert!(result.is_ok(), "expected Ok, got: {result:?}");
1689 assert_eq!(result.unwrap(), "<h1>OK</h1>");
1690 }
1691
1692 #[tokio::test]
1693 async fn fetch_html_non_2xx_returns_error() {
1694 use wiremock::matchers::{method, path};
1695 use wiremock::{Mock, ResponseTemplate};
1696
1697 let (executor, server) = mock_server_executor().await;
1698 Mock::given(method("GET"))
1699 .and(path("/forbidden"))
1700 .respond_with(ResponseTemplate::new(403))
1701 .mount(&server)
1702 .await;
1703
1704 let (host, addrs) = server_host_and_addr(&server);
1705 let url = format!("{}/forbidden", server.uri());
1706 let result = executor
1707 .fetch_html(&url, &host, &addrs, "fetch", "test-cid", None)
1708 .await;
1709 assert!(result.is_err());
1710 let msg = result.unwrap_err().to_string();
1711 assert!(msg.contains("403"), "expected 403 in error: {msg}");
1712 }
1713
1714 #[tokio::test]
1715 async fn fetch_html_404_returns_error() {
1716 use wiremock::matchers::{method, path};
1717 use wiremock::{Mock, ResponseTemplate};
1718
1719 let (executor, server) = mock_server_executor().await;
1720 Mock::given(method("GET"))
1721 .and(path("/missing"))
1722 .respond_with(ResponseTemplate::new(404))
1723 .mount(&server)
1724 .await;
1725
1726 let (host, addrs) = server_host_and_addr(&server);
1727 let url = format!("{}/missing", server.uri());
1728 let result = executor
1729 .fetch_html(&url, &host, &addrs, "fetch", "test-cid", None)
1730 .await;
1731 assert!(result.is_err());
1732 let msg = result.unwrap_err().to_string();
1733 assert!(msg.contains("404"), "expected 404 in error: {msg}");
1734 }
1735
1736 #[tokio::test]
1737 async fn fetch_html_redirect_no_location_returns_error() {
1738 use wiremock::matchers::{method, path};
1739 use wiremock::{Mock, ResponseTemplate};
1740
1741 let (executor, server) = mock_server_executor().await;
1742 Mock::given(method("GET"))
1744 .and(path("/redirect-no-loc"))
1745 .respond_with(ResponseTemplate::new(302))
1746 .mount(&server)
1747 .await;
1748
1749 let (host, addrs) = server_host_and_addr(&server);
1750 let url = format!("{}/redirect-no-loc", server.uri());
1751 let result = executor
1752 .fetch_html(&url, &host, &addrs, "fetch", "test-cid", None)
1753 .await;
1754 assert!(result.is_err());
1755 let msg = result.unwrap_err().to_string();
1756 assert!(
1757 msg.contains("Location") || msg.contains("location"),
1758 "expected Location-related error: {msg}"
1759 );
1760 }
1761
1762 #[tokio::test]
1763 async fn fetch_html_single_redirect_followed() {
1764 use wiremock::matchers::{method, path};
1765 use wiremock::{Mock, ResponseTemplate};
1766
1767 let (executor, server) = mock_server_executor().await;
1768 let final_url = format!("{}/final", server.uri());
1769
1770 Mock::given(method("GET"))
1771 .and(path("/start"))
1772 .respond_with(ResponseTemplate::new(302).insert_header("location", final_url.as_str()))
1773 .mount(&server)
1774 .await;
1775
1776 Mock::given(method("GET"))
1777 .and(path("/final"))
1778 .respond_with(ResponseTemplate::new(200).set_body_string("<p>final</p>"))
1779 .mount(&server)
1780 .await;
1781
1782 let (host, addrs) = server_host_and_addr(&server);
1783 let url = format!("{}/start", server.uri());
1784 let result = follow_redirects_raw(&executor, &url, &host, &addrs).await;
1785 assert!(result.is_ok(), "single redirect should succeed: {result:?}");
1786 assert_eq!(result.unwrap(), "<p>final</p>");
1787 }
1788
1789 #[tokio::test]
1790 async fn fetch_html_three_redirects_allowed() {
1791 use wiremock::matchers::{method, path};
1792 use wiremock::{Mock, ResponseTemplate};
1793
1794 let (executor, server) = mock_server_executor().await;
1795 let hop2 = format!("{}/hop2", server.uri());
1796 let hop3 = format!("{}/hop3", server.uri());
1797 let final_dest = format!("{}/done", server.uri());
1798
1799 Mock::given(method("GET"))
1800 .and(path("/hop1"))
1801 .respond_with(ResponseTemplate::new(301).insert_header("location", hop2.as_str()))
1802 .mount(&server)
1803 .await;
1804 Mock::given(method("GET"))
1805 .and(path("/hop2"))
1806 .respond_with(ResponseTemplate::new(301).insert_header("location", hop3.as_str()))
1807 .mount(&server)
1808 .await;
1809 Mock::given(method("GET"))
1810 .and(path("/hop3"))
1811 .respond_with(ResponseTemplate::new(301).insert_header("location", final_dest.as_str()))
1812 .mount(&server)
1813 .await;
1814 Mock::given(method("GET"))
1815 .and(path("/done"))
1816 .respond_with(ResponseTemplate::new(200).set_body_string("<p>done</p>"))
1817 .mount(&server)
1818 .await;
1819
1820 let (host, addrs) = server_host_and_addr(&server);
1821 let url = format!("{}/hop1", server.uri());
1822 let result = follow_redirects_raw(&executor, &url, &host, &addrs).await;
1823 assert!(result.is_ok(), "3 redirects should succeed: {result:?}");
1824 assert_eq!(result.unwrap(), "<p>done</p>");
1825 }
1826
1827 #[tokio::test]
1828 async fn fetch_html_four_redirects_rejected() {
1829 use wiremock::matchers::{method, path};
1830 use wiremock::{Mock, ResponseTemplate};
1831
1832 let (executor, server) = mock_server_executor().await;
1833 let hop2 = format!("{}/r2", server.uri());
1834 let hop3 = format!("{}/r3", server.uri());
1835 let hop4 = format!("{}/r4", server.uri());
1836 let hop5 = format!("{}/r5", server.uri());
1837
1838 for (from, to) in [
1839 ("/r1", &hop2),
1840 ("/r2", &hop3),
1841 ("/r3", &hop4),
1842 ("/r4", &hop5),
1843 ] {
1844 Mock::given(method("GET"))
1845 .and(path(from))
1846 .respond_with(ResponseTemplate::new(301).insert_header("location", to.as_str()))
1847 .mount(&server)
1848 .await;
1849 }
1850
1851 let (host, addrs) = server_host_and_addr(&server);
1852 let url = format!("{}/r1", server.uri());
1853 let result = follow_redirects_raw(&executor, &url, &host, &addrs).await;
1854 assert!(result.is_err(), "4 redirects should be rejected");
1855 let msg = result.unwrap_err().to_string();
1856 assert!(
1857 msg.contains("redirect"),
1858 "expected redirect-related error: {msg}"
1859 );
1860 }
1861
1862 #[tokio::test]
1863 async fn fetch_html_body_too_large_returns_error() {
1864 use wiremock::matchers::{method, path};
1865 use wiremock::{Mock, ResponseTemplate};
1866
1867 let small_limit_executor = WebScrapeExecutor {
1868 timeout: Duration::from_secs(5),
1869 max_body_bytes: 10,
1870 allowed_domains: vec![],
1871 denied_domains: vec![],
1872 audit_logger: None,
1873 egress_config: EgressConfig::default(),
1874 egress_tx: None,
1875 egress_dropped: Arc::new(AtomicU64::new(0)),
1876 };
1877 let server = wiremock::MockServer::start().await;
1878 Mock::given(method("GET"))
1879 .and(path("/big"))
1880 .respond_with(
1881 ResponseTemplate::new(200)
1882 .set_body_string("this body is definitely longer than ten bytes"),
1883 )
1884 .mount(&server)
1885 .await;
1886
1887 let (host, addrs) = server_host_and_addr(&server);
1888 let url = format!("{}/big", server.uri());
1889 let result = small_limit_executor
1890 .fetch_html(&url, &host, &addrs, "fetch", "test-cid", None)
1891 .await;
1892 assert!(result.is_err());
1893 let msg = result.unwrap_err().to_string();
1894 assert!(msg.contains("too large"), "expected too-large error: {msg}");
1895 }
1896
1897 #[test]
1898 fn extract_scrape_blocks_empty_block_content() {
1899 let text = "```scrape\n\n```";
1900 let blocks = extract_scrape_blocks(text);
1901 assert_eq!(blocks.len(), 1);
1902 assert!(blocks[0].is_empty());
1903 }
1904
1905 #[test]
1906 fn extract_scrape_blocks_whitespace_only() {
1907 let text = "```scrape\n \n```";
1908 let blocks = extract_scrape_blocks(text);
1909 assert_eq!(blocks.len(), 1);
1910 }
1911
1912 #[test]
1913 fn parse_and_extract_multiple_selectors() {
1914 let html = "<div><h1>Title</h1><p>Para</p></div>";
1915 let result = parse_and_extract(html, "h1, p", &ExtractMode::Text, 10).unwrap();
1916 assert!(result.contains("Title"));
1917 assert!(result.contains("Para"));
1918 }
1919
1920 #[test]
1921 fn webscrape_executor_new_with_custom_config() {
1922 let config = ScrapeConfig {
1923 timeout: 60,
1924 max_body_bytes: 512,
1925 ..Default::default()
1926 };
1927 let executor = WebScrapeExecutor::new(&config);
1928 assert_eq!(executor.max_body_bytes, 512);
1929 }
1930
1931 #[test]
1932 fn webscrape_executor_debug() {
1933 let config = ScrapeConfig::default();
1934 let executor = WebScrapeExecutor::new(&config);
1935 let dbg = format!("{executor:?}");
1936 assert!(dbg.contains("WebScrapeExecutor"));
1937 }
1938
1939 #[test]
1940 fn extract_mode_attr_empty_name() {
1941 let mode = ExtractMode::parse("attr:");
1942 assert!(matches!(mode, ExtractMode::Attr(ref s) if s.is_empty()));
1943 }
1944
1945 #[test]
1946 fn default_extract_returns_text() {
1947 assert_eq!(default_extract(), "text");
1948 }
1949
1950 #[test]
1951 fn scrape_instruction_debug() {
1952 let json = r#"{"url":"https://example.com","select":"h1"}"#;
1953 let instr: ScrapeInstruction = serde_json::from_str(json).unwrap();
1954 let dbg = format!("{instr:?}");
1955 assert!(dbg.contains("ScrapeInstruction"));
1956 }
1957
1958 #[test]
1959 fn extract_mode_debug() {
1960 let mode = ExtractMode::Text;
1961 let dbg = format!("{mode:?}");
1962 assert!(dbg.contains("Text"));
1963 }
1964
1965 #[test]
1970 fn max_redirects_constant_is_three() {
1971 const MAX_REDIRECTS: usize = 3;
1975 assert_eq!(MAX_REDIRECTS, 3, "fetch_html allows exactly 3 redirects");
1976 }
1977
1978 #[test]
1981 fn redirect_no_location_error_message() {
1982 let err = std::io::Error::other("redirect with no Location");
1983 assert!(err.to_string().contains("redirect with no Location"));
1984 }
1985
1986 #[test]
1988 fn too_many_redirects_error_message() {
1989 let err = std::io::Error::other("too many redirects");
1990 assert!(err.to_string().contains("too many redirects"));
1991 }
1992
1993 #[test]
1995 fn non_2xx_status_error_format() {
1996 let status = reqwest::StatusCode::FORBIDDEN;
1997 let msg = format!("HTTP {status}");
1998 assert!(msg.contains("403"));
1999 }
2000
2001 #[test]
2003 fn not_found_status_error_format() {
2004 let status = reqwest::StatusCode::NOT_FOUND;
2005 let msg = format!("HTTP {status}");
2006 assert!(msg.contains("404"));
2007 }
2008
2009 #[test]
2011 fn relative_redirect_same_host_path() {
2012 let base = Url::parse("https://example.com/current").unwrap();
2013 let resolved = base.join("/other").unwrap();
2014 assert_eq!(resolved.as_str(), "https://example.com/other");
2015 }
2016
2017 #[test]
2019 fn relative_redirect_relative_path() {
2020 let base = Url::parse("https://example.com/a/b").unwrap();
2021 let resolved = base.join("c").unwrap();
2022 assert_eq!(resolved.as_str(), "https://example.com/a/c");
2023 }
2024
2025 #[test]
2027 fn absolute_redirect_overrides_base() {
2028 let base = Url::parse("https://example.com/page").unwrap();
2029 let resolved = base.join("https://other.com/target").unwrap();
2030 assert_eq!(resolved.as_str(), "https://other.com/target");
2031 }
2032
2033 #[test]
2035 fn redirect_http_downgrade_rejected() {
2036 let location = "http://example.com/page";
2037 let base = Url::parse("https://example.com/start").unwrap();
2038 let next = base.join(location).unwrap();
2039 let err = validate_url(next.as_str()).unwrap_err();
2040 assert!(matches!(err, ToolError::Blocked { .. }));
2041 }
2042
2043 #[test]
2045 fn redirect_location_private_ip_blocked() {
2046 let location = "https://192.168.100.1/admin";
2047 let base = Url::parse("https://example.com/start").unwrap();
2048 let next = base.join(location).unwrap();
2049 let err = validate_url(next.as_str()).unwrap_err();
2050 assert!(matches!(err, ToolError::Blocked { .. }));
2051 let ToolError::Blocked { command: cmd } = err else {
2052 panic!("expected Blocked");
2053 };
2054 assert!(
2055 cmd.contains("private") || cmd.contains("scheme"),
2056 "error message should describe the block reason: {cmd}"
2057 );
2058 }
2059
2060 #[test]
2062 fn redirect_location_internal_domain_blocked() {
2063 let location = "https://metadata.internal/latest/meta-data/";
2064 let base = Url::parse("https://example.com/start").unwrap();
2065 let next = base.join(location).unwrap();
2066 let err = validate_url(next.as_str()).unwrap_err();
2067 assert!(matches!(err, ToolError::Blocked { .. }));
2068 }
2069
2070 #[test]
2072 fn redirect_chain_three_hops_all_public() {
2073 let hops = [
2074 "https://redirect1.example.com/hop1",
2075 "https://redirect2.example.com/hop2",
2076 "https://destination.example.com/final",
2077 ];
2078 for hop in hops {
2079 assert!(validate_url(hop).is_ok(), "expected ok for {hop}");
2080 }
2081 }
2082
2083 #[test]
2088 fn redirect_to_private_ip_rejected_by_validate_url() {
2089 let private_targets = [
2091 "https://127.0.0.1/secret",
2092 "https://10.0.0.1/internal",
2093 "https://192.168.1.1/admin",
2094 "https://172.16.0.1/data",
2095 "https://[::1]/path",
2096 "https://[fe80::1]/path",
2097 "https://localhost/path",
2098 "https://service.internal/api",
2099 ];
2100 for target in private_targets {
2101 let result = validate_url(target);
2102 assert!(result.is_err(), "expected error for {target}");
2103 assert!(
2104 matches!(result.unwrap_err(), ToolError::Blocked { .. }),
2105 "expected Blocked for {target}"
2106 );
2107 }
2108 }
2109
2110 #[test]
2112 fn redirect_relative_url_resolves_correctly() {
2113 let base = Url::parse("https://example.com/page").unwrap();
2114 let relative = "/other";
2115 let resolved = base.join(relative).unwrap();
2116 assert_eq!(resolved.as_str(), "https://example.com/other");
2117 }
2118
2119 #[test]
2121 fn redirect_to_http_rejected() {
2122 let err = validate_url("http://example.com/page").unwrap_err();
2123 assert!(matches!(err, ToolError::Blocked { .. }));
2124 }
2125
2126 #[test]
2127 fn ipv4_mapped_ipv6_link_local_blocked() {
2128 let err = validate_url("https://[::ffff:169.254.0.1]/path").unwrap_err();
2129 assert!(matches!(err, ToolError::Blocked { .. }));
2130 }
2131
2132 #[test]
2133 fn ipv4_mapped_ipv6_public_allowed() {
2134 assert!(validate_url("https://[::ffff:93.184.216.34]/path").is_ok());
2135 }
2136
2137 #[tokio::test]
2140 async fn fetch_http_scheme_blocked() {
2141 let config = ScrapeConfig::default();
2142 let executor = WebScrapeExecutor::new(&config);
2143 let call = crate::executor::ToolCall {
2144 tool_id: ToolName::new("fetch"),
2145 params: {
2146 let mut m = serde_json::Map::new();
2147 m.insert("url".to_owned(), serde_json::json!("http://example.com"));
2148 m
2149 },
2150 caller_id: None,
2151 };
2152 let result = executor.execute_tool_call(&call).await;
2153 assert!(matches!(result, Err(ToolError::Blocked { .. })));
2154 }
2155
2156 #[tokio::test]
2157 async fn fetch_private_ip_blocked() {
2158 let config = ScrapeConfig::default();
2159 let executor = WebScrapeExecutor::new(&config);
2160 let call = crate::executor::ToolCall {
2161 tool_id: ToolName::new("fetch"),
2162 params: {
2163 let mut m = serde_json::Map::new();
2164 m.insert(
2165 "url".to_owned(),
2166 serde_json::json!("https://192.168.1.1/secret"),
2167 );
2168 m
2169 },
2170 caller_id: None,
2171 };
2172 let result = executor.execute_tool_call(&call).await;
2173 assert!(matches!(result, Err(ToolError::Blocked { .. })));
2174 }
2175
2176 #[tokio::test]
2177 async fn fetch_localhost_blocked() {
2178 let config = ScrapeConfig::default();
2179 let executor = WebScrapeExecutor::new(&config);
2180 let call = crate::executor::ToolCall {
2181 tool_id: ToolName::new("fetch"),
2182 params: {
2183 let mut m = serde_json::Map::new();
2184 m.insert(
2185 "url".to_owned(),
2186 serde_json::json!("https://localhost/page"),
2187 );
2188 m
2189 },
2190 caller_id: None,
2191 };
2192 let result = executor.execute_tool_call(&call).await;
2193 assert!(matches!(result, Err(ToolError::Blocked { .. })));
2194 }
2195
2196 #[tokio::test]
2197 async fn fetch_unknown_tool_returns_none() {
2198 let config = ScrapeConfig::default();
2199 let executor = WebScrapeExecutor::new(&config);
2200 let call = crate::executor::ToolCall {
2201 tool_id: ToolName::new("unknown_tool"),
2202 params: serde_json::Map::new(),
2203 caller_id: None,
2204 };
2205 let result = executor.execute_tool_call(&call).await;
2206 assert!(result.unwrap().is_none());
2207 }
2208
2209 #[tokio::test]
2210 async fn fetch_returns_body_via_mock() {
2211 use wiremock::matchers::{method, path};
2212 use wiremock::{Mock, ResponseTemplate};
2213
2214 let (executor, server) = mock_server_executor().await;
2215 Mock::given(method("GET"))
2216 .and(path("/content"))
2217 .respond_with(ResponseTemplate::new(200).set_body_string("plain text content"))
2218 .mount(&server)
2219 .await;
2220
2221 let (host, addrs) = server_host_and_addr(&server);
2222 let url = format!("{}/content", server.uri());
2223 let result = executor
2224 .fetch_html(&url, &host, &addrs, "fetch", "test-cid", None)
2225 .await;
2226 assert!(result.is_ok());
2227 assert_eq!(result.unwrap(), "plain text content");
2228 }
2229
2230 #[test]
2231 fn tool_definitions_returns_web_scrape_and_fetch() {
2232 let config = ScrapeConfig::default();
2233 let executor = WebScrapeExecutor::new(&config);
2234 let defs = executor.tool_definitions();
2235 assert_eq!(defs.len(), 2);
2236 assert_eq!(defs[0].id, "web_scrape");
2237 assert_eq!(
2238 defs[0].invocation,
2239 crate::registry::InvocationHint::FencedBlock("scrape")
2240 );
2241 assert_eq!(defs[1].id, "fetch");
2242 assert_eq!(
2243 defs[1].invocation,
2244 crate::registry::InvocationHint::ToolCall
2245 );
2246 }
2247
2248 #[test]
2249 fn tool_definitions_schema_has_all_params() {
2250 let config = ScrapeConfig::default();
2251 let executor = WebScrapeExecutor::new(&config);
2252 let defs = executor.tool_definitions();
2253 let obj = defs[0].schema.as_object().unwrap();
2254 let props = obj["properties"].as_object().unwrap();
2255 assert!(props.contains_key("url"));
2256 assert!(props.contains_key("select"));
2257 assert!(props.contains_key("extract"));
2258 assert!(props.contains_key("limit"));
2259 let req = obj["required"].as_array().unwrap();
2260 assert!(req.iter().any(|v| v.as_str() == Some("url")));
2261 assert!(req.iter().any(|v| v.as_str() == Some("select")));
2262 assert!(!req.iter().any(|v| v.as_str() == Some("extract")));
2263 }
2264
2265 #[test]
2268 fn subdomain_localhost_blocked() {
2269 let host: url::Host<&str> = url::Host::Domain("foo.localhost");
2270 assert!(is_private_host(&host));
2271 }
2272
2273 #[test]
2274 fn internal_tld_blocked() {
2275 let host: url::Host<&str> = url::Host::Domain("service.internal");
2276 assert!(is_private_host(&host));
2277 }
2278
2279 #[test]
2280 fn local_tld_blocked() {
2281 let host: url::Host<&str> = url::Host::Domain("printer.local");
2282 assert!(is_private_host(&host));
2283 }
2284
2285 #[test]
2286 fn public_domain_not_blocked() {
2287 let host: url::Host<&str> = url::Host::Domain("example.com");
2288 assert!(!is_private_host(&host));
2289 }
2290
2291 #[tokio::test]
2294 async fn resolve_loopback_rejected() {
2295 let url = url::Url::parse("https://127.0.0.1/path").unwrap();
2297 let result = resolve_and_validate(&url).await;
2299 assert!(
2300 result.is_err(),
2301 "loopback IP must be rejected by resolve_and_validate"
2302 );
2303 let err = result.unwrap_err();
2304 assert!(matches!(err, crate::executor::ToolError::Blocked { .. }));
2305 }
2306
2307 #[tokio::test]
2308 async fn resolve_private_10_rejected() {
2309 let url = url::Url::parse("https://10.0.0.1/path").unwrap();
2310 let result = resolve_and_validate(&url).await;
2311 assert!(result.is_err());
2312 assert!(matches!(
2313 result.unwrap_err(),
2314 crate::executor::ToolError::Blocked { .. }
2315 ));
2316 }
2317
2318 #[tokio::test]
2319 async fn resolve_private_192_rejected() {
2320 let url = url::Url::parse("https://192.168.1.1/path").unwrap();
2321 let result = resolve_and_validate(&url).await;
2322 assert!(result.is_err());
2323 assert!(matches!(
2324 result.unwrap_err(),
2325 crate::executor::ToolError::Blocked { .. }
2326 ));
2327 }
2328
2329 #[tokio::test]
2330 async fn resolve_ipv6_loopback_rejected() {
2331 let url = url::Url::parse("https://[::1]/path").unwrap();
2332 let result = resolve_and_validate(&url).await;
2333 assert!(result.is_err());
2334 assert!(matches!(
2335 result.unwrap_err(),
2336 crate::executor::ToolError::Blocked { .. }
2337 ));
2338 }
2339
2340 #[tokio::test]
2341 async fn resolve_no_host_returns_ok() {
2342 let url = url::Url::parse("https://example.com/path").unwrap();
2344 let url_no_host = url::Url::parse("data:text/plain,hello").unwrap();
2346 let result = resolve_and_validate(&url_no_host).await;
2348 assert!(result.is_ok());
2349 let (host, addrs) = result.unwrap();
2350 assert!(host.is_empty());
2351 assert!(addrs.is_empty());
2352 drop(url);
2353 drop(url_no_host);
2354 }
2355
2356 async fn make_file_audit_logger(
2360 dir: &tempfile::TempDir,
2361 ) -> (
2362 std::sync::Arc<crate::audit::AuditLogger>,
2363 std::path::PathBuf,
2364 ) {
2365 use crate::audit::AuditLogger;
2366 use crate::config::AuditConfig;
2367 let path = dir.path().join("audit.log");
2368 let config = AuditConfig {
2369 enabled: true,
2370 destination: path.display().to_string(),
2371 ..Default::default()
2372 };
2373 let logger = std::sync::Arc::new(AuditLogger::from_config(&config, false).await.unwrap());
2374 (logger, path)
2375 }
2376
2377 #[tokio::test]
2378 async fn with_audit_sets_logger() {
2379 let config = ScrapeConfig::default();
2380 let executor = WebScrapeExecutor::new(&config);
2381 assert!(executor.audit_logger.is_none());
2382
2383 let dir = tempfile::tempdir().unwrap();
2384 let (logger, _path) = make_file_audit_logger(&dir).await;
2385 let executor = executor.with_audit(logger);
2386 assert!(executor.audit_logger.is_some());
2387 }
2388
2389 #[test]
2390 fn tool_error_to_audit_result_blocked_maps_correctly() {
2391 let err = ToolError::Blocked {
2392 command: "scheme not allowed: http".into(),
2393 };
2394 let result = tool_error_to_audit_result(&err);
2395 assert!(
2396 matches!(result, AuditResult::Blocked { reason } if reason == "scheme not allowed: http")
2397 );
2398 }
2399
2400 #[test]
2401 fn tool_error_to_audit_result_timeout_maps_correctly() {
2402 let err = ToolError::Timeout { timeout_secs: 15 };
2403 let result = tool_error_to_audit_result(&err);
2404 assert!(matches!(result, AuditResult::Timeout));
2405 }
2406
2407 #[test]
2408 fn tool_error_to_audit_result_execution_error_maps_correctly() {
2409 let err = ToolError::Execution(std::io::Error::other("connection refused"));
2410 let result = tool_error_to_audit_result(&err);
2411 assert!(
2412 matches!(result, AuditResult::Error { message } if message.contains("connection refused"))
2413 );
2414 }
2415
2416 #[tokio::test]
2417 async fn fetch_audit_blocked_url_logged() {
2418 let dir = tempfile::tempdir().unwrap();
2419 let (logger, log_path) = make_file_audit_logger(&dir).await;
2420
2421 let config = ScrapeConfig::default();
2422 let executor = WebScrapeExecutor::new(&config).with_audit(logger);
2423
2424 let call = crate::executor::ToolCall {
2425 tool_id: ToolName::new("fetch"),
2426 params: {
2427 let mut m = serde_json::Map::new();
2428 m.insert("url".to_owned(), serde_json::json!("http://example.com"));
2429 m
2430 },
2431 caller_id: None,
2432 };
2433 let result = executor.execute_tool_call(&call).await;
2434 assert!(matches!(result, Err(ToolError::Blocked { .. })));
2435
2436 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
2437 assert!(
2438 content.contains("\"tool\":\"fetch\""),
2439 "expected tool=fetch in audit: {content}"
2440 );
2441 assert!(
2442 content.contains("\"type\":\"blocked\""),
2443 "expected type=blocked in audit: {content}"
2444 );
2445 assert!(
2446 content.contains("http://example.com"),
2447 "expected URL in audit command field: {content}"
2448 );
2449 }
2450
2451 #[tokio::test]
2452 async fn log_audit_success_writes_to_file() {
2453 let dir = tempfile::tempdir().unwrap();
2454 let (logger, log_path) = make_file_audit_logger(&dir).await;
2455
2456 let config = ScrapeConfig::default();
2457 let executor = WebScrapeExecutor::new(&config).with_audit(logger);
2458
2459 executor
2460 .log_audit(
2461 "fetch",
2462 "https://example.com/page",
2463 AuditResult::Success,
2464 42,
2465 None,
2466 None,
2467 None,
2468 )
2469 .await;
2470
2471 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
2472 assert!(
2473 content.contains("\"tool\":\"fetch\""),
2474 "expected tool=fetch in audit: {content}"
2475 );
2476 assert!(
2477 content.contains("\"type\":\"success\""),
2478 "expected type=success in audit: {content}"
2479 );
2480 assert!(
2481 content.contains("\"command\":\"https://example.com/page\""),
2482 "expected command URL in audit: {content}"
2483 );
2484 assert!(
2485 content.contains("\"duration_ms\":42"),
2486 "expected duration_ms in audit: {content}"
2487 );
2488 }
2489
2490 #[tokio::test]
2491 async fn log_audit_blocked_writes_to_file() {
2492 let dir = tempfile::tempdir().unwrap();
2493 let (logger, log_path) = make_file_audit_logger(&dir).await;
2494
2495 let config = ScrapeConfig::default();
2496 let executor = WebScrapeExecutor::new(&config).with_audit(logger);
2497
2498 executor
2499 .log_audit(
2500 "web_scrape",
2501 "http://evil.com/page",
2502 AuditResult::Blocked {
2503 reason: "scheme not allowed: http".into(),
2504 },
2505 0,
2506 None,
2507 None,
2508 None,
2509 )
2510 .await;
2511
2512 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
2513 assert!(
2514 content.contains("\"tool\":\"web_scrape\""),
2515 "expected tool=web_scrape in audit: {content}"
2516 );
2517 assert!(
2518 content.contains("\"type\":\"blocked\""),
2519 "expected type=blocked in audit: {content}"
2520 );
2521 assert!(
2522 content.contains("scheme not allowed"),
2523 "expected block reason in audit: {content}"
2524 );
2525 }
2526
2527 #[tokio::test]
2528 async fn web_scrape_audit_blocked_url_logged() {
2529 let dir = tempfile::tempdir().unwrap();
2530 let (logger, log_path) = make_file_audit_logger(&dir).await;
2531
2532 let config = ScrapeConfig::default();
2533 let executor = WebScrapeExecutor::new(&config).with_audit(logger);
2534
2535 let call = crate::executor::ToolCall {
2536 tool_id: ToolName::new("web_scrape"),
2537 params: {
2538 let mut m = serde_json::Map::new();
2539 m.insert("url".to_owned(), serde_json::json!("http://example.com"));
2540 m.insert("select".to_owned(), serde_json::json!("h1"));
2541 m
2542 },
2543 caller_id: None,
2544 };
2545 let result = executor.execute_tool_call(&call).await;
2546 assert!(matches!(result, Err(ToolError::Blocked { .. })));
2547
2548 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
2549 assert!(
2550 content.contains("\"tool\":\"web_scrape\""),
2551 "expected tool=web_scrape in audit: {content}"
2552 );
2553 assert!(
2554 content.contains("\"type\":\"blocked\""),
2555 "expected type=blocked in audit: {content}"
2556 );
2557 }
2558
2559 #[tokio::test]
2560 async fn no_audit_logger_does_not_panic_on_blocked_fetch() {
2561 let config = ScrapeConfig::default();
2562 let executor = WebScrapeExecutor::new(&config);
2563 assert!(executor.audit_logger.is_none());
2564
2565 let call = crate::executor::ToolCall {
2566 tool_id: ToolName::new("fetch"),
2567 params: {
2568 let mut m = serde_json::Map::new();
2569 m.insert("url".to_owned(), serde_json::json!("http://example.com"));
2570 m
2571 },
2572 caller_id: None,
2573 };
2574 let result = executor.execute_tool_call(&call).await;
2576 assert!(matches!(result, Err(ToolError::Blocked { .. })));
2577 }
2578
2579 #[tokio::test]
2581 async fn fetch_execute_tool_call_end_to_end() {
2582 use wiremock::matchers::{method, path};
2583 use wiremock::{Mock, ResponseTemplate};
2584
2585 let (executor, server) = mock_server_executor().await;
2586 Mock::given(method("GET"))
2587 .and(path("/e2e"))
2588 .respond_with(ResponseTemplate::new(200).set_body_string("<h1>end-to-end</h1>"))
2589 .mount(&server)
2590 .await;
2591
2592 let (host, addrs) = server_host_and_addr(&server);
2593 let result = executor
2595 .fetch_html(
2596 &format!("{}/e2e", server.uri()),
2597 &host,
2598 &addrs,
2599 "fetch",
2600 "test-cid",
2601 None,
2602 )
2603 .await;
2604 assert!(result.is_ok());
2605 assert!(result.unwrap().contains("end-to-end"));
2606 }
2607
2608 #[test]
2611 fn domain_matches_exact() {
2612 assert!(domain_matches("example.com", "example.com"));
2613 assert!(!domain_matches("example.com", "other.com"));
2614 assert!(!domain_matches("example.com", "sub.example.com"));
2615 }
2616
2617 #[test]
2618 fn domain_matches_wildcard_single_subdomain() {
2619 assert!(domain_matches("*.example.com", "sub.example.com"));
2620 assert!(!domain_matches("*.example.com", "example.com"));
2621 assert!(!domain_matches("*.example.com", "sub.sub.example.com"));
2622 }
2623
2624 #[test]
2625 fn domain_matches_wildcard_does_not_match_empty_label() {
2626 assert!(!domain_matches("*.example.com", ".example.com"));
2628 }
2629
2630 #[test]
2631 fn domain_matches_multi_wildcard_treated_as_exact() {
2632 assert!(!domain_matches("*.*.example.com", "a.b.example.com"));
2634 }
2635
2636 #[test]
2639 fn check_domain_policy_empty_lists_allow_all() {
2640 assert!(check_domain_policy("example.com", &[], &[]).is_ok());
2641 assert!(check_domain_policy("evil.com", &[], &[]).is_ok());
2642 }
2643
2644 #[test]
2645 fn check_domain_policy_denylist_blocks() {
2646 let denied = vec!["evil.com".to_string()];
2647 let err = check_domain_policy("evil.com", &[], &denied).unwrap_err();
2648 assert!(matches!(err, ToolError::Blocked { .. }));
2649 }
2650
2651 #[test]
2652 fn check_domain_policy_denylist_does_not_block_other_domains() {
2653 let denied = vec!["evil.com".to_string()];
2654 assert!(check_domain_policy("good.com", &[], &denied).is_ok());
2655 }
2656
2657 #[test]
2658 fn check_domain_policy_allowlist_permits_matching() {
2659 let allowed = vec!["docs.rs".to_string(), "*.rust-lang.org".to_string()];
2660 assert!(check_domain_policy("docs.rs", &allowed, &[]).is_ok());
2661 assert!(check_domain_policy("blog.rust-lang.org", &allowed, &[]).is_ok());
2662 }
2663
2664 #[test]
2665 fn check_domain_policy_allowlist_blocks_unknown() {
2666 let allowed = vec!["docs.rs".to_string()];
2667 let err = check_domain_policy("other.com", &allowed, &[]).unwrap_err();
2668 assert!(matches!(err, ToolError::Blocked { .. }));
2669 }
2670
2671 #[test]
2672 fn check_domain_policy_deny_overrides_allow() {
2673 let allowed = vec!["example.com".to_string()];
2674 let denied = vec!["example.com".to_string()];
2675 let err = check_domain_policy("example.com", &allowed, &denied).unwrap_err();
2676 assert!(matches!(err, ToolError::Blocked { .. }));
2677 }
2678
2679 #[test]
2680 fn check_domain_policy_wildcard_in_denylist() {
2681 let denied = vec!["*.evil.com".to_string()];
2682 let err = check_domain_policy("sub.evil.com", &[], &denied).unwrap_err();
2683 assert!(matches!(err, ToolError::Blocked { .. }));
2684 assert!(check_domain_policy("evil.com", &[], &denied).is_ok());
2686 }
2687}