Skip to main content

ruso_runtime/runtime/
http.rs

1use std::collections::HashMap;
2use std::time::{Duration, Instant};
3
4use futures::StreamExt;
5use reqwest::header::HeaderMap;
6use reqwest::{Client, Method, RequestBuilder};
7
8use crate::contract::HttpMethod;
9use crate::runtime::body::{object_to_form, object_to_json, object_to_multipart};
10use crate::runtime::bytes::decode_hex;
11use crate::runtime::context::VariableValue;
12use crate::runtime::duration::parse_duration;
13use crate::runtime::error::RuntimeError;
14use crate::runtime::interpolate::interpolate;
15use crate::runtime::response::HttpResponse;
16use crate::runtime::spec::HttpRequestSpec;
17
18pub async fn execute_http(
19    client: &Client,
20    base_url: &str,
21    spec: &HttpRequestSpec,
22    variables: &HashMap<String, VariableValue>,
23    max_response_bytes: usize,
24    retries: u32,
25) -> Result<HttpResponse, RuntimeError> {
26    let raw_path = spec.path.as_str();
27    let path = interpolate(raw_path, variables)?;
28    let url = join_url(base_url, raw_path, &path)?;
29    let method = to_reqwest_method(&spec.method);
30    let timeout = spec.timeout.as_deref().map(parse_duration).transpose()?;
31
32    tracing::debug!(%url, ?method, "http request");
33
34    let mut builder = client.request(method, url);
35    if let Some(duration) = timeout {
36        builder = builder.timeout(duration);
37    }
38
39    if let Some(agent) = &spec.user_agent {
40        builder = builder.header("user-agent", interpolate(agent, variables)?);
41    }
42
43    for (name, value) in &spec.headers {
44        builder = builder.header(
45            interpolate(name, variables)?,
46            interpolate(value, variables)?,
47        );
48    }
49
50    // RFC 6265 §5.4 requires all cookies to ride in a single `Cookie:` header
51    // joined by `"; "`. reqwest's `.header()` appends, so emitting one call
52    // per cookie produced multiple `Cookie:` headers — accepted leniently by
53    // some servers, rejected outright by others. Build one joined string.
54    if !spec.cookies.is_empty() {
55        let mut parts = Vec::with_capacity(spec.cookies.len());
56        for (name, value) in &spec.cookies {
57            let name = interpolate(name, variables)?;
58            let value = interpolate(value, variables)?;
59            parts.push(format!("{name}={value}"));
60        }
61        builder = builder.header("cookie", parts.join("; "));
62    }
63
64    if !spec.queries.is_empty() {
65        let pairs: Vec<(String, String)> = spec
66            .queries
67            .iter()
68            .map(|(name, value)| {
69                Ok((
70                    interpolate(name, variables)?,
71                    interpolate(value, variables)?,
72                ))
73            })
74            .collect::<Result<_, RuntimeError>>()?;
75        builder = builder.query(&pairs);
76    }
77
78    builder = apply_body(builder, spec, variables)?;
79
80    let (response, elapsed) = send_with_retries(builder, retries).await?;
81    let status = response.status().as_u16();
82    let headers = flatten_headers(response.headers());
83    let body = read_body_capped(response, max_response_bytes).await?;
84
85    Ok(HttpResponse {
86        status,
87        headers,
88        body,
89        elapsed,
90    })
91}
92
93/// Stream the response body into a buffer, stopping once `max_bytes` is
94/// reached. Caps memory use against malicious targets returning multi-GB
95/// payloads. The returned `String` is a lossy UTF-8 decode of the truncated
96/// bytes — matchers that need byte-precise comparison should use socket
97/// probes, not HTTP body.
98async fn read_body_capped(
99    response: reqwest::Response,
100    max_bytes: usize,
101) -> Result<String, RuntimeError> {
102    if max_bytes == 0 {
103        return Ok(String::new());
104    }
105    let mut buf: Vec<u8> = Vec::new();
106    let mut stream = response.bytes_stream();
107    while let Some(chunk) = stream.next().await {
108        let chunk = chunk?;
109        let remaining = max_bytes.saturating_sub(buf.len());
110        if remaining == 0 {
111            tracing::warn!(
112                limit = max_bytes,
113                "http response body truncated at max_response_bytes"
114            );
115            break;
116        }
117        let take = chunk.len().min(remaining);
118        buf.extend_from_slice(&chunk[..take]);
119        if take < chunk.len() {
120            tracing::warn!(
121                limit = max_bytes,
122                "http response body truncated at max_response_bytes"
123            );
124            break;
125        }
126    }
127    Ok(String::from_utf8_lossy(&buf).into_owned())
128}
129
130/// Send `builder`, retrying transient transport failures up to `retries` times.
131///
132/// Returns the response and the elapsed time of the attempt that produced it
133/// (backoff waits are excluded, so `response_time` matchers stay meaningful).
134/// Only connection-level failures are retried — a reset peer or a connect/read
135/// timeout — never a received HTTP response (any status) or a permanent TLS
136/// certificate rejection. Each retry clones the request; a non-cloneable
137/// (streaming) body is sent once.
138async fn send_with_retries(
139    builder: RequestBuilder,
140    retries: u32,
141) -> Result<(reqwest::Response, Duration), reqwest::Error> {
142    let mut attempt = 0u32;
143    loop {
144        // Clone for every attempt except the last so `builder` survives to
145        // retry; on the last attempt (or a non-cloneable body) consume it.
146        let cloned = if attempt < retries {
147            builder.try_clone()
148        } else {
149            None
150        };
151        let Some(request) = cloned else {
152            let started = Instant::now();
153            return builder.send().await.map(|resp| (resp, started.elapsed()));
154        };
155
156        let started = Instant::now();
157        match request.send().await {
158            Ok(response) => return Ok((response, started.elapsed())),
159            Err(err) if is_transient(&err) => {
160                attempt += 1;
161                tokio::time::sleep(retry_backoff(attempt)).await;
162            }
163            Err(err) => return Err(err),
164        }
165    }
166}
167
168/// Backoff before retry attempt `n` (1-based): 300ms, 800ms, then 1.5s.
169fn retry_backoff(n: u32) -> Duration {
170    match n {
171        1 => Duration::from_millis(300),
172        2 => Duration::from_millis(800),
173        _ => Duration::from_millis(1500),
174    }
175}
176
177/// Whether a failed request is worth retrying: a timeout, or a connection-level
178/// failure that is *not* a TLS certificate rejection (those are permanent —
179/// retrying only repeats the same handshake error).
180fn is_transient(err: &reqwest::Error) -> bool {
181    if err.is_timeout() {
182        return true;
183    }
184    err.is_connect() && !error_mentions(err, "certificate")
185}
186
187/// Case-insensitive search for `needle` across an error's full source chain.
188fn error_mentions(err: &reqwest::Error, needle: &str) -> bool {
189    let mut source: Option<&dyn std::error::Error> = Some(err);
190    while let Some(cause) = source {
191        if cause.to_string().to_ascii_lowercase().contains(needle) {
192            return true;
193        }
194        source = cause.source();
195    }
196    false
197}
198
199/// Build the `reqwest` client used for HTTP probes.
200///
201/// The settings here are the executor-wide defaults; an individual probe can
202/// override the timeout, redirect, TLS-verification, and proxy behaviour in its
203/// own [`HttpRequestSpec`](crate::runtime::spec::HttpRequestSpec), in which
204/// case a separate client is built for it.
205///
206/// # Errors
207///
208/// Returns [`RuntimeError::Http`] when the proxy URL is malformed or the TLS
209/// backend fails to initialize.
210pub fn build_client(
211    default_timeout: Option<std::time::Duration>,
212    follow_redirect: bool,
213    verify_ssl: bool,
214    proxy: Option<&str>,
215) -> Result<Client, RuntimeError> {
216    let mut builder = Client::builder();
217    if let Some(timeout) = default_timeout {
218        builder = builder.timeout(timeout);
219    }
220    builder = builder.redirect(if follow_redirect {
221        reqwest::redirect::Policy::limited(10)
222    } else {
223        reqwest::redirect::Policy::none()
224    });
225    if !verify_ssl {
226        builder = builder.danger_accept_invalid_certs(true);
227    }
228    if let Some(proxy_url) = proxy {
229        builder = builder.proxy(reqwest::Proxy::all(proxy_url)?);
230    }
231    Ok(builder.build()?)
232}
233
234/// Attach request body; first matching mode in the request block wins (see `http_spec`).
235fn apply_body(
236    builder: RequestBuilder,
237    spec: &HttpRequestSpec,
238    variables: &HashMap<String, VariableValue>,
239) -> Result<RequestBuilder, RuntimeError> {
240    if let Some(body) = &spec.json_body {
241        let json = object_to_json(body, variables)?;
242        return Ok(builder
243            .header("content-type", "application/json")
244            .body(json));
245    }
246    if let Some(body) = &spec.data_body {
247        let form = object_to_form(body, variables)?;
248        return Ok(builder.form(&form));
249    }
250    if let Some(raw) = &spec.raw_body {
251        return Ok(builder.body(interpolate(raw, variables)?));
252    }
253    if let Some(body) = &spec.multipart_body {
254        let form = object_to_multipart(body, variables)?;
255        return Ok(builder.multipart(form));
256    }
257    if let Some(hex) = &spec.body_bytes {
258        let bytes = decode_hex(&interpolate(hex, variables)?)?;
259        return Ok(builder.body(bytes));
260    }
261    Ok(builder)
262}
263
264fn to_reqwest_method(method: &HttpMethod) -> Method {
265    match method {
266        HttpMethod::Get => Method::GET,
267        HttpMethod::Post => Method::POST,
268        HttpMethod::Put => Method::PUT,
269        HttpMethod::Patch => Method::PATCH,
270        HttpMethod::Delete => Method::DELETE,
271        HttpMethod::Head => Method::HEAD,
272        HttpMethod::Options => Method::OPTIONS,
273    }
274}
275
276/// Resolve the request URL relative to the scan target (`base`).
277///
278/// `raw_path` is the path written in the script (pre-interpolation);
279/// `resolved_path` is the same string after `{{ var }}` substitution.
280/// We allow absolute URLs *if and only if* the script itself wrote one —
281/// allowing interpolation to switch the scheme/host opens an SSRF where a
282/// previously-extracted variable can redirect later probes to internal
283/// services (`http://169.254.169.254/...`, `http://localhost:6379/...`).
284fn join_url(base: &str, raw_path: &str, resolved_path: &str) -> Result<String, RuntimeError> {
285    let raw_is_absolute = is_absolute_http_url(raw_path);
286    let resolved_is_absolute = is_absolute_http_url(resolved_path);
287    if raw_is_absolute {
288        return Ok(resolved_path.to_string());
289    }
290    if resolved_is_absolute {
291        // Interpolation produced an absolute URL from a relative template —
292        // a hostname swap by variable. Reject.
293        return Err(RuntimeError::Other(format!(
294            "interpolated path switched to absolute URL; refusing as SSRF guard: {resolved_path}"
295        )));
296    }
297    let base = base.trim_end_matches('/');
298    let path = if resolved_path.starts_with('/') {
299        resolved_path.to_string()
300    } else {
301        format!("/{resolved_path}")
302    };
303    Ok(format!("{base}{path}"))
304}
305
306fn is_absolute_http_url(value: &str) -> bool {
307    let lower = value.trim_start();
308    lower.starts_with("http://") || lower.starts_with("https://")
309}
310
311/// Convert reqwest's `HeaderMap` into a `HashMap<String, String>` for
312/// downstream matchers. HTTP allows multi-valued headers (most notably
313/// `Set-Cookie`, also `WWW-Authenticate`, `Link`, etc.); reqwest's
314/// `HeaderMap` keeps them as separate entries, but matchers expect one
315/// string per header name. We collapse duplicates by joining with `", "`,
316/// which is the RFC 7230 §3.2.2 combining rule for the headers it applies
317/// to; `Set-Cookie` is the documented exception, but matchers operate by
318/// substring search ("`HttpOnly`", "`Secure`", domain names) which still
319/// works correctly against a joined string.
320fn flatten_headers(headers: &HeaderMap) -> HashMap<String, String> {
321    let mut map: HashMap<String, String> = HashMap::new();
322    for (name, value) in headers.iter() {
323        let Ok(text) = value.to_str() else { continue };
324        match map.entry(name.as_str().to_string()) {
325            std::collections::hash_map::Entry::Occupied(mut e) => {
326                let combined = format!("{}, {}", e.get(), text);
327                e.insert(combined);
328            }
329            std::collections::hash_map::Entry::Vacant(e) => {
330                e.insert(text.to_string());
331            }
332        }
333    }
334    map
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use reqwest::header::{HeaderMap, HeaderValue};
341
342    #[test]
343    fn join_url_appends_relative_path() {
344        let url = join_url("http://t.example", "/api", "/api").unwrap();
345        assert_eq!(url, "http://t.example/api");
346    }
347
348    #[test]
349    fn join_url_handles_path_without_leading_slash() {
350        let url = join_url("http://t.example", "api", "api").unwrap();
351        assert_eq!(url, "http://t.example/api");
352    }
353
354    #[test]
355    fn join_url_strips_trailing_base_slash() {
356        let url = join_url("http://t.example/", "/api", "/api").unwrap();
357        assert_eq!(url, "http://t.example/api");
358    }
359
360    #[test]
361    fn join_url_allows_explicitly_absolute_path() {
362        // Script writer wrote a full URL into the path — that's an explicit
363        // opt-in, so we honor it (e.g. probing a different origin during a
364        // multi-host check).
365        let url = join_url(
366            "http://t.example",
367            "https://other.example/x",
368            "https://other.example/x",
369        )
370        .unwrap();
371        assert_eq!(url, "https://other.example/x");
372    }
373
374    #[test]
375    fn join_url_rejects_interpolated_scheme_switch() {
376        // The template is a relative path, but a variable expanded into a
377        // full URL. That's an SSRF vector — refuse.
378        let err = join_url(
379            "http://t.example",
380            "/api/{{ next }}",
381            "http://169.254.169.254/latest/meta-data",
382        )
383        .unwrap_err();
384        let msg = err.to_string();
385        assert!(msg.contains("SSRF"), "expected SSRF guard, got: {msg}");
386    }
387
388    #[test]
389    fn join_url_rejects_interpolated_localhost_redirect() {
390        let err = join_url(
391            "http://t.example",
392            "{{ extracted }}",
393            "http://localhost:6379/info",
394        )
395        .unwrap_err();
396        assert!(err.to_string().contains("SSRF"));
397    }
398
399    #[test]
400    fn flatten_headers_combines_duplicates() {
401        let mut headers = HeaderMap::new();
402        headers.append("set-cookie", HeaderValue::from_static("a=1"));
403        headers.append("set-cookie", HeaderValue::from_static("b=2"));
404        let flat = flatten_headers(&headers);
405        let cookie = flat.get("set-cookie").expect("set-cookie");
406        // Joined form so substring matchers on cookie attributes still work.
407        assert!(cookie.contains("a=1"));
408        assert!(cookie.contains("b=2"));
409    }
410
411    #[test]
412    fn flatten_headers_keeps_single_value_intact() {
413        let mut headers = HeaderMap::new();
414        headers.insert("x-foo", HeaderValue::from_static("bar"));
415        let flat = flatten_headers(&headers);
416        assert_eq!(flat.get("x-foo").map(String::as_str), Some("bar"));
417    }
418
419    /// Localhost server that stalls the first connection past the probe timeout
420    /// (a transient failure), then answers every later connection with 200 OK.
421    /// Each connection is handled on its own thread so `accept` never blocks.
422    fn spawn_stall_then_ok_server() -> u16 {
423        use std::io::{Read, Write};
424        use std::net::TcpListener;
425        use std::sync::Arc;
426        use std::sync::atomic::{AtomicU32, Ordering};
427
428        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
429        let port = listener.local_addr().unwrap().port();
430        let seen = Arc::new(AtomicU32::new(0));
431        std::thread::spawn(move || {
432            for stream in listener.incoming().flatten() {
433                let seen = seen.clone();
434                std::thread::spawn(move || {
435                    let mut stream = stream;
436                    if seen.fetch_add(1, Ordering::SeqCst) == 0 {
437                        std::thread::sleep(Duration::from_secs(2));
438                        return;
439                    }
440                    let mut buf = [0u8; 512];
441                    let _ = stream.read(&mut buf);
442                    let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
443                });
444            }
445        });
446        port
447    }
448
449    fn probe_spec() -> HttpRequestSpec {
450        HttpRequestSpec {
451            method: HttpMethod::Get,
452            path: "/".into(),
453            timeout: Some("700ms".into()),
454            ..Default::default()
455        }
456    }
457
458    #[tokio::test]
459    async fn retries_recover_a_transient_failure() {
460        let base = format!("http://127.0.0.1:{}", spawn_stall_then_ok_server());
461        let client = build_client(None, false, true, None).unwrap();
462        let result = execute_http(&client, &base, &probe_spec(), &HashMap::new(), 1 << 20, 2).await;
463        assert!(result.is_ok(), "retry should recover; got {result:?}");
464        assert_eq!(result.unwrap().status, 200);
465    }
466
467    #[tokio::test]
468    async fn zero_retries_surfaces_the_transient_failure() {
469        // 0 retries is what a probe driven by the script's own `retry` gets:
470        // the single stalled attempt must fail rather than silently retrying.
471        let base = format!("http://127.0.0.1:{}", spawn_stall_then_ok_server());
472        let client = build_client(None, false, true, None).unwrap();
473        let result = execute_http(&client, &base, &probe_spec(), &HashMap::new(), 1 << 20, 0).await;
474        assert!(result.is_err(), "with no retries the failure must surface");
475    }
476}