croft-software 0.2.182

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Outbound HTTP setup shared by every ureq 2 request croft makes (#872):
//! which proxy a request goes through and which certificate authorities it
//! trusts, decided in one place so a download works wherever curl does.
//!
//! ureq on its own trusts only the Mozilla roots compiled into the binary and
//! ignores `HTTPS_PROXY`. Behind a TLS-inspecting gateway (Zscaler, Netskope
//! and the like) every certificate is re-signed by a CA that only the
//! platform store knows, so each download failed with "UnknownIssuer" while
//! curl, pip and cargo on the same machine worked.

use std::net::IpAddr;
use std::sync::{Arc, OnceLock};

use rustls::pki_types::CertificateDer;

/// An agent builder for a request to `url`: through the proxy the environment
/// names for its scheme unless `no_proxy` exempts the host, and trusting the
/// platform CA store (or `SSL_CERT_FILE` / `SSL_CERT_DIR` when set) on top of
/// the Mozilla roots. Callers add their own timeouts and redirect policy.
pub fn builder(url: &str) -> ureq::AgentBuilder {
    let builder = ureq::AgentBuilder::new().tls_config(tls_config());
    let env = |key: &str| std::env::var(key).ok().filter(|v| !v.trim().is_empty());
    match proxy_for(url, &env).and_then(|p| ureq::Proxy::new(p).ok()) {
        Some(proxy) => builder.proxy(proxy),
        None => builder,
    }
}

/// A GET of `url` on a [`builder`] agent with ureq's default timeouts.
pub fn get(url: &str) -> ureq::Request {
    builder(url).build().get(url)
}

/// A response body of at most `max` bytes, refused when it is longer rather
/// than cut short at the cap: a truncated archive or binary that is then
/// unpacked or run is worse than a failed download. A body over the cap is
/// an `io::ErrorKind::FileTooLarge` error naming the limit.
pub fn read_capped(reader: impl std::io::Read, max: u64) -> std::io::Result<Vec<u8>> {
    use std::io::Read;
    let mut bytes = Vec::new();
    reader.take(max.saturating_add(1)).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > max {
        return Err(std::io::Error::new(
            std::io::ErrorKind::FileTooLarge,
            format!("the download is larger than its {} limit", size_label(max)),
        ));
    }
    Ok(bytes)
}

/// `max` in whole MiB when it is a whole number of them, else in bytes.
fn size_label(max: u64) -> String {
    const MIB: u64 = 1024 * 1024;
    if max >= MIB && max.is_multiple_of(MIB) {
        format!("{} MiB", max / MIB)
    } else {
        format!("{max} bytes")
    }
}

/// Why a request failed, short enough for a status line: the HTTP status, or
/// the transport failure and its cause (DNS, refused, timeout, TLS), without
/// the URL ureq's own message opens with. A certificate nothing in the trust
/// store vouches for gets a pointer at the usual reason.
pub fn describe(err: &ureq::Error) -> String {
    let t = match err {
        ureq::Error::Status(code, _) => return format!("HTTP {code}"),
        ureq::Error::Transport(t) => t,
    };
    let mut why = t.kind().to_string();
    if let Some(message) = t.message() {
        why.push_str(&format!(": {message}"));
    }
    let source = std::error::Error::source(t);
    if let Some(source) = source {
        why.push_str(&format!(": {source}"));
    }
    let bad_cert = source
        .and_then(|e| e.downcast_ref::<std::io::Error>())
        .and_then(|e| e.get_ref())
        .and_then(|e| e.downcast_ref::<rustls::Error>())
        .is_some_and(|e| matches!(e, rustls::Error::InvalidCertificate(_)));
    if bad_cert {
        why.push_str(
            " (behind a TLS-inspecting proxy? add its CA to the system store or SSL_CERT_FILE)",
        );
    }
    why
}

/// The client TLS config every request shares, built on first use.
fn tls_config() -> Arc<rustls::ClientConfig> {
    static CONFIG: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
    let config = CONFIG.get_or_init(|| {
        let native = rustls_native_certs::load_native_certs();
        for e in &native.errors {
            crate::lsp::log_file::log(&format!("net: reading the platform CA store: {e}"));
        }
        client_config(native.certs)
    });
    Arc::clone(config)
}

/// A client config trusting the Mozilla roots plus `platform`, the certificates
/// the OS store holds. The Mozilla roots stay so a machine whose store is
/// empty or unreadable still connects as it did before.
fn client_config(platform: Vec<CertificateDer<'static>>) -> Arc<rustls::ClientConfig> {
    let provider = Arc::new(rustls::crypto::ring::default_provider());
    Arc::new(
        rustls::ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("ring supports TLS 1.2 and 1.3")
            .with_root_certificates(root_store(platform))
            .with_no_client_auth(),
    )
}

/// The Mozilla roots plus `platform`, the roots [`client_config`] trusts.
fn root_store(platform: Vec<CertificateDer<'static>>) -> rustls::RootCertStore {
    let mut roots = rustls::RootCertStore {
        roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
    };
    roots.add_parsable_certificates(platform);
    roots
}

/// The proxy for `url`, read from `env` as curl reads it: `https_proxy` for
/// https and `http_proxy` for http (either case), then `all_proxy`. `None`
/// when none is set, and for a host `no_proxy` exempts.
fn proxy_for(url: &str, env: &dyn Fn(&str) -> Option<String>) -> Option<String> {
    let url = url::Url::parse(url).ok()?;
    let keys = match url.scheme() {
        "https" => ["https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"],
        "http" => ["http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"],
        _ => return None,
    };
    let proxy = keys.iter().find_map(|k| env(k))?;
    let no_proxy = env("no_proxy")
        .or_else(|| env("NO_PROXY"))
        .unwrap_or_default();
    (!bypasses(&url.host()?, &no_proxy)).then_some(proxy)
}

/// Whether `host` skips the proxy: loopback always (no proxy can reach it on
/// the user's behalf), otherwise when a `no_proxy` entry covers it: `*`, the
/// host or a parent domain (with or without a leading `.` or `*.`), an IP, or
/// a CIDR range holding it. Names are not resolved, as in curl.
fn bypasses(host: &url::Host<&str>, no_proxy: &str) -> bool {
    let (name, ip): (&str, Option<IpAddr>) = match *host {
        url::Host::Domain(d) => (d, None),
        url::Host::Ipv4(a) => ("", Some(a.into())),
        url::Host::Ipv6(a) => ("", Some(a.into())),
    };
    if name == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) {
        return true;
    }
    let entries = no_proxy
        .split(',')
        .map(|e| e.trim().trim_matches(['[', ']']));
    entries.filter(|e| !e.is_empty()).any(|entry| {
        if entry == "*" {
            return true;
        }
        match (ip, entry.split_once('/')) {
            (Some(ip), Some((net, bits))) => in_cidr(ip, net, bits),
            (Some(ip), None) => entry.parse::<IpAddr>().is_ok_and(|e| e == ip),
            (None, _) => {
                let domain = entry.trim_start_matches('*').trim_start_matches('.');
                let domain = domain.to_ascii_lowercase();
                let sub = |p: &str| p.ends_with('.');
                !domain.is_empty()
                    && (name == domain || name.strip_suffix(&*domain).is_some_and(sub))
            }
        }
    })
}

