Skip to main content

surjection_core/catalog/
http.rs

1//! HTTP for catalogs (#26): `GET` only, behind [`Http`] so tests use a
2//! local stub or recorded fixtures. [`UreqHttp`] is `ureq` with rustls and
3//! the platform's certificate verifier (no OpenSSL, SPEC 4), gzip, a
4//! connect and an overall timeout, a body cap, and proxies from the
5//! injected [`Env`] (never the process environment): `HTTPS_PROXY` (then
6//! `ALL_PROXY`) for `https://`, `HTTP_PROXY` (then `ALL_PROXY`) for a
7//! loopback `http://` registry. A SOCKS proxy or one that does not parse
8//! is an error, never a direct connection. Every hop of an `https://`
9//! request is `https://`: a redirect to plain http is refused before it
10//! is sent; a loopback `http://` registry is not redirected at all.
11
12use std::time::{Duration, Instant};
13
14use ureq::tls::{RootCerts, TlsConfig};
15
16use crate::diagnostics::log;
17use crate::env::Env;
18use crate::error::{CoreError, ErrorCode};
19
20/// A response: the status, the body (gzip already decoded) and the
21/// address that answered (after redirects), when the transport knows it.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct HttpResponse {
24    pub status: u16,
25    pub body: Vec<u8>,
26    pub url: Option<String>,
27}
28
29/// The one request catalogs make. Errors are `catalog_unreachable`.
30pub trait Http: Send + Sync {
31    fn get(&self, url: &str) -> Result<HttpResponse, CoreError>;
32}
33
34/// Per-request limits.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct HttpLimits {
37    pub connect: Duration,
38    /// The whole request, body included.
39    pub total: Duration,
40    pub max_bytes: u64,
41}
42
43impl Default for HttpLimits {
44    fn default() -> Self {
45        Self {
46            connect: Duration::from_secs(10),
47            total: Duration::from_secs(20),
48            max_bytes: 8 * 1024 * 1024,
49        }
50    }
51}
52
53/// [`Http`] over `ureq`.
54pub struct UreqHttp {
55    /// `https://` requests: https on every hop.
56    https: ureq::Agent,
57    /// Loopback `http://` registries: no redirects.
58    loopback: ureq::Agent,
59    /// Why the proxy settings cannot be used, per scheme: every request of
60    /// that scheme fails with it (never a direct connection).
61    https_problem: Option<String>,
62    loopback_problem: Option<String>,
63    max_bytes: u64,
64}
65
66impl std::fmt::Debug for UreqHttp {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("UreqHttp").finish_non_exhaustive()
69    }
70}
71
72/// The first of `names` set (non-empty) in `env`, with its name.
73fn var(env: &Env, names: &[&'static str]) -> Option<(&'static str, String)> {
74    names.iter().find_map(|name| {
75        env.var(name)
76            .map(|value| value.to_string_lossy().trim().to_owned())
77            .filter(|value| !value.is_empty())
78            .map(|value| (*name, value))
79    })
80}
81
82/// The proxy the first set of `names` gives, with the `NO_PROXY` hosts;
83/// `Err` (the reason) for a SOCKS proxy (ureq is built without SOCKS) or
84/// a value that does not parse.
85pub(crate) fn proxy(env: &Env, names: &[&'static str]) -> Result<Option<ureq::Proxy>, String> {
86    let Some((name, url)) = var(env, names) else {
87        return Ok(None);
88    };
89    let unusable = || format!("the proxy in {name} is not a usable proxy address");
90    let parsed = ureq::Proxy::new(&url).map_err(|_| unusable())?;
91    if !matches!(
92        parsed.protocol(),
93        ureq::ProxyProtocol::Http | ureq::ProxyProtocol::Https
94    ) {
95        return Err(format!(
96            "the proxy in {name} is a SOCKS proxy, which Surjection does not support; set it to an \
97             HTTP proxy (http://host:port)"
98        ));
99    }
100    let mut builder = ureq::Proxy::builder(parsed.protocol())
101        .host(parsed.host())
102        .port(parsed.port());
103    if let Some(user) = parsed.username() {
104        builder = builder.username(user);
105    }
106    if let Some(password) = parsed.password() {
107        builder = builder.password(password);
108    }
109    if let Some((_, list)) = var(env, &["NO_PROXY", "no_proxy"]) {
110        for expr in list.split(',').map(str::trim).filter(|e| !e.is_empty()) {
111            builder = builder.no_proxy(expr);
112        }
113    }
114    builder.build().map(Some).map_err(|_| unusable())
115}
116
117impl UreqHttp {
118    pub fn new(env: &Env, limits: HttpLimits) -> Self {
119        let agent = |proxy: Option<ureq::Proxy>, https_only: bool, redirects: u32| {
120            ureq::Agent::config_builder()
121                .http_status_as_error(false)
122                .timeout_connect(Some(limits.connect))
123                .timeout_global(Some(limits.total))
124                .https_only(https_only)
125                .max_redirects(redirects)
126                .user_agent(format!("Surjection/{}", env!("CARGO_PKG_VERSION")))
127                .proxy(proxy)
128                .tls_config(
129                    TlsConfig::builder()
130                        .root_certs(RootCerts::PlatformVerifier)
131                        .build(),
132                )
133                .build()
134                .new_agent()
135        };
136        let https = proxy(
137            env,
138            &["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"],
139        );
140        let loopback = proxy(env, &["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"]);
141        let (https_proxy, https_problem) = match https {
142            Ok(proxy) => (proxy, None),
143            Err(why) => (None, Some(why)),
144        };
145        let (loopback_proxy, loopback_problem) = match loopback {
146            Ok(proxy) => (proxy, None),
147            Err(why) => (None, Some(why)),
148        };
149        Self {
150            https: agent(https_proxy, true, 3),
151            loopback: agent(loopback_proxy, false, 0),
152            https_problem,
153            loopback_problem,
154            max_bytes: limits.max_bytes,
155        }
156    }
157
158    /// The agent for `url`: the https-only one unless it is `http://`
159    /// (registry URLs allow that for loopback hosts only).
160    fn agent_for(&self, url: &str) -> &ureq::Agent {
161        if url.starts_with("http://") {
162            &self.loopback
163        } else {
164            &self.https
165        }
166    }
167
168    fn problem_for(&self, url: &str) -> Option<&str> {
169        if url.starts_with("http://") {
170            self.loopback_problem.as_deref()
171        } else {
172            self.https_problem.as_deref()
173        }
174    }
175}
176
177/// `catalog_unreachable` about `url`.
178pub(crate) fn unreachable(url: &str, why: impl std::fmt::Display) -> CoreError {
179    CoreError::new(
180        ErrorCode::CatalogUnreachable,
181        format!("{} could not be reached: {why}", host_of(url)),
182    )
183}
184
185/// The host (with a port) of `url`, for messages.
186pub(crate) fn host_of(url: &str) -> String {
187    url::Url::parse(url)
188        .ok()
189        .and_then(|parsed| {
190            let host = parsed.host_str()?.to_owned();
191            Some(match parsed.port() {
192                Some(port) => format!("{host}:{port}"),
193                None => host,
194            })
195        })
196        .unwrap_or_else(|| "the catalog".to_owned())
197}
198
199impl Http for UreqHttp {
200    /// [`UreqHttp::call`], logged with the host only (SPEC 4.5).
201    fn get(&self, url: &str) -> Result<HttpResponse, CoreError> {
202        let started = Instant::now();
203        let result = self.call(url);
204        log::http(
205            "catalog",
206            url,
207            result.as_ref().map(|response| response.status),
208            started,
209        );
210        result
211    }
212}
213
214impl UreqHttp {
215    fn call(&self, url: &str) -> Result<HttpResponse, CoreError> {
216        if let Some(why) = self.problem_for(url) {
217            return Err(unreachable(url, why));
218        }
219        let response = self
220            .agent_for(url)
221            .get(url)
222            .header("Accept", "application/json")
223            .call()
224            .map_err(|err| match err {
225                ureq::Error::Timeout(_) => unreachable(url, "it did not answer in time"),
226                ureq::Error::HostNotFound => unreachable(url, "the host was not found"),
227                ureq::Error::ConnectionFailed => unreachable(url, "the connection failed"),
228                ureq::Error::TooManyRedirects => unreachable(url, "too many redirects"),
229                ureq::Error::RequireHttpsOnly(_) => {
230                    unreachable(url, "it redirected to an address without encryption")
231                }
232                other => unreachable(url, other),
233            })?;
234        let status = response.status().as_u16();
235        let answered = ureq::ResponseExt::get_uri(&response).to_string();
236        let body = response
237            .into_body()
238            .with_config()
239            .limit(self.max_bytes)
240            .read_to_vec()
241            .map_err(|err| match err {
242                ureq::Error::BodyExceedsLimit(_) => unreachable(url, "the answer is too large"),
243                ureq::Error::Timeout(_) => unreachable(url, "it did not answer in time"),
244                other => unreachable(url, other),
245            })?;
246        Ok(HttpResponse {
247            status,
248            body,
249            url: Some(answered),
250        })
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    //! The transport itself against local stubs: proxies, redirects, the
257    //! body cap after decompression and the overall timeout. No network.
258
259    use std::io::{Read, Write};
260    use std::net::TcpListener;
261    use std::sync::atomic::{AtomicUsize, Ordering};
262    use std::sync::{Arc, Mutex};
263    use std::time::{Duration, Instant};
264
265    use super::*;
266    use crate::env::Os;
267
268    /// A one-route HTTP stub: every request gets `answer(first line)`, written
269    /// in `chunks` with `pause` between them; requests are counted.
270    struct Stub {
271        url: String,
272        hits: Arc<AtomicUsize>,
273        lines: Arc<Mutex<Vec<String>>>,
274    }
275
276    impl Stub {
277        fn start(
278            answer: impl Fn(&str) -> Vec<Vec<u8>> + Send + Sync + 'static,
279            pause: Duration,
280        ) -> Self {
281            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
282            let url = format!("http://{}", listener.local_addr().unwrap());
283            let hits = Arc::new(AtomicUsize::new(0));
284            let lines = Arc::new(Mutex::new(Vec::new()));
285            let answer = Arc::new(answer);
286            let (thread_hits, thread_lines) = (hits.clone(), lines.clone());
287            std::thread::spawn(move || {
288                for stream in listener.incoming() {
289                    let Ok(mut stream) = stream else { continue };
290                    let (hits, lines, answer) =
291                        (thread_hits.clone(), thread_lines.clone(), answer.clone());
292                    std::thread::spawn(move || {
293                        let mut request = Vec::new();
294                        let mut buf = [0u8; 1024];
295                        while !request.windows(4).any(|w| w == b"\r\n\r\n") {
296                            match stream.read(&mut buf) {
297                                Ok(0) | Err(_) => return,
298                                Ok(n) => request.extend_from_slice(&buf[..n]),
299                            }
300                        }
301                        let text = String::from_utf8_lossy(&request);
302                        let line = text.lines().next().unwrap_or_default().to_owned();
303                        hits.fetch_add(1, Ordering::SeqCst);
304                        lines.lock().unwrap().push(line.clone());
305                        for chunk in answer(&line) {
306                            if stream.write_all(&chunk).is_err() {
307                                return;
308                            }
309                            let _ = stream.flush();
310                            std::thread::sleep(pause);
311                        }
312                    });
313                }
314            });
315            Self { url, hits, lines }
316        }
317
318        fn json(body: &'static str) -> Self {
319            Self::start(
320                move |_| {
321                    vec![format!(
322                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
323                        body.len()
324                    )
325                    .into_bytes()]
326                },
327                Duration::ZERO,
328            )
329        }
330
331        fn hits(&self) -> usize {
332            self.hits.load(Ordering::SeqCst)
333        }
334
335        fn host_port(&self) -> &str {
336            self.url.trim_start_matches("http://")
337        }
338    }
339
340    fn env(vars: &[(&str, &str)]) -> Env {
341        let mut builder = Env::builder(Os::Linux, "/home/me");
342        for (name, value) in vars {
343            builder = builder.var(name, *value);
344        }
345        builder.build()
346    }
347
348    fn limits() -> HttpLimits {
349        HttpLimits {
350            connect: Duration::from_secs(2),
351            total: Duration::from_secs(2),
352            max_bytes: 1024,
353        }
354    }
355
356    /// The request, run so a panic is a failure of its own.
357    fn get(http: &UreqHttp, url: &str) -> Result<HttpResponse, CoreError> {
358        let url = url.to_owned();
359        std::thread::scope(|scope| {
360            scope
361                .spawn(|| http.get(&url))
362                .join()
363                .unwrap_or_else(|_| panic!("the request panicked"))
364        })
365    }
366
367    #[test]
368    fn a_socks_proxy_is_refused_without_connecting_or_going_direct() {
369        let target = Stub::json("{}");
370        let proxy = Stub::json("{}");
371        let loopback = format!("{}/v0.1/servers", target.url);
372        for (name, url) in [
373            ("ALL_PROXY", loopback.as_str()),
374            ("ALL_PROXY", "https://registry.example.invalid/v0.1/servers"),
375            (
376                "HTTPS_PROXY",
377                "https://registry.example.invalid/v0.1/servers",
378            ),
379            ("HTTP_PROXY", loopback.as_str()),
380        ] {
381            let value = format!("socks5://{}", proxy.host_port());
382            let http = UreqHttp::new(&env(&[(name, value.as_str())]), limits());
383            let err = get(&http, url).unwrap_err();
384            assert_eq!(err.code(), ErrorCode::CatalogUnreachable, "{name}");
385            assert!(err.message().contains("SOCKS"), "{name}: {err}");
386        }
387        assert_eq!(target.hits(), 0, "never direct");
388        assert_eq!(proxy.hits(), 0, "never through the SOCKS proxy");
389    }
390
391    #[test]
392    fn a_proxy_that_does_not_parse_is_an_error_not_a_direct_connection() {
393        let target = Stub::json("{}");
394        let http = UreqHttp::new(&env(&[("HTTP_PROXY", "http://[not a host")]), limits());
395        let err = get(&http, &format!("{}/v0.1/servers", target.url)).unwrap_err();
396        assert_eq!(err.code(), ErrorCode::CatalogUnreachable);
397        assert!(err.message().contains("proxy"), "{err}");
398        assert_eq!(target.hits(), 0);
399    }
400
401    #[test]
402    fn https_proxy_wins_over_all_proxy_for_https() {
403        // The HTTPS proxy is a stub: it sees the CONNECT and answers 502.
404        let proxy = Stub::start(
405            |_| vec![b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n".to_vec()],
406            Duration::ZERO,
407        );
408        let https = format!("http://{}", proxy.host_port());
409        let http = UreqHttp::new(
410            &env(&[
411                ("ALL_PROXY", "socks5://127.0.0.1:9"),
412                ("https_proxy", https.as_str()),
413            ]),
414            limits(),
415        );
416        let err = get(&http, "https://registry.example.invalid/v0.1/servers").unwrap_err();
417        assert_eq!(err.code(), ErrorCode::CatalogUnreachable);
418        assert_eq!(proxy.hits(), 1, "{err}");
419        assert!(
420            proxy.lines.lock().unwrap()[0].starts_with("CONNECT registry.example.invalid:443"),
421            "{:?}",
422            proxy.lines.lock().unwrap()
423        );
424    }
425
426    #[test]
427    fn no_proxy_hosts_go_direct() {
428        let target = Stub::json("{}");
429        let http = UreqHttp::new(
430            &env(&[
431                ("HTTP_PROXY", "http://127.0.0.1:9"),
432                ("NO_PROXY", "127.0.0.1"),
433            ]),
434            limits(),
435        );
436        assert_eq!(
437            get(&http, &format!("{}/x", target.url)).unwrap().status,
438            200
439        );
440        assert_eq!(target.hits(), 1);
441    }
442
443    #[test]
444    fn an_https_request_never_sends_a_plain_http_hop() {
445        // What a redirect from https to http would ask for: refused before
446        // anything is sent, on every hop.
447        let target = Stub::json("{}");
448        let http = UreqHttp::new(&env(&[]), limits());
449        let err = http
450            .agent_for("https://registry.example")
451            .get(&format!("{}/latest/meta-data", target.url))
452            .call()
453            .unwrap_err();
454        assert!(matches!(err, ureq::Error::RequireHttpsOnly(_)), "{err}");
455        assert_eq!(target.hits(), 0);
456    }
457
458    #[test]
459    fn a_loopback_registry_does_not_follow_redirects() {
460        let elsewhere = Stub::json("{}");
461        let location = format!(
462            "{}/v0.1/servers",
463            elsewhere.url.replace("127.0.0.1", "localhost")
464        );
465        let registry = Stub::start(
466            move |_| {
467                vec![format!(
468                    "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
469                )
470                .into_bytes()]
471            },
472            Duration::ZERO,
473        );
474        let http = UreqHttp::new(&env(&[]), limits());
475        let result = get(&http, &format!("{}/v0.1/servers", registry.url));
476        assert!(
477            result.as_ref().is_err() || result.as_ref().unwrap().status == 302,
478            "{result:?}"
479        );
480        assert_eq!(elsewhere.hits(), 0);
481    }
482
483    #[test]
484    fn a_gzip_body_over_the_cap_is_refused_after_decompression() {
485        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
486        gz.write_all(&vec![b' '; 64 * 1024]).unwrap();
487        let body = gz.finish().unwrap();
488        assert!(body.len() < 1024, "the compressed body is under the cap");
489        let stub = Stub::start(
490            move |_| {
491                let mut answer = format!(
492                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Encoding: gzip\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
493                    body.len()
494                )
495                .into_bytes();
496                answer.extend_from_slice(&body);
497                vec![answer]
498            },
499            Duration::ZERO,
500        );
501        let http = UreqHttp::new(&env(&[]), limits());
502        let err = get(&http, &format!("{}/x", stub.url)).unwrap_err();
503        assert!(err.message().contains("too large"), "{err}");
504    }
505
506    #[test]
507    fn a_slow_body_stops_at_the_total_timeout() {
508        let stub = Stub::start(
509            |_| {
510                let mut chunks = vec![
511                    b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n"
512                        .to_vec(),
513                ];
514                chunks.extend((0..100).map(|_| b" ".to_vec()));
515                chunks
516            },
517            Duration::from_millis(100),
518        );
519        let http = UreqHttp::new(&env(&[]), limits());
520        let started = Instant::now();
521        let err = get(&http, &format!("{}/x", stub.url)).unwrap_err();
522        assert_eq!(err.code(), ErrorCode::CatalogUnreachable);
523        assert!(
524            started.elapsed() < Duration::from_secs(5),
525            "{:?}",
526            started.elapsed()
527        );
528    }
529}