wreq-rb 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +47 -21
  3. data/README.md +36 -0
  4. data/ext/wreq_rb/Cargo.toml +4 -4
  5. data/ext/wreq_rb/extconf.rb +10 -3
  6. data/ext/wreq_rb/src/client.rs +41 -0
  7. data/lib/wreq-rb/version.rb +1 -1
  8. data/patches/0002-add-preconnect.patch +266 -0
  9. data/vendor/wreq/Cargo.toml +11 -7
  10. data/vendor/wreq/bench/support/server.rs +2 -0
  11. data/vendor/wreq/src/client/layer/redirect/future.rs +1 -1
  12. data/vendor/wreq/src/client/layer/timeout/body.rs +16 -18
  13. data/vendor/wreq/src/client/layer/timeout/future.rs +2 -2
  14. data/vendor/wreq/src/client/request.rs +27 -15
  15. data/vendor/wreq/src/client/ws.rs +4 -3
  16. data/vendor/wreq/src/client.rs +4 -24
  17. data/vendor/wreq/src/conn/net/tcp.rs +16 -66
  18. data/vendor/wreq/src/conn/proxy/socks.rs +11 -1
  19. data/vendor/wreq/src/conn/proxy/tunnel.rs +14 -11
  20. data/vendor/wreq/src/conn/timeout.rs +1 -1
  21. data/vendor/wreq/src/cookie/jar.rs +170 -36
  22. data/vendor/wreq/src/cookie/store.rs +66 -4
  23. data/vendor/wreq/src/cookie.rs +48 -17
  24. data/vendor/wreq/src/dns.rs +2 -4
  25. data/vendor/wreq/src/error.rs +100 -0
  26. data/vendor/wreq/src/ext.rs +0 -49
  27. data/vendor/wreq/src/lib.rs +2 -0
  28. data/vendor/wreq/src/rt.rs +1 -14
  29. data/vendor/wreq/src/tls/trust/store.rs +35 -2
  30. data/vendor/wreq/tests/badssl.rs +3 -239
  31. data/vendor/wreq/tests/cert_store.rs +168 -0
  32. data/vendor/wreq/tests/client.rs +89 -0
  33. data/vendor/wreq/tests/proxy.rs +149 -3
  34. data/vendor/wreq/tests/redirect.rs +35 -0
  35. data/vendor/wreq/tests/support/tls_cert.rs +56 -0
  36. data/vendor/wreq/tests/timeouts.rs +25 -0
  37. data/vendor/wreq/tests/unix_socket.rs +109 -81
  38. data/vendor/wreq/tests/websocket.rs +40 -0
  39. metadata +9 -6
  40. data/vendor/wreq/examples/rt.rs +0 -23
@@ -245,11 +245,52 @@ impl Error {
245
245
  false
246
246
  }
247
247
 
248
+ /// Returns `true` for a 407 response to HTTP CONNECT or a SOCKS5 authentication error.
249
+ ///
250
+ /// With the `socks` feature, the SOCKS5 cases are missing required credentials, rejected
251
+ /// credentials, and negotiation with no acceptable authentication method.
252
+ /// A forwarding proxy's 407 is available through [`Response::status`](crate::Response::status).
253
+ pub fn is_proxy_auth(&self) -> bool {
254
+ #[cfg(feature = "socks")]
255
+ use crate::conn::proxy::socks::SocksError;
256
+ use crate::conn::proxy::tunnel::TunnelError;
257
+
258
+ let mut source = self.source();
259
+
260
+ while let Some(err) = source {
261
+ if let Some(TunnelError::ProxyAuthRequired) = err.downcast_ref::<TunnelError>() {
262
+ return true;
263
+ }
264
+
265
+ #[cfg(feature = "socks")]
266
+ if let Some(SocksError::Socks(
267
+ tokio_socks::Error::PasswordAuthFailure(_)
268
+ | tokio_socks::Error::AuthorizationRequired
269
+ | tokio_socks::Error::NoAcceptableAuthMethods,
270
+ )) = err.downcast_ref::<SocksError>()
271
+ {
272
+ return true;
273
+ }
274
+
275
+ source = err.source();
276
+ }
277
+
278
+ false
279
+ }
280
+
248
281
  /// Returns true if the error is related to a connection reset.
