返回 CodeWhale
guard.rs
根目录 / crates / engine / src / tools / web / guard.rs
1 //! Shared SSRF guard for LLM-initiated HTTP fetches (`fetch_url`, `web.run`).
2 //!
3 //! Validates scheme/host, enforces network policy, resolves DNS and rejects
4 //! private/loopback/link-local/metadata addresses, and returns an optional
5 //! DNS pin so callers can bind the HTTP client to the validated address
6 //! (preventing TOCTOU rebinding). Callers that follow redirects must
7 //! re-invoke [`validate_fetch_target`] on every new Location.
8
9 use crate::tools::spec::{ToolContext, ToolError};
10 use codewhale_net::guard::{DnsPin, PrivateTargets, fetch_target_host, validate_fetch_destination};
11 use codewhale_net::network_policy::Decision;
12
13 /// Validate that `url` is a safe fetch target under SSRF and network policy.
14 ///
15 /// On success returns an optional DNS pin `(hostname, ip)` for hostnames that
16 /// were resolved; literal public IPs return `None` (no pin needed).
17 ///
18 /// `tool` is the policy/audit label (e.g. `"fetch_url"`, `"web_run"`).
19 pub async fn validate_fetch_target(
20 url: &reqwest::Url,
21 context: &ToolContext,
22 tool: &str,
23 private: PrivateTargets,
24 ) -> Result<DnsPin, ToolError> {
25 let host = fetch_target_host(url)?;
26 validate_network_policy(&host, context, tool)?;
27 validate_fetch_destination(host, context.network_policy.as_ref(), tool, true, private).await
28 }
29
30 pub fn validate_network_policy(
31 host: &str,
32 context: &ToolContext,
33 tool: &str,
34 ) -> Result<(), ToolError> {
35 let Some(decider) = context.network_policy.as_ref() else {
36 return Ok(());
37 };
38
39 match decider.evaluate(host, tool) {
40 Decision::Allow => Ok(()),
41 Decision::Deny => Err(ToolError::permission_denied(format!(
42 "network call to '{host}' blocked by network policy"
43 ))),
44 Decision::Prompt => Err(ToolError::permission_denied(format!(
45 "network call to '{host}' requires approval; \
46 re-run after `/network allow {host}` or set network.default = \"allow\" in config"
47 ))),
48 }
49 }
50
51 #[cfg(test)]
52 mod tests {
53 use super::*;
54 use codewhale_net::guard::DNS_PREFLIGHT_TIMEOUT;
55 use std::path::PathBuf;
56
57 fn ctx() -> ToolContext {
58 ToolContext::new(PathBuf::from("."))
59 }
60
61 #[tokio::test]
62 async fn redirected_localhost_hostname_is_rejected() {
63 let url = reqwest::Url::parse("http://localhost:8080/admin").unwrap();
64 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
65 .await
66 .unwrap_err();
67 assert!(format!("{err}").contains("localhost"));
68 }
69
70 #[tokio::test]
71 async fn redirected_private_ip_literal_is_rejected() {
72 let url = reqwest::Url::parse("http://169.254.169.254/latest/meta-data").unwrap();
73 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
74 .await
75 .unwrap_err();
76 assert!(format!("{err}").contains("restricted address"));
77 }
78
79 // GHSA-88gh-2526-gfrr — regression coverage for bracketed IPv6 literals.
80 #[tokio::test]
81 async fn rejects_ipv6_literal_loopback() {
82 let url = reqwest::Url::parse("http://[::1]/").unwrap();
83 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
84 .await
85 .expect_err("[::1] must be rejected as restricted");
86 assert!(format!("{err}").contains("restricted"));
87 }
88
89 #[tokio::test]
90 async fn rejects_ipv6_literal_ula() {
91 let url = reqwest::Url::parse("http://[fc00::1]/").unwrap();
92 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
93 .await
94 .expect_err("[fc00::1] must be rejected as restricted");
95 assert!(format!("{err}").contains("restricted"));
96 }
97
98 #[tokio::test]
99 async fn rejects_ipv6_literal_link_local() {
100 let url = reqwest::Url::parse("http://[fe80::1]/").unwrap();
101 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
102 .await
103 .expect_err("[fe80::1] must be rejected as restricted");
104 assert!(format!("{err}").contains("restricted"));
105 }
106
107 #[tokio::test]
108 async fn rejects_ipv6_literal_ipv4_mapped_loopback() {
109 let url = reqwest::Url::parse("http://[::ffff:127.0.0.1]/").unwrap();
110 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
111 .await
112 .expect_err("[::ffff:127.0.0.1] must be rejected as restricted");
113 assert!(format!("{err}").contains("restricted"));
114 }
115
116 #[tokio::test]
117 async fn rejects_ipv6_literal_unspecified() {
118 let url = reqwest::Url::parse("http://[::]/").unwrap();
119 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
120 .await
121 .expect_err("[::] must be rejected as restricted");
122 assert!(format!("{err}").contains("restricted"));
123 }
124
125 #[tokio::test]
126 async fn redirected_host_respects_network_policy() {
127 use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider};
128 let policy = NetworkPolicy {
129 default: Decision::Deny.into(),
130 allow: vec!["api.deepseek.com".to_string()],
131 deny: vec![],
132 proxy: Vec::new(),
133 proxy_fake_ip_cidrs: Vec::new(),
134 audit: false,
135 };
136 let decider = NetworkPolicyDecider::new(policy, None);
137 let ctx = ToolContext::new(PathBuf::from(".")).with_network_policy(decider);
138 let url = reqwest::Url::parse("https://example.com/redirect-target").unwrap();
139 let err = validate_fetch_target(&url, &ctx, "fetch_url", PrivateTargets::TypedLocalHosts)
140 .await
141 .unwrap_err();
142 assert!(format!("{err}").contains("blocked"));
143 }
144
145 #[tokio::test]
146 async fn unresolved_hostname_is_rejected_before_request() {
147 let url =
148 reqwest::Url::parse("https://codewhale-unresolvable-fetch-target.invalid/resource")
149 .unwrap();
150 let err = validate_fetch_target(&url, &ctx(), "fetch_url", PrivateTargets::TypedLocalHosts)
151 .await
152 .expect_err("unresolved host must fail preflight");
153 let message = format!("{err}");
154 assert!(
155 message.contains("could not resolve host") || message.contains("restricted address"),
156 "error must identify preflight DNS or restricted-IP failure; got {err}"
157 );
158 }
159
160 #[tokio::test]
161 async fn web_run_tool_label_is_used_in_dns_error() {
162 let url =
163 reqwest::Url::parse("https://codewhale-unresolvable-web-run-target.invalid/resource")
164 .unwrap();
165 let err = validate_fetch_target(&url, &ctx(), "web_run", PrivateTargets::TypedLocalHosts)
166 .await
167 .expect_err("unresolved host must fail preflight");
168 let message = format!("{err}");
169 // Either DNS failure (mentions web_run) or a restricted resolution.
170 assert!(
171 message.contains("web_run") || message.contains("restricted address"),
172 "error should be labeled for web_run or report restricted IP; got {err}"
173 );
174 }
175
176 #[test]
177 fn dns_preflight_bound_stays_below_the_fetch_hard_cap() {
178 // The pre-flight resolution runs before every guarded request (and
179 // once per redirect); its own bound must leave room inside the fetch
180 // tool's hard cap instead of being able to outlast it. A wedged
181 // resolver surfaces as a timeout error, not a stalled tool.
182 assert!(
183 DNS_PREFLIGHT_TIMEOUT < super::super::fetch::HARD_MAX_TIMEOUT,
184 "DNS pre-flight bound {:?} must stay below the fetch hard cap {:?}",
185 DNS_PREFLIGHT_TIMEOUT,
186 super::super::fetch::HARD_MAX_TIMEOUT
187 );
188 }
189 }
190
190 lines RUST