/// Whether `ip` lies in the range `net`/`bits`.
fn in_cidr(ip: IpAddr, net: &str, bits: &str) -> bool {
    let (Ok(net), Ok(bits)) = (net.parse::<IpAddr>(), bits.parse::<u32>()) else {
        return false;
    };
    match (ip, net) {
        (IpAddr::V4(a), IpAddr::V4(n)) if bits <= 32 => {
            let mask = u32::MAX.checked_shl(32 - bits).unwrap_or(0);
            u32::from(a) & mask == u32::from(n) & mask
        }
        (IpAddr::V6(a), IpAddr::V6(n)) if bits <= 128 => {
            let mask = u128::MAX.checked_shl(128 - bits).unwrap_or(0);
            u128::from(a) & mask == u128::from(n) & mask
        }
        _ => false,
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::path::Path;

    /// The self-signed `localhost` certificate `croft web --tls` tests with.
    fn test_cert() -> Vec<CertificateDer<'static>> {
        use rustls::pki_types::pem::PemObject;
        let pem = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/web/testdata/cert.pem");
        CertificateDer::pem_file_iter(pem)
            .unwrap()
            .map(Result::unwrap)
            .collect()
    }

    /// An HTTPS server on loopback whose certificate only [`test_cert`]
    /// vouches for, standing in for a TLS-inspecting proxy whose CA is in
    /// the platform store but not among the Mozilla roots. Answers every
    /// request with `ok`; returns its base URL.
    pub(crate) fn https_server() -> String {
        let here = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/web/testdata");
        let config = crate::web::tls::load(&here.join("cert.pem"), &here.join("key.pem")).unwrap();
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            for tcp in listener.incoming().flatten() {
                let Ok(mut plain) = crate::web::tls::terminate(tcp, Arc::clone(&config)) else {
                    continue;
                };
                std::thread::spawn(move || {
                    let mut head = Vec::new();
                    let mut b = [0u8; 1];
                    while !head.ends_with(b"\r\n\r\n") && plain.read(&mut b).unwrap_or(0) == 1 {
                        head.push(b[0]);
                    }
                    let reply =
                        "HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok";
                    let _ = plain.write_all(reply.as_bytes());
                });
            }
        });
        format!("https://127.0.0.1:{port}/")
    }

    #[test]
    fn a_ca_from_the_platform_store_is_trusted_alongside_the_mozilla_roots() {
        let url = https_server();
        let with_platform = ureq::AgentBuilder::new().tls_config(client_config(test_cert()));
        let body = with_platform
            .build()
            .get(&url)
            .call()
            .unwrap()
            .into_string();
        assert_eq!(body.unwrap(), "ok");
        // The Mozilla roots alone (ureq's own default) cannot place it, and
        // the reason names the certificate rather than vanishing.
        let without = ureq::AgentBuilder::new().tls_config(client_config(Vec::new()));
        let err = without.build().get(&url).call().unwrap_err();
        let why = describe(&err);
        assert!(why.contains("UnknownIssuer"), "{why}");
        assert!(why.contains("SSL_CERT_FILE"), "{why}");
        assert!(!why.contains("127.0.0.1"), "no URL in the reason: {why}");
    }

    /// A PEM file from `src/net/testdata`: the chains the eMudhra test hosts
    /// served (leaf first, captured 20 October 2026), and the two roots those
    /// chains end at, which macOS's store still carries (#1912).
    fn testdata(name: &str) -> Vec<CertificateDer<'static>> {
        use rustls::pki_types::pem::PemObject;
        let pem = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src/net/testdata")
            .join(name);
        CertificateDer::pem_file_iter(pem)
            .unwrap()
            .map(Result::unwrap)
            .collect()
    }

    /// Verify `host`'s chain against [`root_store`] at a time inside every
    /// fixture leaf's validity, so only trust decides the outcome.
    fn verify(platform: Vec<CertificateDer<'static>>, host: &str) -> Result<(), rustls::Error> {
        use rustls::client::danger::ServerCertVerifier;
        use rustls::pki_types::{ServerName, UnixTime};
        let chain = testdata(&format!("{host}.pem"));
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
            Arc::new(root_store(platform)),
            provider,
        )
        .build()
        .unwrap();
        let now = UnixTime::since_unix_epoch(std::time::Duration::from_secs(1_792_800_000));
        let name = ServerName::try_from(host.to_string()).unwrap();
        verifier
            .verify_server_cert(&chain[0], &chain[1..], &name, &[], now)
            .map(|_| ())
    }

    #[test]
    fn a_compromised_emudhra_chain_is_refused_though_the_platform_trusts_its_root() {
        // One chain through emSign ECC Root CA - G3, one through the Sectigo
        // cross-sign under AAA Certificate Services.
        for host in [
            "dv-g3b-emudhra.we-have-a-problem.com",
            "dv-g3b-aaa-emudhra.we-have-a-problem.com",
        ] {
            let refused = verify(testdata("emudhra-roots.pem"), host);
            assert!(
                matches!(refused, Err(rustls::Error::InvalidCertificate(_))),
                "{host}: {refused:?}"
            );
        }
        // The same store and clock still accept an ordinary chain.
        verify(
            testdata("emudhra-roots.pem"),
            "emudhra.we-have-a-problem.com",
        )
        .unwrap();
    }

    #[test]
    fn the_mozilla_roots_no_longer_carry_the_distrusted_emsign_roots() {
        let subjects: Vec<String> = root_store(Vec::new())
            .roots
            .iter()
            .map(|anchor| String::from_utf8_lossy(anchor.subject.as_ref()).into_owned())
            .collect();
        for gone in [
            "emSign ECC Root CA - G3",
            "emSign ECC Root CA - C3",
            "emSign Root CA - C1",
        ] {
            assert!(!subjects.iter().any(|s| s.contains(gone)), "{gone}");
        }
        // A kept eMudhra root, so the match above can see these names at all.
        assert!(subjects.iter().any(|s| s.contains("emSign Root CA - G1")));
    }

    #[test]
    fn the_proxy_follows_the_scheme_and_no_proxy() {
        let env = |pairs: &'static [(&'static str, &'static str)]| {
            move |k: &str| pairs.iter().find(|p| p.0 == k).map(|p| p.1.to_string())
        };
        const NO_PROXY: &str = "internal.corp, .lan,*.svc.local,10.0.0.0/8,192.168.1.7,[fd00::1]";
        let corp = env(&[
            ("HTTPS_PROXY", "http://gw:8080"),
            ("http_proxy", "http://plain:3128"),
            ("NO_PROXY", NO_PROXY),
        ]);
        let proxy = |url: &str| proxy_for(url, &corp).unwrap_or_default();
        assert_eq!(proxy("https://github.com/x"), "http://gw:8080");
        assert_eq!(proxy("http://example.com/"), "http://plain:3128");
        for exempt in [
            "https://internal.corp/",
            "https://git.internal.corp/",
            "https://nas.lan/",
            "https://api.svc.local/",
            "https://10.20.30.40/",
            "https://192.168.1.7:8443/",
            "https://[fd00::1]/",
            "http://localhost:3000/",
            "http://127.0.0.1:8080/",
            "http://[::1]/",
        ] {
            assert_eq!(proxy(exempt), "", "{exempt}");
        }
        // A suffix or a range only matches on its boundary.
        for outside in [
            "https://notinternal.corp/",
            "https://192.168.1.8/",
            "https://11.0.0.1/",
        ] {
            assert_eq!(proxy(outside), "http://gw:8080", "{outside}");
        }
        // all_proxy is the fallback, `*` exempts every host, and with nothing
        // set there is no proxy.
        let all = env(&[("ALL_PROXY", "http://all:1")]);
        assert_eq!(
            proxy_for("https://a.b/", &all).as_deref(),
            Some("http://all:1")
        );
        let star = env(&[("https_proxy", "http://gw:1"), ("no_proxy", "*")]);
        assert_eq!(proxy_for("https://a.b/", &star), None);
        assert_eq!(proxy_for("https://a.b/", &env(&[])), None);
    }

    /// A body at the cap is read whole; one byte over is refused, never cut
    /// short to the cap and handed on as if it were the whole download.
    #[test]
    fn a_body_over_the_cap_is_refused_not_truncated() {
        let at_cap = read_capped(&[7u8; 16][..], 16).unwrap();
        assert_eq!(at_cap, vec![7u8; 16]);
        assert_eq!(read_capped(&[][..], 16).unwrap(), Vec::<u8>::new());

        let over = read_capped(&[7u8; 17][..], 16).unwrap_err();
        assert_eq!(over.kind(), std::io::ErrorKind::FileTooLarge);
        assert_eq!(
            over.to_string(),
            "the download is larger than its 16 bytes limit"
        );
        let mib = 1024 * 1024;
        let over = read_capped(std::io::repeat(0).take(mib + 1), mib).unwrap_err();
        assert_eq!(
            over.to_string(),
            "the download is larger than its 1 MiB limit"
        );
    }
}