Skip to main content

eclipse_core/
http.rs

1//! The one place an unauthenticated HTTP `GET` leaves this process.
2//!
3//! Model calls have their own client in `provider`; everything else that reads a URL goes
4//! through [`get`]: the `fetch` tool, and the update notice (`update`). Having one function
5//! means one SSRF policy, one rule about redirects, and one thing to read when asking "what
6//! does this tool send to the network?".
7
8use crate::netguard;
9use std::time::Duration;
10
11/// Which hosts a request may reach.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Reach {
14    /// Public hosts only: no IP literals, no `localhost`, every resolved address public.
15    /// For anything a *model* can choose, which is what makes an internal address a hazard.
16    Public,
17    /// Any host. For a URL the *user* wrote into their own config: pointing the update
18    /// notice at a mirror on the LAN is their call, not a model's.
19    Anywhere,
20}
21
22/// Send one `GET` and return the response head and body reader. Redirects are not followed:
23/// whoever approved or configured this URL did not approve its redirect target.
24///
25/// Errors are plain sentences naming the host or the cause.
26pub async fn get(
27    url: &reqwest::Url,
28    timeout: Duration,
29    reach: Reach,
30    headers: &[(&str, &str)],
31) -> Result<reqwest::Response, String> {
32    if !matches!(url.scheme(), "http" | "https") {
33        return Err("only http(s) URLs are allowed".into());
34    }
35    let mut builder = reqwest::Client::builder()
36        .timeout(timeout)
37        .redirect(reqwest::redirect::Policy::none());
38    if reach == Reach::Public {
39        // The vetted addresses are pinned so a second, different DNS answer cannot swap an
40        // internal address in after the check.
41        let host = netguard::check_url_host(url)?;
42        let port = url.port_or_known_default().unwrap_or(80);
43        let addrs = netguard::resolve_public(&host, port, timeout).await?;
44        builder = builder.resolve_to_addrs(&host, &addrs);
45        // A resolver override is keyed by the host reqwest is about to look up, which is the
46        // string in the URL — and `check_url_host` trims a trailing dot, so `example.com.` was
47        // vetted under one name and pinned under another. Pin both (`#422`).
48        if let Some(named) = url.host_str() {
49            if named != host {
50                builder = builder.resolve_to_addrs(named, &addrs);
51            }
52        }
53        // A proxy decides where the bytes go; vetting a name locally says nothing about it.
54        builder = builder.no_proxy();
55    }
56    let client = builder.build().map_err(|e| e.to_string())?;
57    let mut request = client.get(url.clone());
58    for (name, value) in headers {
59        request = request.header(*name, *value);
60    }
61    request.send().await.map_err(|e| e.to_string())
62}
63
64/// Stream one `GET` into a file, refusing anything over `cap` bytes.
65///
66/// This is the only request here that follows redirects, and the reason is narrow: a release
67/// asset URL on GitHub answers `302` to a signed CDN address by design, so refusing the hop
68/// would refuse every download. What vouches for the bytes is not the host that served them —
69/// it is the SHA256 the release published, checked after this returns.
70pub async fn download(
71    raw: &str,
72    timeout: Duration,
73    cap: u64,
74    path: &std::path::Path,
75) -> Result<u64, String> {
76    use tokio::io::AsyncWriteExt;
77    let url = reqwest::Url::parse(raw).map_err(|e| format!("{raw:?}: {e}"))?;
78    if !matches!(url.scheme(), "http" | "https") {
79        return Err("only http(s) URLs are allowed".into());
80    }
81    let client = reqwest::Client::builder()
82        .timeout(timeout)
83        .redirect(reqwest::redirect::Policy::limited(5))
84        .build()
85        .map_err(|e| e.to_string())?;
86    let user_agent = format!("eclipse/{}", env!("CARGO_PKG_VERSION"));
87    let mut resp = client
88        .get(url.clone())
89        .header("User-Agent", user_agent)
90        .send()
91        .await
92        .map_err(|e| e.to_string())?;
93    if !resp.status().is_success() {
94        return Err(format!("{url} answered {}", resp.status()));
95    }
96    let mut file = tokio::fs::File::create(path)
97        .await
98        .map_err(|e| format!("{}: {e}", path.display()))?;
99    let mut written = 0u64;
100    while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
101        written += chunk.len() as u64;
102        if written > cap {
103            return Err(format!(
104                "{url} sent more than the {cap} bytes a release can weigh"
105            ));
106        }
107        file.write_all(&chunk)
108            .await
109            .map_err(|e| format!("{}: {e}", path.display()))?;
110    }
111    file.flush()
112        .await
113        .map_err(|e| format!("{}: {e}", path.display()))?;
114    Ok(written)
115}