1use crate::security::SecurityPolicy;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8use std::time::Duration;
9
10pub struct HttpRequestTool {
13 security: Arc<SecurityPolicy>,
14 allowed_domains: Vec<String>,
15 max_response_size: usize,
16 timeout_secs: u64,
17}
18
19impl HttpRequestTool {
20 pub fn new(
21 security: Arc<SecurityPolicy>,
22 allowed_domains: Vec<String>,
23 max_response_size: usize,
24 timeout_secs: u64,
25 ) -> Self {
26 Self {
27 security,
28 allowed_domains: normalize_allowed_domains(allowed_domains),
29 max_response_size,
30 timeout_secs,
31 }
32 }
33
34 fn validate_url(&self, raw_url: &str) -> anyhow::Result<String> {
35 let url = raw_url.trim();
36
37 if url.is_empty() {
38 anyhow::bail!("URL cannot be empty");
39 }
40
41 if url.chars().any(char::is_whitespace) {
42 anyhow::bail!("URL cannot contain whitespace");
43 }
44
45 if !url.starts_with("http://") && !url.starts_with("https://") {
46 anyhow::bail!("Only http:// and https:// URLs are allowed");
47 }
48
49 if self.allowed_domains.is_empty() {
50 anyhow::bail!(
51 "HTTP request tool is enabled but no allowed_domains are configured. Add [http_request].allowed_domains in config.toml"
52 );
53 }
54
55 let host = extract_host(url)?;
56
57 if is_private_or_local_host(&host) {
58 anyhow::bail!("Blocked local/private host: {host}");
59 }
60
61 if !host_matches_allowlist(&host, &self.allowed_domains) {
62 anyhow::bail!("Host '{host}' is not in http_request.allowed_domains");
63 }
64
65 Ok(url.to_string())
66 }
67
68 fn validate_method(&self, method: &str) -> anyhow::Result<reqwest::Method> {
69 match method.to_uppercase().as_str() {
70 "GET" => Ok(reqwest::Method::GET),
71 "POST" => Ok(reqwest::Method::POST),
72 "PUT" => Ok(reqwest::Method::PUT),
73 "DELETE" => Ok(reqwest::Method::DELETE),
74 "PATCH" => Ok(reqwest::Method::PATCH),
75 "HEAD" => Ok(reqwest::Method::HEAD),
76 "OPTIONS" => Ok(reqwest::Method::OPTIONS),
77 _ => anyhow::bail!(
78 "Unsupported HTTP method: {method}. Supported: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS"
79 ),
80 }
81 }
82
83 fn parse_headers(&self, headers: &serde_json::Value) -> Vec<(String, String)> {
84 let mut result = Vec::new();
85 if let Some(obj) = headers.as_object() {
86 for (key, value) in obj {
87 if let Some(str_val) = value.as_str() {
88 result.push((key.clone(), str_val.to_string()));
89 }
90 }
91 }
92 result
93 }
94
95 #[cfg(test)]
96 fn redact_headers_for_display(headers: &[(String, String)]) -> Vec<(String, String)> {
97 headers
98 .iter()
99 .map(|(key, value)| {
100 let lower = key.to_lowercase();
101 let is_sensitive = lower.contains("authorization")
102 || lower.contains("api-key")
103 || lower.contains("apikey")
104 || lower.contains("token")
105 || lower.contains("secret");
106 if is_sensitive {
107 (key.clone(), "***REDACTED***".into())
108 } else {
109 (key.clone(), value.clone())
110 }
111 })
112 .collect()
113 }
114
115 async fn execute_request(
116 &self,
117 url: &str,
118 method: reqwest::Method,
119 headers: Vec<(String, String)>,
120 body: Option<&str>,
121 ) -> anyhow::Result<reqwest::Response> {
122 let client = reqwest::Client::builder()
123 .timeout(Duration::from_secs(self.timeout_secs))
124 .build()?;
125
126 let mut request = client.request(method, url);
127
128 for (key, value) in headers {
129 request = request.header(&key, &value);
130 }
131
132 if let Some(body_str) = body {
133 request = request.body(body_str.to_string());
134 }
135
136 Ok(request.send().await?)
137 }
138
139 fn truncate_response(&self, text: &str) -> String {
140 if text.len() > self.max_response_size {
141 let mut truncated = text
142 .chars()
143 .take(self.max_response_size)
144 .collect::<String>();
145 truncated.push_str("\n\n... [Response truncated due to size limit] ...");
146 truncated
147 } else {
148 text.to_string()
149 }
150 }
151}
152
153#[async_trait]
154impl Tool for HttpRequestTool {
155 fn category(&self) -> ToolCategory {
156 ToolCategory::Write
157 }
158
159 fn name(&self) -> &str {
160 "http_request"
161 }
162
163 fn description(&self) -> &str {
164 "Make HTTP requests to external APIs. Supports GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS methods. \
165 Security constraints: allowlist-only domains, no local/private hosts, configurable timeout and response size limits."
166 }
167
168 fn parameters_schema(&self) -> serde_json::Value {
169 json!({
170 "type": "object",
171 "properties": {
172 "url": {
173 "type": "string",
174 "description": "HTTP or HTTPS URL to request"
175 },
176 "method": {
177 "type": "string",
178 "description": "HTTP method (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)",
179 "default": "GET"
180 },
181 "headers": {
182 "type": "object",
183 "description": "Optional HTTP headers as key-value pairs (e.g., {\"Authorization\": \"Bearer token\", \"Content-Type\": \"application/json\"})",
184 "default": {}
185 },
186 "body": {
187 "type": "string",
188 "description": "Optional request body (for POST, PUT, PATCH requests)"
189 }
190 },
191 "required": ["url"]
192 })
193 }
194
195 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
196 let url = args
197 .get("url")
198 .and_then(|v| v.as_str())
199 .ok_or_else(|| anyhow::anyhow!("Missing 'url' parameter"))?;
200
201 let method_str = args.get("method").and_then(|v| v.as_str()).unwrap_or("GET");
202 let headers_val = args.get("headers").cloned().unwrap_or(json!({}));
203 let body = args.get("body").and_then(|v| v.as_str());
204
205 if !self.security.can_act() {
206 return Ok(ToolResult {
207 success: false,
208 output: String::new(),
209 error: Some("Action blocked: autonomy is read-only".into()),
210 });
211 }
212
213 if !self.security.record_action() {
214 return Ok(ToolResult {
215 success: false,
216 output: String::new(),
217 error: Some("Action blocked: rate limit exceeded".into()),
218 });
219 }
220
221 let url = match self.validate_url(url) {
222 Ok(v) => v,
223 Err(e) => {
224 return Ok(ToolResult {
225 success: false,
226 output: String::new(),
227 error: Some(e.to_string()),
228 });
229 }
230 };
231
232 let method = match self.validate_method(method_str) {
233 Ok(m) => m,
234 Err(e) => {
235 return Ok(ToolResult {
236 success: false,
237 output: String::new(),
238 error: Some(e.to_string()),
239 });
240 }
241 };
242
243 let request_headers = self.parse_headers(&headers_val);
244
245 match self
246 .execute_request(&url, method, request_headers, body)
247 .await
248 {
249 Ok(response) => {
250 let status = response.status();
251 let status_code = status.as_u16();
252
253 let response_headers = response.headers().iter();
255 let headers_text = response_headers
256 .map(|(k, _)| {
257 let is_sensitive = k.as_str().to_lowercase().contains("set-cookie");
258 if is_sensitive {
259 format!("{}: ***REDACTED***", k.as_str())
260 } else {
261 format!("{}: {:?}", k.as_str(), k.as_str())
262 }
263 })
264 .collect::<Vec<_>>()
265 .join(", ");
266
267 let response_text = match response.text().await {
269 Ok(text) => self.truncate_response(&text),
270 Err(e) => format!("[Failed to read response body: {e}]"),
271 };
272
273 let output = format!(
274 "Status: {} {}\nResponse Headers: {}\n\nResponse Body:\n{}",
275 status_code,
276 status.canonical_reason().unwrap_or("Unknown"),
277 headers_text,
278 response_text
279 );
280
281 Ok(ToolResult {
282 success: status.is_success(),
283 output,
284 error: if status.is_client_error() || status.is_server_error() {
285 Some(format!("HTTP {}", status_code))
286 } else {
287 None
288 },
289 })
290 }
291 Err(e) => Ok(ToolResult {
292 success: false,
293 output: String::new(),
294 error: Some(format!("HTTP request failed: {e}")),
295 }),
296 }
297 }
298}
299
300fn normalize_allowed_domains(domains: Vec<String>) -> Vec<String> {
303 let mut normalized = domains
304 .into_iter()
305 .filter_map(|d| normalize_domain(&d))
306 .collect::<Vec<_>>();
307 normalized.sort_unstable();
308 normalized.dedup();
309 normalized
310}
311
312fn normalize_domain(raw: &str) -> Option<String> {
313 let mut d = raw.trim().to_lowercase();
314 if d.is_empty() {
315 return None;
316 }
317
318 if let Some(stripped) = d.strip_prefix("https://") {
319 d = stripped.to_string();
320 } else if let Some(stripped) = d.strip_prefix("http://") {
321 d = stripped.to_string();
322 }
323
324 if let Some((host, _)) = d.split_once('/') {
325 d = host.to_string();
326 }
327
328 d = d.trim_start_matches('.').trim_end_matches('.').to_string();
329
330 if let Some((host, _)) = d.split_once(':') {
331 d = host.to_string();
332 }
333
334 if d.is_empty() || d.chars().any(char::is_whitespace) {
335 return None;
336 }
337
338 Some(d)
339}
340
341fn extract_host(url: &str) -> anyhow::Result<String> {
342 let rest = url
343 .strip_prefix("http://")
344 .or_else(|| url.strip_prefix("https://"))
345 .ok_or_else(|| anyhow::anyhow!("Only http:// and https:// URLs are allowed"))?;
346
347 let authority = rest
348 .split(['/', '?', '#'])
349 .next()
350 .ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
351
352 if authority.is_empty() {
353 anyhow::bail!("URL must include a host");
354 }
355
356 if authority.contains('@') {
357 anyhow::bail!("URL userinfo is not allowed");
358 }
359
360 if authority.starts_with('[') {
361 anyhow::bail!("IPv6 hosts are not supported in http_request");
362 }
363
364 let host = authority
365 .split(':')
366 .next()
367 .unwrap_or_default()
368 .trim()
369 .trim_end_matches('.')
370 .to_lowercase();
371
372 if host.is_empty() {
373 anyhow::bail!("URL must include a valid host");
374 }
375
376 Ok(host)
377}
378
379fn host_matches_allowlist(host: &str, allowed_domains: &[String]) -> bool {
380 allowed_domains.iter().any(|domain| {
381 host == domain
382 || host
383 .strip_suffix(domain)
384 .is_some_and(|prefix| prefix.ends_with('.'))
385 })
386}
387
388fn is_private_or_local_host(host: &str) -> bool {
389 let bare = host
391 .strip_prefix('[')
392 .and_then(|h| h.strip_suffix(']'))
393 .unwrap_or(host);
394
395 let has_local_tld = bare
396 .rsplit('.')
397 .next()
398 .is_some_and(|label| label == "local");
399
400 if bare == "localhost" || bare.ends_with(".localhost") || has_local_tld {
401 return true;
402 }
403
404 if let Ok(ip) = bare.parse::<std::net::IpAddr>() {
405 return match ip {
406 std::net::IpAddr::V4(v4) => is_non_global_v4(v4),
407 std::net::IpAddr::V6(v6) => is_non_global_v6(v6),
408 };
409 }
410
411 false
412}
413
414fn is_non_global_v4(v4: std::net::Ipv4Addr) -> bool {
416 let [a, b, c, _] = v4.octets();
417 v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified() || v4.is_broadcast() || v4.is_multicast() || (a == 100 && (64..=127).contains(&b)) || a >= 240 || (a == 192 && b == 0 && (c == 0 || c == 2)) || (a == 198 && b == 51) || (a == 203 && b == 0) || (a == 198 && (18..=19).contains(&b)) }
430
431fn is_non_global_v6(v6: std::net::Ipv6Addr) -> bool {
433 let segs = v6.segments();
434 v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() || (segs[0] & 0xfe00) == 0xfc00 || (segs[0] & 0xffc0) == 0xfe80 || (segs[0] == 0x2001 && segs[1] == 0x0db8) || v6.to_ipv4_mapped().is_some_and(is_non_global_v4)
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use crate::security::{AutonomyLevel, SecurityPolicy};
447
448 fn test_tool(allowed_domains: Vec<&str>) -> HttpRequestTool {
449 let security = Arc::new(SecurityPolicy {
450 autonomy: AutonomyLevel::Supervised,
451 ..SecurityPolicy::default()
452 });
453 HttpRequestTool::new(
454 security,
455 allowed_domains.into_iter().map(String::from).collect(),
456 1_000_000,
457 30,
458 )
459 }
460
461 #[test]
462 fn normalize_domain_strips_scheme_path_and_case() {
463 let got = normalize_domain(" HTTPS://Docs.Example.com/path ").unwrap();
464 assert_eq!(got, "docs.example.com");
465 }
466
467 #[test]
468 fn normalize_allowed_domains_deduplicates() {
469 let got = normalize_allowed_domains(vec![
470 "example.com".into(),
471 "EXAMPLE.COM".into(),
472 "https://example.com/".into(),
473 ]);
474 assert_eq!(got, vec!["example.com".to_string()]);
475 }
476
477 #[test]
478 fn validate_accepts_exact_domain() {
479 let tool = test_tool(vec!["example.com"]);
480 let got = tool.validate_url("https://example.com/docs").unwrap();
481 assert_eq!(got, "https://example.com/docs");
482 }
483
484 #[test]
485 fn validate_accepts_http() {
486 let tool = test_tool(vec!["example.com"]);
487 assert!(tool.validate_url("http://example.com").is_ok());
488 }
489
490 #[test]
491 fn validate_accepts_subdomain() {
492 let tool = test_tool(vec!["example.com"]);
493 assert!(tool.validate_url("https://api.example.com/v1").is_ok());
494 }
495
496 #[test]
497 fn validate_rejects_allowlist_miss() {
498 let tool = test_tool(vec!["example.com"]);
499 let err = tool
500 .validate_url("https://google.com")
501 .unwrap_err()
502 .to_string();
503 assert!(err.contains("allowed_domains"));
504 }
505
506 #[test]
507 fn validate_rejects_localhost() {
508 let tool = test_tool(vec!["localhost"]);
509 let err = tool
510 .validate_url("https://localhost:8080")
511 .unwrap_err()
512 .to_string();
513 assert!(err.contains("local/private"));
514 }
515
516 #[test]
517 fn validate_rejects_private_ipv4() {
518 let tool = test_tool(vec!["192.168.1.5"]);
519 let err = tool
520 .validate_url("https://192.168.1.5")
521 .unwrap_err()
522 .to_string();
523 assert!(err.contains("local/private"));
524 }
525
526 #[test]
527 fn validate_rejects_whitespace() {
528 let tool = test_tool(vec!["example.com"]);
529 let err = tool
530 .validate_url("https://example.com/hello world")
531 .unwrap_err()
532 .to_string();
533 assert!(err.contains("whitespace"));
534 }
535
536 #[test]
537 fn validate_rejects_userinfo() {
538 let tool = test_tool(vec!["example.com"]);
539 let err = tool
540 .validate_url("https://user@example.com")
541 .unwrap_err()
542 .to_string();
543 assert!(err.contains("userinfo"));
544 }
545
546 #[test]
547 fn validate_requires_allowlist() {
548 let security = Arc::new(SecurityPolicy::default());
549 let tool = HttpRequestTool::new(security, vec![], 1_000_000, 30);
550 let err = tool
551 .validate_url("https://example.com")
552 .unwrap_err()
553 .to_string();
554 assert!(err.contains("allowed_domains"));
555 }
556
557 #[test]
558 fn validate_accepts_valid_methods() {
559 let tool = test_tool(vec!["example.com"]);
560 assert!(tool.validate_method("GET").is_ok());
561 assert!(tool.validate_method("POST").is_ok());
562 assert!(tool.validate_method("PUT").is_ok());
563 assert!(tool.validate_method("DELETE").is_ok());
564 assert!(tool.validate_method("PATCH").is_ok());
565 assert!(tool.validate_method("HEAD").is_ok());
566 assert!(tool.validate_method("OPTIONS").is_ok());
567 }
568
569 #[test]
570 fn validate_rejects_invalid_method() {
571 let tool = test_tool(vec!["example.com"]);
572 let err = tool.validate_method("INVALID").unwrap_err().to_string();
573 assert!(err.contains("Unsupported HTTP method"));
574 }
575
576 #[test]
577 fn blocks_multicast_ipv4() {
578 assert!(is_private_or_local_host("224.0.0.1"));
579 assert!(is_private_or_local_host("239.255.255.255"));
580 }
581
582 #[test]
583 fn blocks_broadcast() {
584 assert!(is_private_or_local_host("255.255.255.255"));
585 }
586
587 #[test]
588 fn blocks_reserved_ipv4() {
589 assert!(is_private_or_local_host("240.0.0.1"));
590 assert!(is_private_or_local_host("250.1.2.3"));
591 }
592
593 #[test]
594 fn blocks_documentation_ranges() {
595 assert!(is_private_or_local_host("192.0.2.1")); assert!(is_private_or_local_host("198.51.100.1")); assert!(is_private_or_local_host("203.0.113.1")); }
599
600 #[test]
601 fn blocks_benchmarking_range() {
602 assert!(is_private_or_local_host("198.18.0.1"));
603 assert!(is_private_or_local_host("198.19.255.255"));
604 }
605
606 #[test]
607 fn blocks_ipv6_localhost() {
608 assert!(is_private_or_local_host("::1"));
609 assert!(is_private_or_local_host("[::1]"));
610 }
611
612 #[test]
613 fn blocks_ipv6_multicast() {
614 assert!(is_private_or_local_host("ff02::1"));
615 }
616
617 #[test]
618 fn blocks_ipv6_link_local() {
619 assert!(is_private_or_local_host("fe80::1"));
620 }
621
622 #[test]
623 fn blocks_ipv6_unique_local() {
624 assert!(is_private_or_local_host("fd00::1"));
625 }
626
627 #[test]
628 fn blocks_ipv4_mapped_ipv6() {
629 assert!(is_private_or_local_host("::ffff:127.0.0.1"));
630 assert!(is_private_or_local_host("::ffff:192.168.1.1"));
631 assert!(is_private_or_local_host("::ffff:10.0.0.1"));
632 }
633
634 #[test]
635 fn allows_public_ipv4() {
636 assert!(!is_private_or_local_host("8.8.8.8"));
637 assert!(!is_private_or_local_host("1.1.1.1"));
638 assert!(!is_private_or_local_host("93.184.216.34"));
639 }
640
641 #[test]
642 fn blocks_ipv6_documentation_range() {
643 assert!(is_private_or_local_host("2001:db8::1"));
644 }
645
646 #[test]
647 fn allows_public_ipv6() {
648 assert!(!is_private_or_local_host("2607:f8b0:4004:800::200e"));
649 }
650
651 #[test]
652 fn blocks_shared_address_space() {
653 assert!(is_private_or_local_host("100.64.0.1"));
654 assert!(is_private_or_local_host("100.127.255.255"));
655 assert!(!is_private_or_local_host("100.63.0.1")); assert!(!is_private_or_local_host("100.128.0.1")); }
658
659 #[tokio::test]
660 async fn execute_blocks_readonly_mode() {
661 let security = Arc::new(SecurityPolicy {
662 autonomy: AutonomyLevel::ReadOnly,
663 ..SecurityPolicy::default()
664 });
665 let tool = HttpRequestTool::new(security, vec!["example.com".into()], 1_000_000, 30);
666 let result = tool
667 .execute(json!({"url": "https://example.com"}))
668 .await
669 .unwrap();
670 assert!(!result.success);
671 assert!(result.error.unwrap().contains("read-only"));
672 }
673
674 #[tokio::test]
675 async fn execute_blocks_when_rate_limited() {
676 let security = Arc::new(SecurityPolicy {
677 max_actions_per_hour: 0,
678 ..SecurityPolicy::default()
679 });
680 let tool = HttpRequestTool::new(security, vec!["example.com".into()], 1_000_000, 30);
681 let result = tool
682 .execute(json!({"url": "https://example.com"}))
683 .await
684 .unwrap();
685 assert!(!result.success);
686 assert!(result.error.unwrap().contains("rate limit"));
687 }
688
689 #[test]
690 fn truncate_response_within_limit() {
691 let tool = test_tool(vec!["example.com"]);
692 let text = "hello world";
693 assert_eq!(tool.truncate_response(text), "hello world");
694 }
695
696 #[test]
697 fn truncate_response_over_limit() {
698 let tool = HttpRequestTool::new(
699 Arc::new(SecurityPolicy::default()),
700 vec!["example.com".into()],
701 10,
702 30,
703 );
704 let text = "hello world this is long";
705 let truncated = tool.truncate_response(text);
706 assert!(truncated.len() <= 10 + 60); assert!(truncated.contains("[Response truncated"));
708 }
709
710 #[test]
711 fn parse_headers_preserves_original_values() {
712 let tool = test_tool(vec!["example.com"]);
713 let headers = json!({
714 "Authorization": "Bearer secret",
715 "Content-Type": "application/json",
716 "X-API-Key": "my-key"
717 });
718 let parsed = tool.parse_headers(&headers);
719 assert_eq!(parsed.len(), 3);
720 assert!(
721 parsed
722 .iter()
723 .any(|(k, v)| k == "Authorization" && v == "Bearer secret")
724 );
725 assert!(
726 parsed
727 .iter()
728 .any(|(k, v)| k == "X-API-Key" && v == "my-key")
729 );
730 assert!(
731 parsed
732 .iter()
733 .any(|(k, v)| k == "Content-Type" && v == "application/json")
734 );
735 }
736
737 #[test]
738 fn redact_headers_for_display_redacts_sensitive() {
739 let headers = vec![
740 ("Authorization".into(), "Bearer secret".into()),
741 ("Content-Type".into(), "application/json".into()),
742 ("X-API-Key".into(), "my-key".into()),
743 ("X-Secret-Token".into(), "tok-123".into()),
744 ];
745 let redacted = HttpRequestTool::redact_headers_for_display(&headers);
746 assert_eq!(redacted.len(), 4);
747 assert!(
748 redacted
749 .iter()
750 .any(|(k, v)| k == "Authorization" && v == "***REDACTED***")
751 );
752 assert!(
753 redacted
754 .iter()
755 .any(|(k, v)| k == "X-API-Key" && v == "***REDACTED***")
756 );
757 assert!(
758 redacted
759 .iter()
760 .any(|(k, v)| k == "X-Secret-Token" && v == "***REDACTED***")
761 );
762 assert!(
763 redacted
764 .iter()
765 .any(|(k, v)| k == "Content-Type" && v == "application/json")
766 );
767 }
768
769 #[test]
770 fn redact_headers_does_not_alter_original() {
771 let headers = vec![("Authorization".into(), "Bearer real-token".into())];
772 let _ = HttpRequestTool::redact_headers_for_display(&headers);
773 assert_eq!(headers[0].1, "Bearer real-token");
774 }
775}