self_update 1.0.0-rc.2

Self updates for standalone executables
Documentation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#![cfg(feature = "reqwest")]

use std::time::Duration;

use reqwest::blocking::Response;

use super::{HeaderMap, HttpClient, HttpResponse};
use crate::Result;

/// Sync [`HttpClient`] backed by a `reqwest::blocking::Client`.
///
/// The default (`ReqwestClient(None)`) builds a fresh per-call client honoring the per-request
/// timeout, the TLS feature, proxy-env, and http2 adaptive window. A `ReqwestClient(Some(client))`
/// (built via `From<reqwest::blocking::Client>`, used by the `reqwest_client` convenience setter)
/// reuses the injected client; the per-request timeout/headers are still layered on, but proxy-env
/// and TLS defer to the injected client.
#[derive(Default)]
pub struct ReqwestClient(Option<reqwest::blocking::Client>);

impl From<reqwest::blocking::Client> for ReqwestClient {
    fn from(client: reqwest::blocking::Client) -> Self {
        Self(Some(client))
    }
}

impl ReqwestClient {
    /// Build a ReqwestClient with custom root CA certificates baked in.
    /// Uses the same TLS backend selection (rustls wins over native-tls) as the per-call path.
    pub(crate) fn build_with_certs(
        certs: &[crate::tls::Certificate],
    ) -> std::result::Result<
        std::sync::Arc<dyn crate::http_client::HttpClient>,
        crate::http_client::ClientBuildError,
    > {
        let mut builder = reqwest::blocking::ClientBuilder::new();
        #[cfg(feature = "rustls")]
        {
            builder = builder.use_rustls_tls();
        }
        #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
        {
            builder = builder.use_native_tls();
        }
        builder = builder.http2_adaptive_window(true);
        // Collect all certs and merge in a single call: `tls_certs_merge` accumulates the passed
        // certs onto the trust store, so one call with the whole set is equivalent to (and clearer
        // than) one call per cert.
        let mut collected = Vec::with_capacity(certs.len());
        for cert in certs {
            let c = if cert.is_pem() {
                reqwest::Certificate::from_pem(cert.bytes())
                    .map_err(|e| format!("invalid PEM certificate: {e}"))?
            } else {
                reqwest::Certificate::from_der(cert.bytes())
                    .map_err(|e| format!("invalid DER certificate: {e}"))?
            };
            collected.push(c);
        }
        builder = builder.tls_certs_merge(collected);
        let client = builder
            .build()
            .map_err(|e| format!("failed to build HTTP client: {e}"))?;
        Ok(std::sync::Arc::new(ReqwestClient::from(client)))
    }
}

impl HttpClient for ReqwestClient {
    fn get(
        &self,
        url: &str,
        headers: &HeaderMap,
        timeout: Option<Duration>,
    ) -> Result<Box<dyn HttpResponse>> {
        let resp = match &self.0 {
            Some(client) => {
                // Injected client: reuse it; layer the per-request timeout + headers on.
                let mut req = client.get(url).headers(headers.clone());
                if let Some(timeout) = timeout {
                    req = req.timeout(timeout);
                }
                req.send()?
            }
            None => {
                let mut client_builder = reqwest::blocking::ClientBuilder::new();
                if let Some(timeout) = timeout {
                    client_builder = client_builder.timeout(timeout);
                }
                // When both TLS features are enabled, rustls wins (it is the crate default).
                #[cfg(feature = "rustls")]
                {
                    client_builder = client_builder.use_rustls_tls();
                }
                #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
                {
                    client_builder = client_builder.use_native_tls();
                }
                let client = client_builder.http2_adaptive_window(true).build()?;
                client.get(url).headers(headers.clone()).send()?
            }
        };

        if !resp.status().is_success() {
            return Err(crate::errors::status_to_error(resp.status().as_u16(), url));
        }
        Ok(Box::new(resp))
    }
}

impl HttpResponse for Response {
    fn headers(&self) -> &HeaderMap<http::HeaderValue> {
        Response::headers(self)
    }

    fn body(self: Box<Self>) -> Box<dyn std::io::Read> {
        self
    }
}

