Skip to main content

agentmux_srv/drone/executor/blocks/
api.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! API block — HTTP request via reqwest. Honors `{{...}}` interpolation
5//! in url, headers, and body.
6//!
7//! Config (`node.data`):
8//!   * `method` — "GET" / "POST" / "PUT" / "DELETE" / "PATCH" (default GET)
9//!   * `url` — required; supports `{{...}}`
10//!   * `headers` — optional `{ name: value }` map; values support `{{...}}`
11//!   * `body` — optional string body (POST/PUT/PATCH); supports `{{...}}`
12//!   * `auth` — optional `{ vault: "<entry>", as: "bearer" | "header:<Name>" }`: a Vault
13//!     entry's value sent as that header. See [`super::api_auth`] for what keeps it on the one
14//!     site the drone names; the first call asks the person.
15//!
16//! Output:
17//!   ```json
18//!   { "status": 200, "body": <parsed-json-or-text>, "headers": { ... } }
19//!   ```
20//!
21//! A response is read up to [`MAX_RESPONSE_BYTES`]; a longer one is an error.
22
23use 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
37/// The most of a response a call reads: a drone's ledger is not where a download goes.
38const MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
39
40/// The client for a call with a Vault credential: it follows no redirect, so the credential goes
41/// to the one site the drone names and nowhere a response points.
42static 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
48/// Shared `reqwest::Client` so drones with multiple API blocks
49/// reuse one connection pool instead of building a new pool per
50/// request. Per-request timeouts move to the RequestBuilder.
51/// (reagent P2 on PR #755.)
52static 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            // Re-run SSRF validation on every redirect target —
58            // otherwise a public attacker-controlled URL can return
59            // `302 Location: http://169.254.169.254/...` and bypass
60            // the initial check. (codex P1 on PR #755.)
61            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
74/// Validate a resolved URL before dispatching it. Phase 1 SSRF
75/// protection: rejects non-http(s) schemes and literal-IP hosts that
76/// fall into reserved / link-local / private / loopback ranges (the
77/// AWS metadata endpoint 169.254.169.254, RFC1918 space, 127.0.0.1,
78/// fc00::/7, ::1, etc.). DNS-resolved hostnames are not re-checked
79/// post-resolution — that requires a custom `reqwest` resolver and
80/// lands as a follow-up issue. See kimi P1 on PR #755.
81fn 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
87/// Same checks as `validate_url_safety` but takes a pre-parsed
88/// `reqwest::Url`. The redirect-policy closure receives Url values
89/// directly, so this avoids a parse round-trip on every hop.
90fn 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    // IPv6 literals in URLs are bracketed: `https://[::1]/`. Strip the
99    // brackets before attempting an IP parse; that path also lets us
100    // distinguish a true IPv6 literal from an ambiguous string.
101    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    // Otherwise it's a domain name — DNS-resolution-time SSRF
119    // validation is out of scope for Phase 1 (see fn doc-comment).
120    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    // Check pure-v6 reserved ranges first. Order matters: `::1` is
134    // v6 loopback AND happens to satisfy `to_ipv4()` (lower 32 bits
135    // map to 0.0.0.1, a public v4). Catching loopback up here avoids
136    // misclassifying it as "public v4 embedded in v6".
137    if v6.is_loopback()
138        || v6.is_unspecified()
139        || v6.is_multicast()
140        // unique-local fc00::/7 — stable API for this is gated, so
141        // check the segment manually.
142        || (v6.segments()[0] & 0xfe00) == 0xfc00
143        // link-local fe80::/10
144        || (v6.segments()[0] & 0xffc0) == 0xfe80
145    {
146        return true;
147    }
148    // IPv4-mapped (`::ffff:a.b.c.d`) and IPv4-compatible (`::a.b.c.d`,
149    // deprecated) literals route to the embedded IPv4 address on
150    // most kernels, bypassing v6-only checks. Delegate to the v4
151    // predicate so private/loopback IPv4 in v6 form is caught.
152    // (codex P1 on PR #755.)
153    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        // `to_ipv4` returns Some for mapped (handled above) AND
159        // IPv4-compatible (`::a.b.c.d`). This branch catches the
160        // compatible form.
161        return is_reserved_v4(&v4);
162    }
163    false
164}
165
166/// What a call with a Vault credential sends it as, and what takes it out of the answer.
167struct Credential {
168    name: reqwest::header::HeaderName,
169    value: reqwest::header::HeaderValue,
170    scrubber: crate::backend::vault::scrub::Scrubber,
171}
172
173/// Checks and resolves the node's `auth`, asking the person the first time. `None` when the node
174/// has none. Nothing is sent, and nothing but the person's answer is waited for.
175async 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    // The Host header picks the virtual host the server routes the request to: a node that kept the approved URL
183    // and set another Host would send the credential to a tenant nobody approved.
184    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
197/// `text` with the credential taken out of it, when the call had one.
198fn 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
205/// A failure while reading the body: a timeout is worded apart from the rest (see [`exchange`]).
206fn 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
214/// The response's body up to [`MAX_RESPONSE_BYTES`].
215async 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    // Before anything is sent: a bad `auth` is an error, never a call with no credential.
268    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    // Try to parse as JSON for downstream `{{api.body.field}}` access.
292    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
301/// Send the request and read the whole answer. A timeout says nothing about
302/// whether the other side did the work, so it is worded apart from a failure to
303/// connect: the retry policy runs the second again and never the first.
304async 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    /// A loopback server that answers with `reply` and then says nothing more.
322    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        // 169.254.169.254 is link-local (RFC 3927) — covers the cloud
372        // metadata endpoints for AWS, GCP, Azure (all use this address
373        // or other link-local IPs).
374        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        // fc00::/7 — RFC 4193 unique local addresses.
394        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        // ::ffff:a.b.c.d routes to a.b.c.d on most kernels. The v6
401        // path must delegate to the v4 reserved check or these slip
402        // past the SSRF guard. (codex P1.)
403        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        // ::a.b.c.d (IPv4-compatible, deprecated form). Defense in
412        // depth — some kernels still honor it.
413        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        // Mapped form of a public IP is consistent with allowing the
419        // plain form — block only the reserved range, not the wrapper.
420        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        // 8.8.8.8 is a public DNS address — not reserved.
432        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        // Not https: the credential would cross in the clear.
447        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        // The site comes from a run's value.
451        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        // An `auth` the block doesn't understand is not ignored.
456        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        // The node can't set the credential's header itself.
459        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        // A Host of another tenant would route the credential somewhere nobody approved.
463        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        // Not a saved drone's run: nobody to grant it to.
467        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    /// A one-shot HTTP server on a free local port that answers with `head` and `body`.
472    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        // One that says how long it is, too long.
493        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        // One that doesn't say, and goes on past it.
499        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}