Skip to main content

lc_tools/extended/
http.rs

1//! HTTP tool with SSRF protection
2
3use std::time::Duration;
4
5use async_trait::async_trait;
6use serde_json::Value;
7
8use crate::ssrf::{guarded_get, guarded_post_json};
9use lc_core::tools::ToolError;
10use lc_core::BaseTool;
11
12/// HTTP request tool (GET/POST) with SSRF protection.
13pub struct HTTPTool {
14    /// Per-request timeout handed to the per-request pinned client.
15    timeout: Duration,
16    allow_private_ips: bool,
17}
18
19impl HTTPTool {
20    /// Creates an HTTP tool with a 30s timeout and SSRF protection enabled.
21    pub fn new() -> Self {
22        Self {
23            timeout: Duration::from_secs(30),
24            allow_private_ips: false,
25        }
26    }
27
28    /// Creates an HTTP tool with a custom timeout (SSRF protection enabled).
29    pub fn with_timeout(timeout: Duration) -> Self {
30        Self {
31            timeout,
32            allow_private_ips: false,
33        }
34    }
35
36    /// Allow requests to private/internal IP addresses (SSRF opt-in).
37    pub fn with_allow_private_ips(mut self, allow: bool) -> Self {
38        self.allow_private_ips = allow;
39        self
40    }
41
42    /// Sends a GET request, following redirects with SSRF checks per hop.
43    pub async fn get(&self, url: &str) -> Result<String, ToolError> {
44        // SSRF: guarded_get resolves once, validates every answer, pins the validated
45        // IPs, then follows redirects manually with the same treatment per hop.
46        guarded_get(url, !self.allow_private_ips, Some(self.timeout))
47            .await?
48            .text()
49            .await
50            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))
51    }
52
53    /// Sends a POST request with a JSON body (single hop, IP-pinned SSRF guard).
54    pub async fn post(&self, url: &str, body: Value) -> Result<String, ToolError> {
55        // POST never follows redirects (the 3xx response is returned as-is); resolve-once
56        // plus IP pinning still closes the DNS-rebinding window on this single hop.
57        guarded_post_json(url, &body, !self.allow_private_ips, Some(self.timeout))
58            .await?
59            .text()
60            .await
61            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))
62    }
63}
64
65impl Default for HTTPTool {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71#[async_trait]
72impl BaseTool for HTTPTool {
73    fn name(&self) -> &str {
74        "http_request"
75    }
76
77    fn description(&self) -> &str {
78        "Make HTTP requests. Input JSON: {\"url\": \"...\", \"method\": \"get|post\", \"body\": {...}}. \
79         SSRF protection enabled by default (blocks private IPs)."
80    }
81
82    async fn run(&self, input: String) -> Result<String, ToolError> {
83        let v: Value =
84            serde_json::from_str(&input).map_err(|e| ToolError::InvalidInput(e.to_string()))?;
85        let url = v
86            .get("url")
87            .and_then(|x| x.as_str())
88            .ok_or_else(|| ToolError::InvalidInput("Missing 'url' field".to_string()))?;
89        let method = v.get("method").and_then(|x| x.as_str()).unwrap_or("get");
90        match method {
91            "get" => self.get(url).await,
92            "post" => {
93                self.post(url, v.get("body").cloned().unwrap_or(Value::Null))
94                    .await
95            }
96            other => Err(ToolError::InvalidInput(format!(
97                "Unknown method: {}. Supported: get, post",
98                other
99            ))),
100        }
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::ssrf::is_private_ip;
108    use std::net::IpAddr;
109
110    #[test]
111    fn test_name_description() {
112        let t = HTTPTool::new();
113        assert_eq!(t.name(), "http_request");
114        assert!(t.description().contains("HTTP"));
115    }
116
117    #[test]
118    fn test_private_ip_detection() {
119        assert!(is_private_ip(&IpAddr::from([127, 0, 0, 1])));
120        assert!(is_private_ip(&IpAddr::from([10, 0, 0, 1])));
121        assert!(is_private_ip(&IpAddr::from([172, 16, 0, 1])));
122        assert!(is_private_ip(&IpAddr::from([172, 31, 255, 255])));
123        assert!(is_private_ip(&IpAddr::from([192, 168, 1, 1])));
124        assert!(is_private_ip(&IpAddr::from([169, 254, 169, 254])));
125        assert!(is_private_ip(&IpAddr::from([0, 0, 0, 0])));
126
127        assert!(!is_private_ip(&IpAddr::from([8, 8, 8, 8])));
128        assert!(!is_private_ip(&IpAddr::from([1, 1, 1, 1])));
129        assert!(!is_private_ip(&IpAddr::from([172, 15, 0, 1])));
130        assert!(!is_private_ip(&IpAddr::from([172, 32, 0, 1])));
131    }
132
133    #[tokio::test]
134    async fn test_ssrf_blocks_localhost() {
135        // Rejection happens after resolve but before connect, so no listener is
136        // contacted — works offline even though Windows answers every loopback port.
137        let tool = HTTPTool::new();
138        let result = tool.get("http://127.0.0.1:6379/").await;
139        assert!(result.is_err());
140        assert!(result.unwrap_err().to_string().contains("SSRF"));
141    }
142
143    #[tokio::test]
144    async fn test_ssrf_blocks_cloud_metadata() {
145        let tool = HTTPTool::new();
146        let result = tool.get("http://169.254.169.254/latest/meta-data/").await;
147        assert!(result.is_err());
148        assert!(result.unwrap_err().to_string().contains("SSRF"));
149    }
150
151    #[test]
152    fn test_with_timeout_is_recorded() {
153        // The opt-in flag and custom timeout are plumbed into guarded_get as
154        // (!allow, Some(timeout)); assert the configuration side directly.
155        let tool = HTTPTool::with_timeout(Duration::from_secs(7)).with_allow_private_ips(true);
156        assert_eq!(tool.timeout, Duration::from_secs(7));
157        assert!(tool.allow_private_ips);
158    }
159
160    #[tokio::test]
161    async fn test_run_invalid_json() {
162        let t = HTTPTool::new();
163        assert!(t.run("not json".to_string()).await.is_err());
164    }
165
166    #[tokio::test]
167    async fn test_run_missing_url() {
168        let t = HTTPTool::new();
169        assert!(t.run(r#"{"method":"get"}"#.to_string()).await.is_err());
170    }
171
172    #[tokio::test]
173    async fn test_run_unknown_method() {
174        let t = HTTPTool::new();
175        let r = t
176            .run(r#"{"url":"http://x","method":"put"}"#.to_string())
177            .await;
178        assert!(r.is_err());
179    }
180}