282
+ ///
283
+ /// Resets during SOCKS proxy setup are reported by [`Self::is_proxy_connect`] instead.
284
+ /// The underlying I/O error remains available through the source chain.
249
285
  pub fn is_connection_reset(&self) -> bool {
250
286
  let mut source = self.source();
251
287
 
252
288
  while let Some(err) = source {
289
+ #[cfg(feature = "socks")]
290
+ if err.is::<crate::conn::proxy::socks::SocksError>() {
291
+ return false;
292
+ }
293
+
253
294
  if let Some(io) = err.downcast_ref::<io::Error>()
254
295
  && io.kind() == io::ErrorKind::ConnectionReset
255
296
  {
@@ -546,6 +587,65 @@ mod tests {
546
587
  assert!(nested.is_timeout());
547
588
  }
548
589
 
590
+ #[test]
591
+ fn is_proxy_auth() {
592
+ use crate::conn::proxy::tunnel::TunnelError;
593
+
594
+ let err = Error::request(ProxyConnect(Box::new(TunnelError::ProxyAuthRequired)));
595
+ assert!(err.is_proxy_auth());
596
+
597
+ let err = Error::request(ProxyConnect(Box::new(TunnelError::TunnelUnsuccessful(
598
+ Some(503),
599
+ ))));
600
+ assert!(!err.is_proxy_auth());
601
+ }
602
+
603
+ #[cfg(feature = "socks")]
604
+ #[test]
605
+ fn is_proxy_auth_socks() {
606
+ use crate::conn::proxy::socks::SocksError;
607
+
608
+ let err = Error::request(ProxyConnect(Box::new(SocksError::Socks(
609
+ tokio_socks::Error::PasswordAuthFailure(1),
610
+ ))));
611
+ assert!(err.is_proxy_auth());
612
+
613
+ let err = Error::request(ProxyConnect(Box::new(SocksError::Socks(
614
+ tokio_socks::Error::AuthorizationRequired,
615
+ ))));
616
+ assert!(err.is_proxy_auth());
617
+
618
+ let err = Error::request(ProxyConnect(Box::new(SocksError::Socks(
619
+ tokio_socks::Error::NoAcceptableAuthMethods,
620
+ ))));
621
+ assert!(err.is_proxy_auth());
622
+
623
+ let err = Error::request(ProxyConnect(Box::new(SocksError::MissingHost)));
624
+ assert!(!err.is_proxy_auth());
625
+ }
626
+
627
+ #[cfg(feature = "socks")]
628
+ #[test]
629
+ fn socks_connect_failure_exposes_its_io_error() {
630
+ use crate::conn::proxy::socks::SocksError;
631
+
632
+ let refused = io::Error::from(io::ErrorKind::ConnectionRefused);
633
+ let err = Error::request(ProxyConnect(Box::new(SocksError::ConnectFailed(Box::new(
634
+ refused,
635
+ )))));
636
+
637
+ let mut source = err.source();
638
+ let mut kind = None;
639
+ while let Some(inner) = source {
640
+ if let Some(io) = inner.downcast_ref::<io::Error>() {
641
+ kind = Some(io.kind());
642
+ }
643
+ source = inner.source();
644
+ }
645
+
646
+ assert_eq!(kind, Some(io::ErrorKind::ConnectionRefused));
647
+ }
648
+
549
649
  #[test]
550
650
  fn is_connection_reset() {
551
651
  let err = Error::request(io::Error::new(
@@ -82,10 +82,6 @@ pub(crate) trait UriExt {
82
82
  /// Returns the port of the URI, or the default port for the scheme if none is specified.
83
83
  fn port_or_default(&self) -> u16;
84
84
 
85
- /// Sets the query component of the URI, replacing any existing query.
86
- #[cfg(feature = "query")]
87
- fn set_query(&mut self, query: String);
88
-
89
85
  /// Returns the username and password from the URI's userinfo, if present.
90
86
  fn userinfo(&self) -> (Option<&str>, Option<&str>);
91
87
 
@@ -130,32 +126,6 @@ impl UriExt for Uri {
130
126
  }
131
127
  }
132
128
 
133
- #[cfg(feature = "query")]
134
- fn set_query(&mut self, query: String) {
135
- use http::uri::PathAndQuery;
136
-
137
- if query.is_empty() {
138
- return;
139
- }
140
-
141
- let path = self.path();
142
- let parts = match PathAndQuery::from_maybe_shared(Bytes::from(format!("{path}?{query}"))) {
143
- Ok(path_and_query) => {
144
- let mut parts = self.clone().into_parts();
145
- parts.path_and_query.replace(path_and_query);
146
- parts
147
- }
148
- Err(_err) => {
149
- debug!("Failed to set query in URI: {_err}");
150
- return;
151
- }
152
- };
153
-
154
- if let Ok(uri) = Uri::from_parts(parts) {
155
- *self = uri;
156
- }
157
- }
158
-
159
129
  fn userinfo(&self) -> (Option<&str>, Option<&str>) {
160
130
  self.authority()
161
131
  .and_then(|auth| auth.as_str().rsplit_once('@'))
@@ -378,25 +348,6 @@ mod tests {
378
348
  assert_eq!(uri.to_string(), "http://:p%40ss%20word@example.com/");
379
349
  }
380
350
 
381
- #[cfg(feature = "query")]
382
- #[test]
383
- fn test_set_query() {
384
- let mut uri: Uri = "http://example.com/path".parse().unwrap();
385
- uri.set_query("key=value&foo=bar".to_string());
386
-
387
- assert_eq!(uri.to_string(), "http://example.com/path?key=value&foo=bar");
388
-
389
- let mut uri: Uri = "http://example.com/path?existing=param".parse().unwrap();
390
- uri.set_query("newkey=newvalue".to_string());
391
-
392
- assert_eq!(uri.to_string(), "http://example.com/path?newkey=newvalue");
393
-
394
- let mut uri: Uri = "http://example.com/path".parse().unwrap();
395
- uri.set_query("".to_string());
396
-
397
- assert_eq!(uri.to_string(), "http://example.com/path");
398
- }
399
-
400
351
  #[test]
401
352
  fn test_response_builder_ext() {
402
353
  let uri = Uri::try_from("http://example.com").unwrap();
@@ -222,6 +222,8 @@
222
222
  //! enabled or disabled:
223
223
  //!
224
224
  //! - **cookies**: Provides cookie session support.
225
+ //! - **cookies-psl**: Enables `cookies` and restricts cookie `Domain` attributes using the Public
226
+ //! Suffix List. If the suffix is the request host, the cookie is stored as host-only.
225
227
  //! - **gzip**: Provides response body gzip decompression.
226
228
  //! - **brotli**: Provides response body brotli decompression.
227
229
  //! - **zstd**: Provides response body zstd decompression.
@@ -57,20 +57,6 @@ pub struct Executor(Arc<dyn rt::Executor<BoxSendFuture> + Send + Sync>);
57
57
 
58
58
  // ===== impl Executor =====
59
59
 
60
- impl Executor {
61
- /// Creates an [`Executor`] backed by a custom implementation.
62
- ///
63
- /// The value is wrapped in an [`Arc`] and type-erased, so the resulting
64
- /// handle is cheap to clone and safe to share across threads.
65
- #[inline]
66
- pub fn new<E>(exec: E) -> Self
67
- where
68
- E: rt::Executor<BoxSendFuture> + Send + Sync + 'static,
69
- {
70
- Executor(Arc::new(exec))
71
- }
72
- }
73
-
74
60
  impl<Fut> rt::Executor<Fut> for Executor
75
61
  where
76
62
  Fut: Future<Output = ()> + Send + 'static,
@@ -139,6 +125,7 @@ pub struct Timer(Time);
139
125
 
140
126
  impl Timer {
141
127
  /// Creates a [`Timer`] backed by a custom implementation.
128
+ #[cfg(test)]
142
129
  #[inline]
143
130
  pub fn new<M>(timer: M) -> Self
144
131
  where
@@ -1,6 +1,9 @@
1
- use std::sync::Arc;
1
+ use std::{net::IpAddr, sync::Arc};
2
2
 
3
- use btls::x509::store::{X509Store, X509StoreBuilder};
3
+ use btls::x509::{
4
+ store::{X509Store, X509StoreBuilder},
5
+ verify::X509CheckFlags,
6
+ };
4
7
 
5
8
  use super::{
6
9
  Certificate, CertificateInput,
@@ -114,6 +117,36 @@ impl CertStoreBuilder {
114
117
  self
115
118
  }
116
119
 
120
+ /// Requires peer certificates to be issued for `host`, a DNS name or IP address.
121
+ ///
122
+ /// The check runs during chain verification and does not depend on the request URI, so a
123
+ /// server dialed by IP address can be verified against the DNS name in its certificate.
124
+ /// The subject common name is never used as a fallback.
125
+ ///
126
+ /// Use it with [`ClientBuilder::tls_verify_hostname(false)`]. Otherwise the URI host is checked
127
+ /// as well: a host of the same kind replaces this requirement, and one of the other kind must
128
+ /// match too. The requirement applies to every client built with this store.
129
+ ///
130
+ /// [`ClientBuilder::tls_verify_hostname(false)`]: crate::ClientBuilder::tls_verify_hostname
131
+ pub fn verify_host<H>(mut self, host: H) -> Self
132
+ where
133
+ H: AsRef<str>,
134
+ {
135
+ if let Ok(ref mut builder) = self.builder {
136
+ let host = host.as_ref();
137
+ let param = builder.verify_param_mut();
138
+ param.set_hostflags(X509CheckFlags::NEVER_CHECK_SUBJECT);
139
+ let result = match host.parse::<IpAddr>() {
140
+ Ok(ip) => param.set_ip(ip),
141
+ Err(_) => param.set_host(host),
142
+ };
143
+ if let Err(err) = result {
144
+ self.builder = Err(Error::tls(err));
145
+ }
146
+ }
147
+ self
148
+ }
149
+
117
150
  /// Constructs the [`CertStore`].
118
151
  ///
119
152
  /// This method finalizes the builder and constructs the [`CertStore`]
@@ -1,8 +1,8 @@
1
- use std::{error::Error as StdError, io, time::Duration};
1
+ use std::time::Duration;
2
2
 
3
3
  use wreq::{
4
- Client, retry,
5
- tls::{AlpsProtocol, TlsInfo, TlsOptions, TlsVersion, trust::CertStore},
4
+ Client,
5
+ tls::{TlsOptions, TlsVersion},
6
6
  };
7
7
 
8
8
  macro_rules! join {
@@ -11,197 +11,6 @@ macro_rules! join {
11
11
  };
12
12
  }
13
13
 
14
- fn badssl_connection_reset_retry_policy() -> retry::Policy {
15
- retry::Policy::default()
16
- .max_retries_per_request(10)
17
- .no_budget()
18
- .classify_fn(|req_rep| {
19
- if req_rep.error().is_some_and(is_connection_reset) {
20
- req_rep.retryable()
21
- } else {
22
- req_rep.success()
23
- }
24
- })
25
- }
26
-
27
- fn is_connection_reset(err: &(dyn StdError + 'static)) -> bool {
28
- let mut source = Some(err);
29
-
30
- while let Some(err) = source {
31
- if let Some(io) = err.downcast_ref::<io::Error>()
32
- && io.kind() == io::ErrorKind::ConnectionReset
33
- {
34
- return true;
35
- }
36
-
37
- source = err.source();
38
- }
39
-
40
- false
41
- }
42
-
43
- #[tokio::test]
44
- async fn test_badssl_modern() {
45
- let text = Client::builder()
46
- .no_proxy()
47
- .retry(badssl_connection_reset_retry_policy())
48
- .build()
49
- .unwrap()
50
- .get("https://mozilla-modern.badssl.com/")
51
- .send()
52
- .await
53
- .unwrap()
54
- .text()
55
- .await
56
- .unwrap();
57
-
58
- assert!(text.contains("<title>mozilla-modern.badssl.com</title>"));
59
- }
60
-
61
- #[tokio::test]
62
- async fn test_badssl_self_signed() {
63
- let text = Client::builder()
64
- .tls_cert_verification(false)
65
- .no_proxy()
66
- .retry(badssl_connection_reset_retry_policy())
67
- .build()
68
- .unwrap()
69
- .get("https://self-signed.badssl.com/")
70
- .send()
71
- .await
72
- .unwrap()
73
- .text()
74
- .await
75
- .unwrap();
76
-
77
- assert!(text.contains("<title>self-signed.badssl.com</title>"));
78
- }
79
-
80
- #[tokio::test]
81
- async fn test_badssl_wrong_host() {
82
- let text = Client::builder()
83
- .tls_verify_hostname(false)
84
- .no_proxy()
85
- .retry(badssl_connection_reset_retry_policy())
86
- .build()
87
- .unwrap()
88
- .get("https://wrong.host.badssl.com/")
89
- .send()
90
- .await
91
- .unwrap()
92
- .text()
93
- .await
94
- .unwrap();
95
-
96
- assert!(text.contains("<title>wrong.host.badssl.com</title>"));
97
-
98
- let result = Client::builder()
99
- .tls_verify_hostname(false)
100
- .no_proxy()
101
- .build()
102
- .unwrap()
103
- .get("https://self-signed.badssl.com/")
104
- .send()
105
- .await;
106
-
107
- assert!(result.is_err());
108
- }
109
-
110
- const CURVES_LIST: &str = join!(
111
- ":",
112
- "X25519",
113
- "P-256",
114
- "P-384",
115
- "P-521",
116
- "ffdhe2048",
117
- "ffdhe3072"
118
- );
119
-
120
- #[tokio::test]
121
- async fn test_3des_support() -> wreq::Result<()> {
122
- let tls_options = TlsOptions::builder()
123
- .cipher_list(join!(
124
- ":",
125
- "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
126
- "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"
127
- ))
128
- .curves_list(CURVES_LIST)
129
- .build();
130
-
131
- // Create a client with the TLS options
132
- let client = Client::builder()
133
- .tls_options(tls_options)
134
- .tls_cert_verification(false)
135
- .retry(badssl_connection_reset_retry_policy())
136
- .connect_timeout(Duration::from_secs(360))
137
- .build()?;
138
-
139
- // Check if the client can connect to the 3des.badssl.com
140
- let content = client
141
- .get("https://3des.badssl.com/")
142
- .send()
143
- .await?
144
- .text()
145
- .await?;
146
-
147
- println!("3des.badssl.com is supported:\n{content}");
148
-
149
- Ok(())
150
- }
151
-
152
- #[tokio::test]
153
- async fn test_firefox_7x_100_cipher() -> wreq::Result<()> {
154
- let tls_options = TlsOptions::builder()
155
- .cipher_list(join!(
156
- ":",
157
- "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
158
- "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
159
- "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
160
- "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"
161
- ))
162
- .curves_list(CURVES_LIST)
163
- .build();
164
-
165
- // Create a client with the TLS options
166
- let client = Client::builder()
167
- .tls_options(tls_options)
168
- .tls_cert_verification(false)
169
- .retry(badssl_connection_reset_retry_policy())
170
- .connect_timeout(Duration::from_secs(360))
171
- .build()?;
172
-
173
- // Check if the client can connect to the dh2048.badssl.com
174
- let content = client
175
- .get("https://dh2048.badssl.com/")
176
- .send()
177
- .await?
178
- .text()
179
- .await?;
180
-
181
- println!("dh2048.badssl.com is supported:\n{content}");
182
-
183
- Ok(())
184
- }
185
-
186
- #[tokio::test]
187
- async fn test_alps_new_endpoint() -> wreq::Result<()> {
188
- let tls_options = TlsOptions::builder()
189
- .min_tls_version(TlsVersion::TLS_1_2)
190
- .max_tls_version(TlsVersion::TLS_1_3)
191
- .alps_protocols([AlpsProtocol::HTTP2])
192
- .alps_use_new_codepoint(true)
193
- .build();
194
-
195
- let client = Client::builder()
196
- .tls_options(tls_options)
197
- .connect_timeout(Duration::from_secs(360))
198
- .build()?;
199
-
200
- let resp = client.get("https://www.google.com").send().await?;
201
- assert!(resp.status().is_success());
202
- Ok(())
203
- }
204
-
205
14
  #[tokio::test]
206
15
  async fn test_aes_hw_override() -> wreq::Result<()> {
207
16
  const CIPHER_LIST: &str = join!(
@@ -246,48 +55,3 @@ async fn test_aes_hw_override() -> wreq::Result<()> {
246
55
  assert!(text.contains("ChaCha20Poly1305"));
247
56
  Ok(())
248
57
  }
249
-
250
- #[tokio::test]
251
- async fn test_tls_self_signed_cert() {
252
- let client = Client::builder()
253
- .tls_cert_verification(false)
254
- .tls_info(true)
255
- .retry(badssl_connection_reset_retry_policy())
256
- .no_proxy()
257
- .build()
258
- .unwrap();
259
-
260
- let resp = client
261
- .get("https://self-signed.badssl.com/")
262
- .send()
263
- .await
264
- .unwrap();
265
-
266
- let peer_cert_der = resp
267
- .extensions()
268
- .get::<TlsInfo>()
269
- .and_then(|info| info.peer_certificate())
270
- .unwrap();
271
-
272
- let self_signed_cert_store = CertStore::builder()
273
- .add_der_cert(peer_cert_der)
274
- .build()
275
- .unwrap();
276
-
277
- let client = Client::builder()
278
- .tls_cert_store(self_signed_cert_store)
279
- .retry(badssl_connection_reset_retry_policy())
280
- .no_proxy()
281
- .build()
282
- .unwrap();
283
-
284
- let resp = client
285
- .get("https://self-signed.badssl.com/")
286
- .send()
287
- .await
288
- .unwrap();
289
- assert!(resp.status().is_success());
290
-
291
- let res = client.get("https://www.google.com").send().await;
292
- assert!(res.is_err());
293
- }
@@ -0,0 +1,168 @@
1
+ #[path = "support/tls_cert.rs"]
2
+ mod tls_cert;
3
+
4
+ use std::{net::SocketAddr, pin::Pin};
5
+
6
+ use btls::{
7
+ pkey::{PKey, Private},
8
+ ssl::Ssl,
9
+ x509::X509,
10
+ };
11
+ use tokio::{
12
+ io::{AsyncReadExt, AsyncWriteExt},
13
+ net::TcpListener,
14
+ };
15
+ use wreq::{Client, tls::trust::CertStore};
16
+
17
+ async fn serve(cert: &X509, key: &PKey<Private>) -> SocketAddr {
18
+ let acceptor = tls_cert::acceptor(cert, key);
19
+
20
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
21
+ start_tls_server(listener, acceptor)
22
+ }
23
+
24
+ fn start_tls_server(listener: TcpListener, acceptor: btls::ssl::SslAcceptor) -> SocketAddr {
25
+ let addr = listener.local_addr().unwrap();
26
+ tokio::spawn(async move {
27
+ while let Ok((tcp, _)) = listener.accept().await {
28
+ let ssl = Ssl::new(acceptor.context()).unwrap();
29
+ let mut stream = tokio_btls::SslStream::new(ssl, tcp).unwrap();
30
+ tokio::spawn(async move {
31
+ if Pin::new(&mut stream).accept().await.is_ok() {
32
+ let mut buf = [0; 1024];
33
+ let _ = stream.read(&mut buf).await;
34
+ let _ = stream
35
+ .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n")
36
+ .await;
37
+ }
38
+ });
39
+ }
40
+ });
41
+ addr
42
+ }
43
+
44
+ #[tokio::test]
45
+ async fn verify_host_overrides_uri_host() {
46
+ let (cert, key) = tls_cert::self_signed("wreq.test", [192, 0, 2, 1].into());
47
+ let der = cert.to_der().unwrap();
48
+ let url = format!("https://{}/", serve(&cert, &key).await);
49
+
50
+ let get = |host: &'static str| {
51
+ let store = CertStore::builder()
52
+ .add_der_cert(&der)
53
+ .verify_host(host)
54
+ .build()
55
+ .unwrap();
56
+ let client = Client::builder()
57
+ .tls_cert_store(store)
58
+ .tls_verify_hostname(false)
59
+ .no_proxy()
60
+ .build()
61
+ .unwrap();
62
+ client.get(&url).send()
63
+ };
64
+
65
+ // The URI names 127.0.0.1, which the certificate does not cover.
66
+ assert!(get("wreq.test").await.unwrap().status().is_success());
67
+ assert!(get("192.0.2.1").await.unwrap().status().is_success());
68
+ assert!(get("other.test").await.is_err());
69
+ }
70
+
71
+ async fn send(builder: wreq::ClientBuilder, url: &str) -> wreq::Result<wreq::Response> {
72
+ builder.no_proxy().build().unwrap().get(url).send().await
73
+ }
74
+
75
+ fn assert_verification_failure(result: wreq::Result<wreq::Response>) {
76
+ let error = result.unwrap_err();
77
+ assert!(
78
+ format!("{error:?}").contains("CERTIFICATE_VERIFY_FAILED"),
79
+ "{error:?}"
80
+ );
81
+ }
82
+
83
+ #[tokio::test]
84
+ async fn ca_issued_certificate_verifies_over_tls13() {
85
+ use btls::ssl::{SslAcceptor, SslMethod, SslVersion};
86
+
87
+ // Issued by LOCALHOST_CA for localhost and 127.0.0.1.
88
+ const LOCALHOST_CERT: &[u8] = include_bytes!("support/localhost.cert");
89
+ const LOCALHOST_KEY: &[u8] = include_bytes!("support/localhost.key");
90
+ const LOCALHOST_CA: &[u8] = include_bytes!("support/localhost-ca.cert");
91
+
92
+ let cert = X509::from_der(LOCALHOST_CERT).unwrap();
93
+ let key = PKey::private_key_from_der(LOCALHOST_KEY).unwrap();
94
+ let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
95
+ acceptor.set_certificate(&cert).unwrap();
96
+ acceptor.set_private_key(&key).unwrap();
97
+ acceptor
98
+ .set_min_proto_version(Some(SslVersion::TLS1_3))
99
+ .unwrap();
100
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
101
+ let url = format!("https://{}/", start_tls_server(listener, acceptor.build()));
102
+
103
+ assert_verification_failure(send(Client::builder(), &url).await);
104
+ let store = CertStore::builder()
105
+ .add_der_cert(LOCALHOST_CA)
106
+ .build()
107
+ .unwrap();
108
+ let response = send(Client::builder().tls_cert_store(store), &url)
109
+ .await
110
+ .unwrap();
111
+ assert!(response.status().is_success());
112
+ }
113
+
114
+ #[tokio::test]
115
+ async fn self_signed_certificate_requires_explicit_trust() {
116
+ use wreq::tls::TlsInfo;
117
+
118
+ let (cert, key) = tls_cert::self_signed("wreq.test", [127, 0, 0, 1].into());
119
+ let addr = serve(&cert, &key).await;
120
+ let url = format!("https://{addr}/");
121
+
122
+ assert_verification_failure(send(Client::builder(), &url).await);
123
+ assert_verification_failure(send(Client::builder().tls_verify_hostname(false), &url).await);
124
+
125
+ let builder = Client::builder()
126
+ .tls_cert_verification(false)
127
+ .tls_info(true);
128
+ let response = send(builder, &url).await.unwrap();
129
+ assert!(response.status().is_success());
130
+ let peer_cert = response
131
+ .extensions()
132
+ .get::<TlsInfo>()
133
+ .and_then(TlsInfo::peer_certificate)
134
+ .unwrap();
135
+ assert_eq!(peer_cert, cert.to_der().unwrap().as_slice());
136
+
137
+ let response = send(Client::builder().tls_cert_verification(false), &url)
138
+ .await
139
+ .unwrap();
140
+ assert!(response.extensions().get::<TlsInfo>().is_none());
141
+
142
+ let store = CertStore::builder()
143
+ .add_der_cert(peer_cert)
144
+ .build()
145
+ .unwrap();
146
+ let named = |host: &'static str| {
147
+ Client::builder()
148
+ .resolve(host, addr)
149
+ .tls_cert_store(store.clone())
150
+ };
151
+ let port = addr.port();
152
+ let response = send(named("wreq.test"), &format!("https://wreq.test:{port}/"))
153
+ .await
154
+ .unwrap();
155
+ assert!(response.status().is_success());
156
+ let wrong_host = format!("https://other.test:{port}/");
157
+ assert_verification_failure(send(named("other.test"), &wrong_host).await);
158
+ let response = send(named("other.test").tls_verify_hostname(false), &wrong_host)
159
+ .await
160
+ .unwrap();
161
+ assert!(response.status().is_success());
162
+
163
+ // Both certificates cover loopback, but the trust store contains only the first.
164
+ let (other_cert, other_key) = tls_cert::self_signed("wreq.test", addr.ip());
165
+ let other_addr = serve(&other_cert, &other_key).await;
166
+ let other_url = format!("https://{other_addr}/");
167
+ assert_verification_failure(send(Client::builder().tls_cert_store(store), &other_url).await);
168
+ }