agentmux_srv/drone/executor/blocks/
api.rs1use std::collections::HashMap;
24use std::net::{Ipv4Addr, Ipv6Addr};
25use std::sync::OnceLock;
26use std::time::Duration;
27
28use serde_json::{json, Value};
29
30use crate::drone::data_flow::ExecutionScope;
31use crate::drone::types::FlowNode;
32
33use super::api_auth;
34
35const DEFAULT_TIMEOUT_MS: u64 = 30_000;
36
37const MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
39
40static CREDENTIAL_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
43
44fn credential_client() -> &'static reqwest::Client {
45 CREDENTIAL_CLIENT.get_or_init(|| crate::http_client::client_with(|b| b.redirect(reqwest::redirect::Policy::none())))
46}
47
48static HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
53
54fn http_client() -> &'static reqwest::Client {
55 HTTP_CLIENT.get_or_init(|| {
56 crate::http_client::client_with(|b| {
57 b.redirect(reqwest::redirect::Policy::custom(|attempt| {
62 if let Err(e) = validate_url_for_safety(attempt.url()) {
63 return attempt.error(format!("redirect blocked: {e}"));
64 }
65 if attempt.previous().len() >= 10 {
66 return attempt.error("too many redirects");
67 }
68 attempt.follow()
69 }))
70 })
71 })
72}
73
74fn validate_url_safety(url_str: &str) -> Result<(), String> {
82 let url = reqwest::Url::parse(url_str)
83 .map_err(|e| format!("invalid URL: {e}"))?;
84 validate_url_for_safety(&url)
85}
86
87fn validate_url_for_safety(url: &reqwest::Url) -> Result<(), String> {
91 match url.scheme() {
92 "http" | "https" => {}
93 other => return Err(format!("URL scheme `{other}` is not allowed (http/https only)")),
94 }
95 let host = url
96 .host_str()
97 .ok_or_else(|| "URL missing host".to_string())?;
98 if let Some(inner) = host.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
102 let v6: Ipv6Addr = inner
103 .parse()
104 .map_err(|e| format!("invalid IPv6 host `{inner}`: {e}"))?;
105 if is_reserved_v6(&v6) {
106 return Err(format!("host `{v6}` is a reserved IPv6 address"));
107 }
108 return Ok(());
109 }
110 if host.eq_ignore_ascii_case("localhost") {
111 return Err("host `localhost` is not allowed".to_string());
112 }
113 if let Ok(v4) = host.parse::<Ipv4Addr>() {
114 if is_reserved_v4(&v4) {
115 return Err(format!("host `{v4}` is a reserved/private IP"));
116 }
117 }
118 Ok(())
121}
122
123fn is_reserved_v4(v4: &Ipv4Addr) -> bool {
124 v4.is_loopback()
125 || v4.is_private()
126 || v4.is_link_local()
127 || v4.is_broadcast()
128 || v4.is_unspecified()
129 || v4.is_multicast()
130}
131
132fn is_reserved_v6(v6: &Ipv6Addr) -> bool {
133 if v6.is_loopback()
138 || v6.is_unspecified()
139 || v6.is_multicast()
140 || (v6.segments()[0] & 0xfe00) == 0xfc00
143 || (v6.segments()[0] & 0xffc0) == 0xfe80
145 {
146 return true;
147 }
148 if let Some(v4) = v6.to_ipv4_mapped() {
154 return is_reserved_v4(&v4);
155 }
156 #[allow(deprecated)]
157 if let Some(v4) = v6.to_ipv4() {
158 return is_reserved_v4(&v4);
162 }
163 false
164}
165
166struct Credential {
168 name: reqwest::header::HeaderName,
169 value: reqwest::header::HeaderValue,
170 scrubber: crate::backend::vault::scrub::Scrubber,
171}
172
173async fn credential(node: &FlowNode, scope: &ExecutionScope, url_raw: &str, url: &str, headers: &HashMap<String, String>) -> Result<Option<Credential>, String> {
176 let Some(auth) = api_auth::parse(&node.data)? else { return Ok(None) };
177 if scope.drone_id.trim().is_empty() {
178 return Err("a Vault credential is for a saved drone's run".into());
179 }
180 let site = api_auth::site(url_raw, url)?;
181 let name = auth.how.name();
182 if headers.keys().any(|k| k.trim().eq_ignore_ascii_case("host")) {
185 return Err("a call with a Vault credential can't set the Host header: it goes to the site in the URL".into());
186 }
187 if api_auth::sets_it_too(headers, &name) {
188 return Err(format!("the node sets the {name} header and also takes it from the Vault: leave it out of `headers`"));
189 }
190 let state = crate::drone::host::state()?;
191 let asking = if scope.never_ask { crate::server::drone_vault::Asking::Never } else { crate::server::drone_vault::Asking::Person };
192 let resolved = crate::server::drone_vault::resolve_with(state, &scope.drone_id, &auth.entry, &site, asking).await?;
193 let value = auth.how.value(&resolved.value)?;
194 Ok(Some(Credential { name, value, scrubber: resolved.scrubber }))
195}
196
197fn clean(credential: &Option<Credential>, text: String) -> String {
199 match credential {
200 Some(c) => c.scrubber.scrub(&text).into_owned(),
201 None => text,
202 }
203}
204
205fn read_error(e: &reqwest::Error, timeout_ms: u64) -> String {
207 if e.is_timeout() {
208 format!("timed out after {} seconds: {e}", timeout_ms.div_ceil(1000))
209 } else {
210 format!("read body: {e}")
211 }
212}
213
214async fn read_capped(mut resp: reqwest::Response, timeout_ms: u64) -> Result<Vec<u8>, String> {
216 if resp.content_length().is_some_and(|n| n > MAX_RESPONSE_BYTES as u64) {
217 return Err(format!("the response is longer than {} MiB", MAX_RESPONSE_BYTES / (1024 * 1024)));
218 }
219 let mut bytes = Vec::new();
220 while let Some(chunk) = resp.chunk().await.map_err(|e| read_error(&e, timeout_ms))? {
221 if bytes.len() + chunk.len() > MAX_RESPONSE_BYTES {
222 return Err(format!("the response is longer than {} MiB", MAX_RESPONSE_BYTES / (1024 * 1024)));
223 }
224 bytes.extend_from_slice(&chunk);
225 }
226 Ok(bytes)
227}
228
229pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
230 let method_raw = node
231 .data
232 .get("method")
233 .and_then(|v| v.as_str())
234 .unwrap_or("GET")
235 .to_uppercase();
236 let url_raw = node
237 .data
238 .get("url")
239 .and_then(|v| v.as_str())
240 .ok_or_else(|| "API block missing `url`".to_string())?;
241 let url = scope.resolve(url_raw);
242 if url.trim().is_empty() {
243 return Err("API block resolved URL is empty".to_string());
244 }
245 validate_url_safety(&url)?;
246
247 let headers_map: HashMap<String, String> = match node.data.get("headers") {
248 Some(Value::Object(obj)) => obj
249 .iter()
250 .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), scope.resolve(s))))
251 .collect(),
252 _ => HashMap::new(),
253 };
254
255 let body_resolved: Option<String> = node
256 .data
257 .get("body")
258 .and_then(|v| v.as_str())
259 .map(|s| scope.resolve(s));
260
261 let timeout_ms = node
262 .data
263 .get("timeout_ms")
264 .and_then(|v| v.as_u64())
265 .unwrap_or(DEFAULT_TIMEOUT_MS);
266
267 let credential = credential(node, scope, url_raw, &url, &headers_map).await?;
269
270 let client = if credential.is_some() { credential_client() } else { http_client() };
271 let method = reqwest::Method::from_bytes(method_raw.as_bytes())
272 .map_err(|e| format!("invalid method `{method_raw}`: {e}"))?;
273 let mut req = client
274 .request(method, &url)
275 .timeout(Duration::from_millis(timeout_ms));
276 for (k, v) in &headers_map {
277 req = req.header(k, v);
278 }
279 if let Some(c) = &credential {
280 req = req.header(c.name.clone(), c.value.clone());
281 }
282 if let Some(b) = body_resolved {
283 if !b.is_empty() {
284 req = req.body(b);
285 }
286 }
287 let (status, resp_headers, bytes) = exchange(req, timeout_ms).await.map_err(|e| clean(&credential, e))?;
288 let resp_headers: HashMap<String, String> =
289 resp_headers.into_iter().map(|(k, v)| (k, clean(&credential, v))).collect();
290 let text = clean(&credential, String::from_utf8_lossy(&bytes).to_string());
291 let body_val: Value = serde_json::from_str(&text).unwrap_or(Value::String(text));
293
294 Ok(json!({
295 "status": status,
296 "body": body_val,
297 "headers": resp_headers,
298 }))
299}
300
301async fn exchange(req: reqwest::RequestBuilder, timeout_ms: u64) -> Result<(u16, HashMap<String, String>, Vec<u8>), String> {
305 let timed_out = |e: &reqwest::Error| format!("timed out after {} seconds: {e}", timeout_ms.div_ceil(1000));
306 let resp = req.send().await.map_err(|e| if e.is_timeout() { timed_out(&e) } else { format!("request failed: {e}") })?;
307 let status = resp.status().as_u16();
308 let headers: HashMap<String, String> = resp
309 .headers()
310 .iter()
311 .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
312 .collect();
313 let bytes = read_capped(resp, timeout_ms).await?;
314 Ok((status, headers, bytes))
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 async fn stalled(reply: &'static [u8]) -> String {
323 use tokio::io::AsyncWriteExt;
324 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
325 let url = format!("http://{}/", listener.local_addr().unwrap());
326 tokio::spawn(async move {
327 let (mut socket, _) = listener.accept().await.unwrap();
328 let _ = socket.write_all(reply).await;
329 tokio::time::sleep(Duration::from_secs(30)).await;
330 });
331 url
332 }
333
334 #[tokio::test]
335 async fn a_request_that_times_out_says_so_apart_from_one_that_could_not_connect() {
336 let client = reqwest::Client::new();
337 let url = stalled(b"").await;
338 let err = exchange(client.get(&url).timeout(Duration::from_millis(150)), 150).await.unwrap_err();
339 assert!(err.starts_with("timed out after 1 seconds:"), "{err}");
340
341 let url = stalled(b"HTTP/1.1 200 OK
342Content-Length: 10
343
344abc").await;
345 let err = exchange(client.get(&url).timeout(Duration::from_millis(300)), 300).await.unwrap_err();
346 assert!(err.starts_with("timed out after 1 seconds:"), "a body that stalls is a timeout too: {err}");
347
348 let refused = {
349 let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
350 format!("http://{}/", l.local_addr().unwrap())
351 };
352 let err = exchange(client.get(&refused).timeout(Duration::from_secs(5)), 5000).await.unwrap_err();
353 assert!(err.starts_with("request failed:"), "a refused connection is the world's failure: {err}");
354 }
355
356 #[test]
357 fn ssrf_rejects_loopback() {
358 assert!(validate_url_safety("http://127.0.0.1/").is_err());
359 assert!(validate_url_safety("http://127.0.0.1:8080/x").is_err());
360 assert!(validate_url_safety("https://[::1]/").is_err());
361 }
362
363 #[test]
364 fn ssrf_rejects_localhost_hostname() {
365 assert!(validate_url_safety("http://localhost/").is_err());
366 assert!(validate_url_safety("http://LocalHost:80/").is_err());
367 }
368
369 #[test]
370 fn ssrf_rejects_aws_metadata_endpoint() {
371 assert!(validate_url_safety("http://169.254.169.254/latest/meta-data/").is_err());
375 }
376
377 #[test]
378 fn ssrf_rejects_rfc1918_private() {
379 assert!(validate_url_safety("http://10.0.0.1/").is_err());
380 assert!(validate_url_safety("http://172.16.0.1/").is_err());
381 assert!(validate_url_safety("http://192.168.1.1/").is_err());
382 }
383
384 #[test]
385 fn ssrf_rejects_non_http_schemes() {
386 assert!(validate_url_safety("file:///etc/passwd").is_err());
387 assert!(validate_url_safety("ftp://example.com/").is_err());
388 assert!(validate_url_safety("gopher://example.com/").is_err());
389 }
390
391 #[test]
392 fn ssrf_rejects_ipv6_unique_local() {
393 assert!(validate_url_safety("http://[fc00::1]/").is_err());
395 assert!(validate_url_safety("http://[fd00::1]/").is_err());
396 }
397
398 #[test]
399 fn ssrf_rejects_ipv4_mapped_ipv6_to_reserved() {
400 assert!(validate_url_safety("http://[::ffff:127.0.0.1]/").is_err());
404 assert!(validate_url_safety("http://[::ffff:169.254.169.254]/").is_err());
405 assert!(validate_url_safety("http://[::ffff:10.0.0.1]/").is_err());
406 assert!(validate_url_safety("http://[::ffff:192.168.1.1]/").is_err());
407 }
408
409 #[test]
410 fn ssrf_rejects_ipv4_compatible_ipv6_to_reserved() {
411 assert!(validate_url_safety("http://[::127.0.0.1]/").is_err());
414 }
415
416 #[test]
417 fn ssrf_allows_public_ipv4_in_mapped_form() {
418 assert!(validate_url_safety("https://[::ffff:8.8.8.8]/").is_ok());
421 }
422
423 #[test]
424 fn ssrf_allows_public_hostnames() {
425 assert!(validate_url_safety("https://api.example.com/v1/users").is_ok());
426 assert!(validate_url_safety("http://example.com:8080/").is_ok());
427 }
428
429 #[test]
430 fn ssrf_allows_public_ip_literal() {
431 assert!(validate_url_safety("https://8.8.8.8/").is_ok());
433 }
434
435 fn node(data: Value) -> FlowNode {
436 FlowNode { id: "api1".to_string(), position: Default::default(), data, node_type: None }
437 }
438
439 fn scope_of(drone: &str) -> ExecutionScope {
440 ExecutionScope { drone_id: drone.to_string(), ..ExecutionScope::new() }
441 }
442
443 #[tokio::test]
444 async fn a_credential_that_cannot_be_used_is_an_error_never_a_call_without_it() {
445 let auth = json!({ "vault": "api-key-acme", "as": "bearer" });
446 let http = node(json!({ "url": "http://api.example.com/x", "auth": auth }));
448 let err = run(&http, &scope_of("nightly")).await.unwrap_err();
449 assert!(err.contains("https"), "{err}");
450 let moving = node(json!({ "url": "https://{{trigger.host}}/x", "auth": auth }));
452 let scope = ExecutionScope { trigger: json!({ "host": "evil.example.net" }), ..scope_of("nightly") };
453 let err = run(&moving, &scope).await.unwrap_err();
454 assert!(err.contains("written out"), "{err}");
455 let basic = node(json!({ "url": "https://api.example.com/x", "auth": { "vault": "k", "as": "basic" } }));
457 assert!(run(&basic, &scope_of("nightly")).await.is_err());
458 let both = node(json!({ "url": "https://api.example.com/x", "headers": { "Authorization": "Bearer mine" }, "auth": auth }));
460 let err = run(&both, &scope_of("nightly")).await.unwrap_err();
461 assert!(err.contains("authorization"), "{err}");
462 let host = node(json!({ "url": "https://api.example.com/x", "headers": { "host": "other-tenant.example.net" }, "auth": auth }));
464 let err = run(&host, &scope_of("nightly")).await.unwrap_err();
465 assert!(err.contains("Host"), "{err}");
466 let ok = node(json!({ "url": "https://api.example.com/x", "auth": auth }));
468 assert!(run(&ok, &scope_of("")).await.unwrap_err().contains("saved drone"));
469 }
470
471 async fn serve(head: &'static str, body: Vec<u8>) -> String {
473 use tokio::io::{AsyncReadExt, AsyncWriteExt};
474 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
475 let addr = listener.local_addr().unwrap();
476 tokio::spawn(async move {
477 let (mut sock, _) = listener.accept().await.unwrap();
478 let mut buf = [0u8; 1024];
479 let _ = sock.read(&mut buf).await;
480 let _ = sock.write_all(head.as_bytes()).await;
481 let _ = sock.write_all(&body).await;
482 let _ = sock.shutdown().await;
483 });
484 format!("http://{addr}/")
485 }
486
487 #[tokio::test]
488 async fn a_response_is_read_up_to_the_cap_and_no_further() {
489 let small = serve("HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\n", b"hello".to_vec()).await;
490 let resp = reqwest::get(&small).await.unwrap();
491 assert_eq!(read_capped(resp, 5000).await.unwrap(), b"hello");
492 let long = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", MAX_RESPONSE_BYTES + 1);
494 let head: &'static str = Box::leak(long.into_boxed_str());
495 let url = serve(head, Vec::new()).await;
496 let err = read_capped(reqwest::get(&url).await.unwrap(), 5000).await.unwrap_err();
497 assert!(err.contains("longer than"), "{err}");
498 let url = serve("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'x'; MAX_RESPONSE_BYTES + 10]).await;
500 let err = read_capped(reqwest::get(&url).await.unwrap(), 5000).await.unwrap_err();
501 assert!(err.contains("longer than"), "{err}");
502 }
503
504 #[test]
505 fn what_comes_back_is_cleaned_of_the_credential_when_the_call_had_one() {
506 let secret = "sk_live_abcdefgh1234";
507 let c = Some(Credential {
508 name: reqwest::header::AUTHORIZATION,
509 value: reqwest::header::HeaderValue::from_static("x"),
510 scrubber: crate::backend::vault::scrub::Scrubber::new(&[("api-key-acme".to_string(), secret.to_string())]),
511 });
512 assert_eq!(clean(&c, format!("{{\"echo\":\"Bearer {secret}\"}}")), "{\"echo\":\"Bearer [vault:api-key-acme]\"}");
513 assert_eq!(clean(&None, format!("Bearer {secret}")), format!("Bearer {secret}"));
514 }
515}