/// Async [`super::AsyncHttpClient`] backed by a `reqwest::Client`. Mirrors [`ReqwestClient`]:
/// `None` builds a fresh per-call client, `Some` reuses an injected one.
#[cfg(feature = "async")]
#[derive(Default)]
pub struct ReqwestAsyncClient(Option<reqwest::Client>);

#[cfg(feature = "async")]
impl From<reqwest::Client> for ReqwestAsyncClient {
    fn from(client: reqwest::Client) -> Self {
        Self(Some(client))
    }
}

#[cfg(feature = "async")]
impl ReqwestAsyncClient {
    /// Async sibling of [`ReqwestClient::build_with_certs`]: build a `ReqwestAsyncClient` with
    /// custom root CA certificates baked in, using `reqwest::ClientBuilder` (async) and the same
    /// TLS backend selection.
    pub(crate) fn build_async_with_certs(
        certs: &[crate::tls::Certificate],
    ) -> std::result::Result<
        std::sync::Arc<dyn crate::http_client::AsyncHttpClient>,
        crate::http_client::ClientBuildError,
    > {
        let mut builder = reqwest::ClientBuilder::new();
        #[cfg(feature = "rustls")]
        {
            builder = builder.use_rustls_tls();
        }
        #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
        {
            builder = builder.use_native_tls();
        }
        builder = builder.http2_adaptive_window(true);
        let mut collected = Vec::with_capacity(certs.len());
        for cert in certs {
            let c = if cert.is_pem() {
                reqwest::Certificate::from_pem(cert.bytes())
                    .map_err(|e| format!("invalid PEM certificate: {e}"))?
            } else {
                reqwest::Certificate::from_der(cert.bytes())
                    .map_err(|e| format!("invalid DER certificate: {e}"))?
            };
            collected.push(c);
        }
        builder = builder.tls_certs_merge(collected);
        let client = builder
            .build()
            .map_err(|e| format!("failed to build HTTP client: {e}"))?;
        Ok(std::sync::Arc::new(ReqwestAsyncClient::from(client)))
    }
}

#[cfg(feature = "async")]
impl super::AsyncHttpClient for ReqwestAsyncClient {
    fn get<'a>(
        &'a self,
        url: &'a str,
        headers: &'a HeaderMap,
        timeout: Option<Duration>,
    ) -> futures_util::future::BoxFuture<'a, Result<Box<dyn super::AsyncHttpResponse>>> {
        Box::pin(async move {
            let resp = match &self.0 {
                Some(client) => {
                    let mut req = client.get(url).headers(headers.clone());
                    if let Some(timeout) = timeout {
                        req = req.timeout(timeout);
                    }
                    req.send().await?
                }
                None => {
                    let mut client_builder = reqwest::ClientBuilder::new();
                    if let Some(timeout) = timeout {
                        client_builder = client_builder.timeout(timeout);
                    }
                    #[cfg(feature = "rustls")]
                    {
                        client_builder = client_builder.use_rustls_tls();
                    }
                    #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
                    {
                        client_builder = client_builder.use_native_tls();
                    }
                    let client = client_builder.http2_adaptive_window(true).build()?;
                    client.get(url).headers(headers.clone()).send().await?
                }
            };
            if !resp.status().is_success() {
                return Err(crate::errors::status_to_error(resp.status().as_u16(), url));
            }
            Ok(Box::new(resp) as Box<dyn super::AsyncHttpResponse>)
        })
    }
}

#[cfg(feature = "async")]
impl super::AsyncHttpResponse for reqwest::Response {
    fn headers(&self) -> &HeaderMap<http::HeaderValue> {
        reqwest::Response::headers(self)
    }

