Skip to main content

troupekit_tools/
http.rs

1use crate::tool::ToolError;
2#[cfg(any(feature = "reqwest", test))]
3use async_trait::async_trait;
4#[cfg(feature = "reqwest")]
5use reqwest::header::{ACCEPT, CONTENT_TYPE, LOCATION, USER_AGENT};
6#[cfg(feature = "reqwest")]
7use reqwest::redirect::Policy;
8use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
9#[cfg(feature = "reqwest")]
10use std::net::SocketAddr;
11use std::time::Duration;
12use troupekit_trace::{content, trace_span, url_for_trace, Trace};
13pub use troupekit_core::http::{
14    media_type, read_limited, Body, ChunkBody, HttpError, HttpErrorKind, HttpRequest, HttpResponse,
15    Method, Transport,
16};
17#[cfg(feature = "reqwest")]
18use url::{Host, Url};
19
20#[cfg(feature = "reqwest")]
21const AGENT: &str = concat!("troupekit/", env!("CARGO_PKG_VERSION"));
22
23/// A tool's view of an answer read into memory: status, final URL, lower-case
24/// media type without parameters, the body cut at the size limit, and
25/// `truncated` when bytes were dropped.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Received {
28    pub status: u16,
29    pub url: String,
30    pub content_type: String,
31    pub body: Vec<u8>,
32    pub truncated: bool,
33}
34
35/// Sends `req` through `http` and reads the whole body into memory, at most
36/// `HttpLimits::default().max_body_bytes` even when the transport has no cap.
37/// The span keeps the URL's origin in clear and its path as content, since
38/// some APIs carry a token in the path.
39/// Returns the answer, or the transport failure as a `ToolError`.
40pub async fn receive(http: &dyn Transport, req: HttpRequest) -> Result<Received, ToolError> {
41    let clean = url_for_trace(&req.url);
42    let (origin, path) = split_origin(&clean);
43    let mut span = trace_span!(
44        Trace::Tools,
45        "tool.http",
46        method = req.method.as_str(),
47        url = origin,
48        path = content(path),
49    );
50    let result = span.instrument(receive_body(http, req)).await;
51    match &result {
52        Ok(res) => {
53            span.record("status", res.status);
54            span.record("body_bytes", res.body.len());
55            span.record("truncated", res.truncated);
56        }
57        Err(_) => span.fail("request failed"),
58    }
59    result
60}
61
62/// Splits a URL cleaned by `url_for_trace` into its origin (scheme and
63/// authority) and the rest, at the first `/` or `\\` after the authority.
64/// `//` marks an authority only at the start or right after a scheme; any
65/// other input has an empty origin, so a relative path stays withheld.
66/// Input: the clean URL. Output: the origin and the path.
67fn split_origin(clean: &str) -> (&str, &str) {
68    let Some(at) = clean
69        .find("//")
70        .filter(|&at| at == 0 || is_scheme(&clean[..at]))
71    else {
72        return ("", clean);
73    };
74    let start = at + 2;
75    let end = clean[start..]
76        .find(['/', '\\'])
77        .map_or(clean.len(), |at| start + at);
78    assert!(start <= end && end <= clean.len());
79    clean.split_at(end)
80}
81
82/// Reports whether `text` is a URL scheme with its colon: an ASCII letter,
83/// then letters, digits, `+`, `-` or `.`, then `:`.
84/// Input: the text before `//`. Output: true for a scheme.
85fn is_scheme(text: &str) -> bool {
86    let Some(name) = text.strip_suffix(':') else {
87        return false;
88    };
89    let mut chars = name.chars();
90    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
91        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
92}
93
94async fn receive_body(http: &dyn Transport, req: HttpRequest) -> Result<Received, ToolError> {
95    let mut res = http.send(req).await?;
96    let content_type = res.content_type();
97    let (body, over) =
98        read_limited(res.body.as_mut(), HttpLimits::default().max_body_bytes).await?;
99    Ok(Received {
100        status: res.status,
101        url: res.url,
102        content_type,
103        body,
104        truncated: res.truncated || over,
105    })
106}
107
108/// Limits for one request, redirects included.
109/// The default is 2 MiB of body, 15 seconds in total and 5 redirects.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct HttpLimits {
112    pub max_body_bytes: usize,
113    pub timeout: Duration,
114    pub max_redirects: usize,
115}
116
117impl Default for HttpLimits {
118    fn default() -> Self {
119        Self {
120            max_body_bytes: 2 * 1024 * 1024,
121            timeout: Duration::from_secs(15),
122            max_redirects: 5,
123        }
124    }
125}
126
127/// HTTP client that only reaches allowed addresses, public unicast by
128/// default. Each hop's host is resolved, every address checked and the
129/// connection pinned to a checked address; GET redirects are re-checked and
130/// a cross-origin hop drops all request headers. The body is read eagerly
131/// inside the time and size limits. No proxy is used.
132#[cfg(feature = "reqwest")]
133#[derive(Debug, Clone)]
134pub struct GuardedHttp {
135    limits: HttpLimits,
136    allow: fn(IpAddr) -> bool,
137}
138
139#[cfg(feature = "reqwest")]
140impl GuardedHttp {
141    /// Builds a client that reaches public unicast addresses only.
142    /// Returns the client with `limits` applied to every request.
143    pub fn new(limits: HttpLimits) -> Self {
144        Self {
145            limits,
146            allow: is_public_ip,
147        }
148    }
149
150    /// Builds a client with its own address rule, for tests and for
151    /// operator-configured self-hosted services. Crate-private so model
152    /// input can never widen the rule.
153    pub(crate) fn with_policy(limits: HttpLimits, allow: fn(IpAddr) -> bool) -> Self {
154        Self { limits, allow }
155    }
156
157    async fn follow(&self, req: HttpRequest) -> Result<HttpResponse, HttpError> {
158        let mut url = Url::parse(&req.url).map_err(|e| {
159            HttpError::new(
160                HttpErrorKind::Invalid,
161                format!("bad url `{}`: {e}", req.url),
162            )
163        })?;
164        let method = reqwest::Method::from_bytes(req.method.as_str().as_bytes())
165            .map_err(|e| HttpError::new(HttpErrorKind::Invalid, e.to_string()))?;
166        let mut headers = req.headers;
167        for _ in 0..=self.limits.max_redirects {
168            let addr = pinned_addr(&url, self.allow).await?;
169            let mut builder = reqwest::Client::builder()
170                .redirect(Policy::none())
171                .no_proxy();
172            if let Some(Host::Domain(domain)) = url.host() {
173                builder = builder.resolve(domain, addr);
174            }
175            let client = builder.build().map_err(|e| network(e.to_string()))?;
176            let mut rb = client
177                .request(method.clone(), url.clone())
178                .header(USER_AGENT, AGENT);
179            if !req.accept.is_empty() {
180                rb = rb.header(ACCEPT, req.accept.join(", "));
181            }
182            for (name, value) in &headers {
183                rb = rb.header(name.as_str(), value.as_str());
184            }
185            if let Some(body) = &req.body {
186                rb = rb.body(body.clone());
187            }
188            let mut response = rb
189                .send()
190                .await
191                .map_err(|e| network(format!("{url}: {}", e.without_url())))?;
192            let status = response.status();
193            if status.is_redirection() && req.method == Method::Get {
194                let location = response
195                    .headers()
196                    .get(LOCATION)
197                    .and_then(|l| l.to_str().ok())
198                    .ok_or_else(|| network(format!("{url}: redirect without a valid Location")))?;
199                let next = url
200                    .join(location)
201                    .map_err(|e| network(format!("bad redirect `{location}`: {e}")))?;
202                if next.origin() != url.origin() {
203                    headers.clear();
204                }
205                url = next;
206                continue;
207            }
208            let content_type = response
209                .headers()
210                .get(CONTENT_TYPE)
211                .and_then(|v| v.to_str().ok())
212                .map(media_type)
213                .unwrap_or_default();
214            if status.is_success()
215                && !req.accept.is_empty()
216                && !req
217                    .accept
218                    .iter()
219                    .any(|a| a.eq_ignore_ascii_case(&content_type))
220            {
221                return Err(HttpError::new(
222                    HttpErrorKind::Rejected,
223                    format!(
224                        "{url}: content type `{content_type}` is not one of {}",
225                        req.accept.join(", ")
226                    ),
227                ));
228            }
229            let reply_headers = response
230                .headers()
231                .iter()
232                .filter_map(|(k, v)| {
233                    v.to_str()
234                        .ok()
235                        .map(|v| (k.as_str().to_owned(), v.to_owned()))
236                })
237                .collect();
238            let max = self.limits.max_body_bytes;
239            let mut body = Vec::new();
240            let mut truncated = false;
241            while let Some(chunk) = response
242                .chunk()
243                .await
244                .map_err(|e| network(format!("{url}: {}", e.without_url())))?
245            {
246                let room = max - body.len();
247                if chunk.len() > room {
248                    body.extend_from_slice(&chunk[..room]);
249                    truncated = true;
250                    break;
251                }
252                body.extend_from_slice(&chunk);
253            }
254            assert!(body.len() <= max);
255            return Ok(HttpResponse {
256                status: status.as_u16(),
257                url: url.to_string(),
258                headers: reply_headers,
259                body: Box::new(ChunkBody::new(vec![body])),
260                truncated,
261            });
262        }
263        Err(HttpError::new(
264            HttpErrorKind::Rejected,
265            format!("more than {} redirects", self.limits.max_redirects),
266        ))
267    }
268}
269
270#[cfg(feature = "reqwest")]
271#[async_trait]
272impl Transport for GuardedHttp {
273    async fn send(&self, req: HttpRequest) -> Result<HttpResponse, HttpError> {
274        let timeout = self.limits.timeout;
275        tokio::time::timeout(timeout, self.follow(req))
276            .await
277            .map_err(|_| {
278                HttpError::new(
279                    HttpErrorKind::Timeout,
280                    format!("timed out after {} ms", timeout.as_millis()),
281                )
282            })?
283    }
284}
285
286#[cfg(any(feature = "reqwest", test))]
287fn network(message: String) -> HttpError {
288    HttpError::new(HttpErrorKind::Network, message)
289}
290
291#[cfg(feature = "reqwest")]
292fn blocked(message: String) -> HttpError {
293    HttpError::new(HttpErrorKind::Blocked, message)
294}
295
296#[cfg(feature = "reqwest")]
297async fn pinned_addr(url: &Url, allow: fn(IpAddr) -> bool) -> Result<SocketAddr, HttpError> {
298    if !matches!(url.scheme(), "http" | "https") {
299        return Err(blocked(format!(
300            "scheme `{}` is not http or https",
301            url.scheme()
302        )));
303    }
304    let port = url
305        .port_or_known_default()
306        .ok_or_else(|| blocked(format!("{url}: no port")))?;
307    let addrs: Vec<SocketAddr> = match url.host() {
308        Some(Host::Ipv4(ip)) => vec![SocketAddr::new(IpAddr::V4(ip), port)],
309        Some(Host::Ipv6(ip)) => vec![SocketAddr::new(IpAddr::V6(ip), port)],
310        Some(Host::Domain(domain)) => tokio::net::lookup_host((domain, port))
311            .await
312            .map_err(|e| network(format!("{domain}: {e}")))?
313            .collect(),
314        None => return Err(blocked(format!("{url}: no host"))),
315    };
316    if let Some(bad) = addrs.iter().find(|a| !allow(a.ip())) {
317        return Err(blocked(format!(
318            "{url}: address {} is not public",
319            bad.ip()
320        )));
321    }
322    addrs
323        .first()
324        .copied()
325        .ok_or_else(|| network(format!("{url}: host has no address")))
326}
327
328/// Whether `ip` is a public unicast address a tool may reach.
329/// Private, loopback, link-local, unspecified, multicast, broadcast, CGNAT,
330/// documentation, reserved and unique-local ranges are not, nor IPv6 forms
331/// that embed such an IPv4 address.
332pub fn is_public_ip(ip: IpAddr) -> bool {
333    match ip {
334        IpAddr::V4(v4) => is_public_v4(v4),
335        IpAddr::V6(v6) => is_public_v6(v6),
336    }
337}
338
339fn is_public_v4(ip: Ipv4Addr) -> bool {
340    let [a, b, c, _] = ip.octets();
341    let blocked = a == 0
342        || a == 10
343        || a == 127
344        || (a == 100 && (b & 0xc0) == 64)
345        || (a == 169 && b == 254)
346        || (a == 172 && (b & 0xf0) == 16)
347        || (a == 192 && b == 0 && (c == 0 || c == 2))
348        || (a == 192 && b == 168)
349        || (a == 198 && (b & 0xfe) == 18)
350        || (a == 198 && b == 51 && c == 100)
351        || (a == 203 && b == 0 && c == 113)
352        || a >= 224;
353    !blocked
354}
355
356fn is_public_v6(ip: Ipv6Addr) -> bool {
357    if let Some(v4) = ip.to_ipv4_mapped() {
358        return is_public_v4(v4);
359    }
360    let s = ip.segments();
361    let embedded = |hi: u16, lo: u16| Ipv4Addr::from(((hi as u32) << 16) | lo as u32);
362    if s[0] == 0x64 && s[1] == 0xff9b {
363        return s[2..6] == [0, 0, 0, 0] && is_public_v4(embedded(s[6], s[7]));
364    }
365    if s[0] == 0x2002 {
366        return is_public_v4(embedded(s[1], s[2]));
367    }
368    let global_unicast = (s[0] & 0xe000) == 0x2000;
369    let teredo = s[0] == 0x2001 && s[1] == 0;
370    let documentation = (s[0] == 0x2001 && s[1] == 0x0db8) || (s[0] & 0xfff0) == 0x3ff0;
371    global_unicast && !teredo && !documentation
372}
373
374/// Test transport: answers from a queue and records every request.
375/// An empty queue answers a `Network` error. A response with an empty
376/// `url` gets the request's URL.
377#[cfg(test)]
378pub(crate) struct FakeHttp {
379    responses: std::sync::Mutex<std::collections::VecDeque<Result<Received, HttpError>>>,
380    requests: std::sync::Mutex<Vec<HttpRequest>>,
381}
382
383#[cfg(test)]
384impl FakeHttp {
385    /// Builds a fake that returns `responses` in order.
386    pub(crate) fn new(responses: Vec<Result<Received, HttpError>>) -> std::sync::Arc<Self> {
387        std::sync::Arc::new(Self {
388            responses: std::sync::Mutex::new(responses.into()),
389            requests: std::sync::Mutex::new(Vec::new()),
390        })
391    }
392
393    /// Builds a response with `status`, media type `mime` and `body`.
394    pub(crate) fn reply(status: u16, mime: &str, body: &str) -> Result<Received, HttpError> {
395        Ok(Received {
396            status,
397            url: String::new(),
398            content_type: mime.into(),
399            body: body.as_bytes().to_vec(),
400            truncated: false,
401        })
402    }
403
404    /// Returns copies of the requests received so far.
405    pub(crate) fn requests(&self) -> Vec<HttpRequest> {
406        self.requests.lock().unwrap().clone()
407    }
408}
409
410#[cfg(test)]
411#[async_trait]
412impl Transport for FakeHttp {
413    async fn send(&self, req: HttpRequest) -> Result<HttpResponse, HttpError> {
414        let url = req.url.clone();
415        self.requests.lock().unwrap().push(req);
416        let next = self
417            .responses
418            .lock()
419            .unwrap()
420            .pop_front()
421            .unwrap_or_else(|| Err(network("no fake response left".into())));
422        next.map(|r| HttpResponse {
423            status: r.status,
424            url: if r.url.is_empty() { url } else { r.url },
425            headers: vec![("content-type".into(), r.content_type)],
426            body: Box::new(ChunkBody::new(vec![r.body])),
427            truncated: r.truncated,
428        })
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    #[cfg(feature = "reqwest")]
436    use std::net::{Ipv4Addr, SocketAddr};
437    #[cfg(feature = "reqwest")]
438    use std::sync::{Arc, Mutex};
439    #[cfg(feature = "reqwest")]
440    use tokio::io::{AsyncReadExt, AsyncWriteExt};
441    #[cfg(feature = "reqwest")]
442    use tokio::net::TcpListener;
443
444    fn ip(s: &str) -> IpAddr {
445        s.parse().unwrap()
446    }
447
448    #[test]
449    fn blocks_non_public_addresses() {
450        for bad in [
451            "127.0.0.1",
452            "10.1.2.3",
453            "172.16.0.1",
454            "192.168.1.1",
455            "169.254.169.254",
456            "0.0.0.0",
457            "100.64.0.1",
458            "224.0.0.1",
459            "255.255.255.255",
460            "192.0.2.1",
461            "198.51.100.7",
462            "203.0.113.9",
463            "::1",
464            "::",
465            "fe80::1",
466            "fc00::1",
467            "fd12::1",
468            "ff02::1",
469            "2001:db8::1",
470            "::ffff:127.0.0.1",
471            "::ffff:10.0.0.1",
472            "::ffff:169.254.169.254",
473            "64:ff9b::a00:1",
474        ] {
475            assert!(!is_public_ip(ip(bad)), "{bad} must be blocked");
476        }
477        for good in [
478            "8.8.8.8",
479            "1.1.1.1",
480            "2606:4700:4700::1111",
481            "::ffff:8.8.8.8",
482        ] {
483            assert!(is_public_ip(ip(good)), "{good} must be allowed");
484        }
485    }
486
487    #[cfg(feature = "reqwest")]
488    #[tokio::test]
489    async fn rejects_bad_schemes_and_private_hosts() {
490        let http = GuardedHttp::new(HttpLimits::default());
491        for url in [
492            "file:///etc/passwd",
493            "ftp://example.com/",
494            "gopher://x/",
495            "http://127.0.0.1/",
496            "http://[::1]/",
497            "http://10.0.0.1/",
498            "http://localhost/",
499        ] {
500            let err = receive(&http, HttpRequest::get(url)).await.unwrap_err();
501            assert!(matches!(err, ToolError::Blocked(_)), "{url}: {err}");
502        }
503        assert!(matches!(
504            receive(&http, HttpRequest::get("not a url")).await,
505            Err(ToolError::InvalidArgs(_))
506        ));
507    }
508
509    #[cfg(feature = "reqwest")]
510    fn test_policy(ip: IpAddr) -> bool {
511        ip == IpAddr::V4(Ipv4Addr::LOCALHOST) || is_public_ip(ip)
512    }
513
514    #[cfg(feature = "reqwest")]
515    fn local() -> GuardedHttp {
516        GuardedHttp::with_policy(HttpLimits::default(), test_policy)
517    }
518
519    #[cfg(feature = "reqwest")]
520    async fn serve(responses: Vec<String>) -> (SocketAddr, Arc<Mutex<Vec<String>>>) {
521        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
522        let addr = listener.local_addr().unwrap();
523        let seen = Arc::new(Mutex::new(Vec::new()));
524        let log = seen.clone();
525        tokio::spawn(async move {
526            for body in responses {
527                let (mut sock, _) = listener.accept().await.unwrap();
528                let mut buf = vec![0u8; 8192];
529                let n = sock.read(&mut buf).await.unwrap_or(0);
530                log.lock()
531                    .unwrap()
532                    .push(String::from_utf8_lossy(&buf[..n]).to_ascii_lowercase());
533                sock.write_all(body.as_bytes()).await.unwrap();
534                sock.shutdown().await.ok();
535            }
536        });
537        (addr, seen)
538    }
539
540    #[cfg(feature = "reqwest")]
541    fn redirect(to: &str) -> String {
542        format!("HTTP/1.1 302 Found\r\nLocation: {to}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
543    }
544
545    #[cfg(feature = "reqwest")]
546    fn ok(mime: &str, body: &str) -> String {
547        format!("HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len())
548    }
549
550    #[cfg(feature = "reqwest")]
551    #[tokio::test]
552    async fn redirect_to_private_address_rejected_per_hop() {
553        for target in [
554            "http://10.0.0.1/x",
555            "http://[::ffff:192.168.0.1]/",
556            "http://169.254.169.254/latest",
557        ] {
558            let (addr, seen) = serve(vec![redirect(target)]).await;
559            let err = receive(&local(), HttpRequest::get(&format!("http://{addr}/start")))
560                .await
561                .unwrap_err();
562            assert_eq!(seen.lock().unwrap().len(), 1, "first hop must be served");
563            assert!(
564                matches!(err, ToolError::Blocked(ref m) if m.contains("not public")),
565                "{target}: {err}"
566            );
567        }
568    }
569
570    #[cfg(feature = "reqwest")]
571    #[tokio::test]
572    async fn follows_public_redirect() {
573        let (addr, seen) = serve(vec![
574            redirect("/page"),
575            ok("text/html; charset=utf-8", "<p>hi</p>"),
576        ])
577        .await;
578        let mut req = HttpRequest::get(&format!("http://{addr}/start"));
579        req.accept = vec!["text/html".into()];
580        let got = receive(&local(), req).await.unwrap();
581        assert_eq!(seen.lock().unwrap().len(), 2);
582        assert_eq!(
583            (got.status, got.content_type.as_str(), got.body.as_slice()),
584            (200, "text/html", b"<p>hi</p>".as_slice())
585        );
586        assert!(got.url.ends_with("/page") && !got.truncated);
587    }
588
589    #[cfg(feature = "reqwest")]
590    #[tokio::test]
591    async fn too_many_redirects_rejected() {
592        let (addr, _) = serve((0..7).map(|_| redirect("/again")).collect()).await;
593        let err = receive(&local(), HttpRequest::get(&format!("http://{addr}/")))
594            .await
595            .unwrap_err();
596        assert!(
597            matches!(err, ToolError::Http(ref m) if m.contains("redirects")),
598            "{err}"
599        );
600    }
601
602    #[cfg(feature = "reqwest")]
603    #[tokio::test]
604    async fn cross_origin_redirect_drops_headers() {
605        let (second, seen_second) = serve(vec![ok("text/plain", "done")]).await;
606        let (first, seen_first) = serve(vec![
607            redirect("/same"),
608            redirect(&format!("http://{second}/other")),
609        ])
610        .await;
611        let mut req = HttpRequest::get(&format!("http://{first}/start"));
612        req.headers.push(("X-Key".into(), "k-123".into()));
613        let got = receive(&local(), req).await.unwrap();
614        assert_eq!(got.body, b"done");
615        let first_log = seen_first.lock().unwrap().clone();
616        assert!(
617            first_log.iter().all(|r| r.contains("x-key: k-123")),
618            "same origin keeps headers"
619        );
620        assert!(
621            !seen_second.lock().unwrap()[0].contains("x-key"),
622            "other origin must not see headers"
623        );
624    }
625
626    #[cfg(feature = "reqwest")]
627    #[tokio::test]
628    async fn body_is_capped_and_flagged() {
629        let (addr, _) = serve(vec![ok("text/plain", &"a".repeat(3000))]).await;
630        let limits = HttpLimits {
631            max_body_bytes: 1024,
632            ..HttpLimits::default()
633        };
634        let got = receive(
635            &GuardedHttp::with_policy(limits, test_policy),
636            HttpRequest::get(&format!("http://{addr}/")),
637        )
638        .await
639        .unwrap();
640        assert_eq!(got.body.len(), 1024);
641        assert!(got.truncated);
642    }
643
644    #[cfg(feature = "reqwest")]
645    #[tokio::test]
646    async fn rejects_unaccepted_content_type() {
647        let (addr, _) = serve(vec![ok("image/png", "png")]).await;
648        let mut req = HttpRequest::get(&format!("http://{addr}/"));
649        req.accept = vec!["text/html".into()];
650        let err = receive(&local(), req).await.unwrap_err();
651        assert!(
652            matches!(err, ToolError::Http(ref m) if m.contains("image/png")),
653            "{err}"
654        );
655    }
656
657    #[cfg(feature = "reqwest")]
658    #[tokio::test]
659    async fn non_get_redirect_is_returned_not_followed() {
660        let (addr, seen) = serve(vec![redirect("/elsewhere")]).await;
661        let req = HttpRequest {
662            method: Method::Post,
663            body: Some(b"{}".to_vec()),
664            ..HttpRequest::get(&format!("http://{addr}/"))
665        };
666        let got = receive(&local(), req).await.unwrap();
667        assert_eq!(got.status, 302);
668        assert_eq!(seen.lock().unwrap().len(), 1);
669    }
670
671    #[cfg(feature = "reqwest")]
672    #[tokio::test]
673    async fn times_out() {
674        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
675        let addr = listener.local_addr().unwrap();
676        tokio::spawn(async move {
677            let (_sock, _) = listener.accept().await.unwrap();
678            tokio::time::sleep(Duration::from_secs(5)).await;
679        });
680        let limits = HttpLimits {
681            timeout: Duration::from_millis(200),
682            ..HttpLimits::default()
683        };
684        let err = receive(
685            &GuardedHttp::with_policy(limits, test_policy),
686            HttpRequest::get(&format!("http://{addr}/")),
687        )
688        .await
689        .unwrap_err();
690        assert!(
691            matches!(err, ToolError::Http(ref m) if m.contains("timed out")),
692            "{err}"
693        );
694    }
695
696    #[test]
697    fn request_debug_hides_header_values() {
698        let mut req = HttpRequest::get("https://example.com/");
699        req.headers
700            .push(("Authorization".into(), "Bearer k-123".into()));
701        let dbg = format!("{req:?}");
702        assert!(
703            dbg.contains("Authorization") && !dbg.contains("k-123"),
704            "{dbg}"
705        );
706    }
707}
708
709#[cfg(test)]
710mod trace_tests {
711    use super::*;
712
713    #[tokio::test]
714    async fn http_tool_span_has_no_headers_or_query() {
715        let http = FakeHttp::new(vec![FakeHttp::reply(200, "text/plain", "hello")]);
716        let sink = std::sync::Arc::new(troupekit_trace::MemorySink::default());
717        let tracer = troupekit_trace::Tracer::builder()
718            .content(true)
719            .sink(sink.clone())
720            .build()
721            .unwrap();
722        let mut req = HttpRequest::get("https://user:pw@api.example.com/v1/x?token=sekrit#frag");
723        req.headers
724            .push(("Authorization".into(), "Bearer sk-hidden".into()));
725        let got = tracer
726            .in_scope(receive(http.as_ref(), req))
727            .await
728            .unwrap();
729        drop(tracer);
730        assert_eq!(got.status, 200);
731        let lines = sink.lines();
732        let start = lines
733            .iter()
734            .find(|l| l.contains("\"t\":\"start\""))
735            .expect("one tool.http span");
736        assert!(start.contains("\"cat\":\"tools\"") && start.contains("\"name\":\"tool.http\""));
737        assert!(start.contains("\"method\":\"GET\""), "{start}");
738        assert!(start.contains("\"url\":\"https://api.example.com\""), "{start}");
739        assert!(start.contains("\"path\":\"/v1/x\""), "{start}");
740        let end = lines.iter().find(|l| l.contains("\"t\":\"end\"")).unwrap();
741        assert!(end.contains("\"status\":200") && end.contains("\"body_bytes\":5"), "{end}");
742        for line in &lines {
743            for needle in ["sekrit", "sk-hidden", "Authorization", "pw@", "frag", "hello"] {
744                assert!(!line.contains(needle), "{needle} in {line}");
745            }
746        }
747    }
748
749    #[tokio::test]
750    async fn http_tool_span_withholds_the_path_without_content() {
751        let token = "123456789:AAH-secret-bot-token";
752        let urls = [
753            format!("https://api.telegram.org/bot{token}/sendMessage"),
754            format!("https://hooks.slack.com/services/T000/B000/{token}"),
755        ];
756        for url in urls {
757            let http = FakeHttp::new(vec![FakeHttp::reply(200, "text/plain", "ok")]);
758            let sink = std::sync::Arc::new(troupekit_trace::MemorySink::default());
759            let tracer = troupekit_trace::Tracer::builder()
760                .sink(sink.clone())
761                .build()
762                .unwrap();
763            tracer
764                .in_scope(receive(http.as_ref(), HttpRequest::get(&url)))
765                .await
766                .unwrap();
767            drop(tracer);
768            let lines = sink.lines();
769            assert!(lines.iter().all(|l| !l.contains("secret-bot")), "{lines:?}");
770            assert!(lines.iter().any(|l| l.contains("\"url\":\"https://")), "{lines:?}");
771        }
772        assert_eq!(split_origin("https://h:1/a/b"), ("https://h:1", "/a/b"));
773        assert_eq!(split_origin("https://h"), ("https://h", ""));
774        assert_eq!(split_origin("/rel/p"), ("", "/rel/p"));
775    }
776
777    #[test]
778    fn split_origin_keeps_relative_paths_out_of_the_origin() {
779        assert_eq!(
780            split_origin("/services//tok-secret"),
781            ("", "/services//tok-secret")
782        );
783        assert_eq!(split_origin("/a/x://tok-secret"), ("", "/a/x://tok-secret"));
784        assert_eq!(
785            split_origin("services/tok-secret"),
786            ("", "services/tok-secret")
787        );
788        assert_eq!(split_origin("tok-secret"), ("", "tok-secret"));
789        assert_eq!(split_origin("//h/p"), ("//h", "/p"));
790        assert_eq!(split_origin("git+ssh://h/p"), ("git+ssh://h", "/p"));
791    }
792
793    #[tokio::test]
794    async fn http_tool_span_withholds_a_relative_path_without_content() {
795        let token = "123456789:AAH-secret-bot-token";
796        let http = FakeHttp::new(vec![FakeHttp::reply(200, "text/plain", "ok")]);
797        let sink = std::sync::Arc::new(troupekit_trace::MemorySink::default());
798        let tracer = troupekit_trace::Tracer::builder()
799            .sink(sink.clone())
800            .build()
801            .unwrap();
802        let url = format!("/services//{token}");
803        tracer
804            .in_scope(receive(http.as_ref(), HttpRequest::get(&url)))
805            .await
806            .unwrap();
807        drop(tracer);
808        let lines = sink.lines();
809        assert!(lines.iter().any(|l| l.contains("tool.http")), "{lines:?}");
810        assert!(lines.iter().all(|l| !l.contains("secret-bot")), "{lines:?}");
811    }
812}