    fn text(self: Box<Self>) -> futures_util::future::BoxFuture<'static, Result<String>> {
        Box::pin(async move { Ok((*self).text().await?) })
    }

    fn bytes_stream(
        self: Box<Self>,
    ) -> futures_util::stream::BoxStream<'static, Result<bytes::Bytes>> {
        use futures_util::StreamExt;
        Box::pin((*self).bytes_stream().map(|chunk| Ok(chunk?)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Error;
    use std::io::{Read as _, Write as _};
    use std::net::TcpListener;

    /// Serve a single HTTP response (the given status line + a short body) over a fresh loopback
    /// listener, then close. Returns the base URL (`http://127.0.0.1:<port>/`). No external network.
    fn stub(status: &'static str) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}/", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let body = "err";
                let out = format!(
                    "HTTP/1.1 {}\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    status,
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        base
    }

    /// Serve a single `200 OK` response with the given `body` (a known content type), then close.
    /// Returns the base URL. Used by the async JSON-mapping test below.
    #[cfg(feature = "async")]
    fn stub_ok(body: &'static str, content_type: &'static str) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}/", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let out = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    content_type,
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        base
    }

    /// A PEM block carrying a CERTIFICATE marker but a body that decodes to bytes which are not a
    /// valid X.509 DER certificate. reqwest's TLS backend accepts the PEM framing but rejects this
    /// at client-build time, exercising the deferred-validation path (the `from_*` constructors are
    /// infallible). `bm90IGEgdmFsaWQgY2VydA==` is base64 for "not a valid cert".
    const BAD_PEM: &[u8] =
        b"-----BEGIN CERTIFICATE-----\nbm90IGEgdmFsaWQgY2VydA==\n-----END CERTIFICATE-----\n";

    #[test]
    fn build_with_certs_rejects_garbage_pem() {
        // A PEM-framed but non-certificate body must surface a config-time `Err` from
        // `build_with_certs` (the parse is deferred to here from the infallible
        // `Certificate::from_pem` constructor) rather than panicking or building a usable client.
        let res =
            ReqwestClient::build_with_certs(&[crate::tls::Certificate::from_pem(BAD_PEM.to_vec())]);
        assert!(
            res.is_err(),
            "garbage PEM must be rejected at build time, got Ok"
        );
    }

    #[test]
    fn build_with_certs_rejects_garbage_der() {
        // Same as the PEM case for the DER decoder: invalid DER bytes must produce an `Err`.
        let res = ReqwestClient::build_with_certs(&[crate::tls::Certificate::from_der(
            b"not der".to_vec(),
        )]);
        assert!(
            res.is_err(),
            "garbage DER must be rejected at build time, got Ok"
        );
    }

    /// Sync `get` (through the trait) against the loopback stub serving `status`; returns the mapped
    /// error.
    fn get_status(status: &'static str) -> Error {
        let client = ReqwestClient::default();
        let base = stub(status);
        client
            .get(&base, &HeaderMap::new(), None)
            .err()
            .expect("non-2xx must be an Err")
    }

    #[test]
    fn sync_get_maps_each_status_to_its_structured_variant() {
        // `HttpClient::get` runs `status_to_error` on any non-2xx before returning. Pin the full
        // mapping table so a regression in the per-call client path (not just `status_to_error` in
        // isolation) is caught: 404 -> NotFound, 401/403 -> Unauthorized, 400/500/503 -> HttpStatus.
        let err = get_status("404 Not Found");
        assert!(
            matches!(err, Error::NotFound { .. }),
            "404 -> NotFound, got {:?}",
            err
        );
        assert_eq!(err.http_status(), Some(404));

        assert!(matches!(
            get_status("401 Unauthorized"),
            Error::Unauthorized { status: 401, .. }
        ));
        assert!(matches!(
            get_status("403 Forbidden"),
            Error::Unauthorized { status: 403, .. }
        ));
        assert!(matches!(
            get_status("400 Bad Request"),
            Error::HttpStatus { status: 400, .. }
        ));
        assert!(matches!(
            get_status("500 Internal Server Error"),
            Error::HttpStatus { status: 500, .. }
        ));
        assert!(matches!(
            get_status("503 Service Unavailable"),
            Error::HttpStatus { status: 503, .. }
        ));
    }

    #[test]
    fn sync_get_transport_failure_maps_to_transport() {
        // A connection refused (no listener) cannot complete, so `From<reqwest::Error>` routes the
        // failure to `Error::Transport` (via the `?` on `send()`), never a status variant.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);
        let url = format!("http://{}/", addr);
        let client = ReqwestClient::default();
        let err = client
            .get(&url, &HeaderMap::new(), None)
            .err()
            .expect("connection refused must be an Err");
        assert!(
            matches!(err, Error::Transport(_)),
            "uncompleted request must map to Error::Transport, got {:?}",
            err
        );
        assert_eq!(err.http_status(), None);
    }

    /// Async `get` (through the trait) against the loopback stub serving `status`; returns the
    /// mapped error.
    #[cfg(feature = "async")]
    async fn get_async_status(status: &'static str) -> Error {
        use super::super::AsyncHttpClient;
        let client = ReqwestAsyncClient::default();
        let base = stub(status);
        client
            .get(&base, &HeaderMap::new(), None)
            .await
            .err()
            .expect("non-2xx must be an Err")
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_get_maps_each_status_to_its_structured_variant() {
        // The async client shares the same `status_to_error` mapping as the sync path. Pin it
        // independently so the async lane cannot drift from the sync lane.
        let err = get_async_status("404 Not Found").await;
        assert!(
            matches!(err, Error::NotFound { .. }),
            "404 -> NotFound (async), got {:?}",
            err
        );
        assert_eq!(err.http_status(), Some(404));

        assert!(matches!(
            get_async_status("401 Unauthorized").await,
            Error::Unauthorized { status: 401, .. }
        ));
        assert!(matches!(
            get_async_status("403 Forbidden").await,
            Error::Unauthorized { status: 403, .. }
        ));
        assert!(matches!(
            get_async_status("500 Internal Server Error").await,
            Error::HttpStatus { status: 500, .. }
        ));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_get_transport_failure_maps_to_transport() {
        use super::super::AsyncHttpClient;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);
        let url = format!("http://{}/", addr);
        let client = ReqwestAsyncClient::default();
        let err = client
            .get(&url, &HeaderMap::new(), None)
            .await
            .err()
            .expect("connection refused must be an Err");
        assert!(
            matches!(err, Error::Transport(_)),
            "uncompleted async request must map to Error::Transport, got {:?}",
            err
        );
        assert_eq!(err.http_status(), None);
    }

    /// The async response trait dropped reqwest's `.json()` in favor of `text().await? ->
    /// serde_json::from_str`. A malformed body must therefore surface as `Error::Json` (via the
    /// `From<serde_json::Error>` conversion the backends rely on), not as a transport error or a
    /// panic. This pins the async JSON error mapping end-to-end: drive a real `ReqwestAsyncClient`
    /// against a 200 serving invalid JSON, read it through the trait's `text()`, and parse exactly
    /// as the async backends do.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_text_then_from_str_maps_malformed_json_to_error_json() {
        use super::super::AsyncHttpClient;
        let client = ReqwestAsyncClient::default();
        let base = stub_ok("{not valid json", "application/json");
        let resp = client
            .get(&base, &HeaderMap::new(), None)
            .await
            .expect("200 must be Ok");
        // Exactly the async backend pattern: `text().await?` then `serde_json::from_str`.
        let body = resp.text().await.expect("text() reads the body");
        let parsed: Result<serde_json::Value> =
            serde_json::from_str::<serde_json::Value>(&body).map_err(Into::into);
        let err = parsed.expect_err("malformed JSON must be an Err");
        assert!(
            matches!(err, Error::Json(_)),
            "malformed async JSON must map to Error::Json, got {:?}",
            err
        );
    }

    /// The async seam (`AsyncHttpClient`/`AsyncHttpResponse`) must stay object-safe just like the
    /// sync seam — an injected client is carried as `Arc<dyn AsyncHttpClient>`, so any leaked generic
    /// method would break these `Box<dyn ...>` coercions at compile time.
    #[cfg(feature = "async")]
    #[test]
    fn async_traits_are_object_safe() {
        let _client: Box<dyn super::super::AsyncHttpClient> =
            Box::new(ReqwestAsyncClient::default());
        let _arc: std::sync::Arc<dyn super::super::AsyncHttpClient> =
            std::sync::Arc::new(ReqwestAsyncClient::default());
    }
}