wreq-rb 0.6.1 → 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 (41) 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 +7 -4
  5. data/ext/wreq_rb/extconf.rb +10 -3
  6. data/ext/wreq_rb/src/client.rs +145 -14
  7. data/ext/wreq_rb/src/response.rs +28 -3
  8. data/lib/wreq-rb/version.rb +1 -1
  9. data/patches/0002-add-preconnect.patch +266 -0
  10. data/vendor/wreq/Cargo.toml +11 -7
  11. data/vendor/wreq/bench/support/server.rs +2 -0
  12. data/vendor/wreq/src/client/layer/redirect/future.rs +1 -1
  13. data/vendor/wreq/src/client/layer/timeout/body.rs +16 -18
  14. data/vendor/wreq/src/client/layer/timeout/future.rs +2 -2
  15. data/vendor/wreq/src/client/request.rs +27 -15
  16. data/vendor/wreq/src/client/ws.rs +4 -3
  17. data/vendor/wreq/src/client.rs +4 -24
  18. data/vendor/wreq/src/conn/net/tcp.rs +16 -66
  19. data/vendor/wreq/src/conn/proxy/socks.rs +11 -1
  20. data/vendor/wreq/src/conn/proxy/tunnel.rs +14 -11
  21. data/vendor/wreq/src/conn/timeout.rs +1 -1
  22. data/vendor/wreq/src/cookie/jar.rs +170 -36
  23. data/vendor/wreq/src/cookie/store.rs +66 -4
  24. data/vendor/wreq/src/cookie.rs +48 -17
  25. data/vendor/wreq/src/dns.rs +2 -4
  26. data/vendor/wreq/src/error.rs +100 -0
  27. data/vendor/wreq/src/ext.rs +0 -49
  28. data/vendor/wreq/src/lib.rs +2 -0
  29. data/vendor/wreq/src/rt.rs +1 -14
  30. data/vendor/wreq/src/tls/trust/store.rs +35 -2
  31. data/vendor/wreq/tests/badssl.rs +3 -239
  32. data/vendor/wreq/tests/cert_store.rs +168 -0
  33. data/vendor/wreq/tests/client.rs +89 -0
  34. data/vendor/wreq/tests/proxy.rs +149 -3
  35. data/vendor/wreq/tests/redirect.rs +35 -0
  36. data/vendor/wreq/tests/support/tls_cert.rs +56 -0
  37. data/vendor/wreq/tests/timeouts.rs +25 -0
  38. data/vendor/wreq/tests/unix_socket.rs +109 -81
  39. data/vendor/wreq/tests/websocket.rs +40 -0
  40. metadata +9 -6
  41. data/vendor/wreq/examples/rt.rs +0 -23
@@ -14,13 +14,17 @@ use std::{convert::TryInto, fmt, sync::Arc, time::SystemTime};
14
14
 
15
15
  use cookie::{Cookie as RawCookie, Expiration, SameSite};
16
16
  use http::{Uri, Version};
17
+ use url::Host;
17
18
 
18
19
  pub use self::jar::Jar;
19
20
  use crate::{error::Error, header::HeaderValue};
20
21
 
21
- /// A parsed HTTP cookie.
22
+ /// A parsed HTTP cookie with optional [`Jar`] storage metadata.
22
23
  #[derive(Debug, Clone)]
23
- pub struct Cookie<'a>(RawCookie<'a>);
24
+ pub struct Cookie<'a> {
25
+ inner: RawCookie<'a>,
26
+ host: Option<Host<Box<str>>>,
27
+ }
24
28
 
25
29
  impl<'a> Cookie<'a> {
26
30
  pub(crate) fn parse(value: &'a HeaderValue) -> crate::Result<Cookie<'a>> {
@@ -28,13 +32,22 @@ impl<'a> Cookie<'a> {
28
32
  .map_err(cookie::ParseError::from)
29
33
  .and_then(cookie::Cookie::parse)
30
34
  .map_err(Error::decode)
31
- .map(Cookie)
35
+ .map(|cookie| Cookie {
36
+ inner: cookie,
37
+ host: None,
38
+ })
39
+ }
40
+
41
+ #[inline]
42
+ fn with_host(mut self, host: Host<Box<str>>) -> Self {
43
+ self.host = Some(host);
44
+ self
32
45
  }
33
46
 
34
47
  /// Returns the name of `self`.
35
48
  #[inline]
36
49
  pub fn name(&self) -> &str {
37
- self.0.name()
50
+ self.inner.name()
38
51
  }
39
52
 
40
53
  /// Returns the value of `self`.
@@ -42,37 +55,37 @@ impl<'a> Cookie<'a> {
42
55
  /// Does not strip surrounding quotes.
43
56
  #[inline]
44
57
  pub fn value(&self) -> &str {
45
- self.0.value()
58
+ self.inner.value()
46
59
  }
47
60
 
48
61
  /// Returns whether this cookie was marked `HttpOnly` or not.
49
62
  #[inline]
50
63
  pub fn http_only(&self) -> bool {
51
- self.0.http_only().unwrap_or(false)
64
+ self.inner.http_only().unwrap_or(false)
52
65
  }
53
66
 
54
67
  /// Returns whether this cookie was marked `Secure` or not.
55
68
  #[inline]
56
69
  pub fn secure(&self) -> bool {
57
- self.0.secure().unwrap_or(false)
70
+ self.inner.secure().unwrap_or(false)
58
71
  }
59
72
 
60
73
  /// Returns whether the `SameSite` attribute of this cookie is `Lax`.
61
74
  #[inline]
62
75
  pub fn same_site_lax(&self) -> bool {
63
- self.0.same_site() == Some(SameSite::Lax)
76
+ self.inner.same_site() == Some(SameSite::Lax)
64
77
  }
65
78
 
66
79
  /// Returns whether the `SameSite` attribute of this cookie is `Strict`.
67
80
  #[inline]
68
81
  pub fn same_site_strict(&self) -> bool {
69
- self.0.same_site() == Some(SameSite::Strict)
82
+ self.inner.same_site() == Some(SameSite::Strict)
70
83
  }
71
84
 
72
85
  /// Returns the `Path` of the cookie if one was specified.
73
86
  #[inline]
74
87
  pub fn path(&self) -> Option<&str> {
75
- self.0.path()
88
+ self.inner.path()
76
89
  }
77
90
 
78
91
  /// Returns the `Domain` of the cookie if one was specified.
@@ -82,13 +95,25 @@ impl<'a> Cookie<'a> {
82
95
  /// stripped.
83
96
  #[inline]
84
97
  pub fn domain(&self) -> Option<&str> {
85
- self.0.domain()
98
+ self.inner.domain()
99
+ }
100
+
101
+ /// Returns the canonical host used to store this cookie.
102
+ ///
103
+ /// Cookies returned by [`Jar`] query methods include this value.
104
+ #[inline]
105
+ pub fn host(&self) -> Option<Host<&str>> {
106
+ self.host.as_ref().map(|host| match host {
107
+ Host::Domain(domain) => Host::Domain(domain.as_ref()),
108
+ Host::Ipv4(address) => Host::Ipv4(*address),
109
+ Host::Ipv6(address) => Host::Ipv6(*address),
110
+ })
86
111
  }
87
112
 
88
113
  /// Returns the specified max-age of the cookie if it is non-negative and representable.
89
114
  #[inline]
90
115
  pub fn max_age(&self) -> Option<std::time::Duration> {
91
- self.0.max_age().and_then(|d| d.try_into().ok())
116
+ self.inner.max_age().and_then(|d| d.try_into().ok())
92
117
  }
93
118
 
94
119
  /// Returns the expiration date-time of the cookie if one was specified.
@@ -96,7 +121,7 @@ impl<'a> Cookie<'a> {
96
121
  /// Session cookies return `None`.
97
122
  #[inline]
98
123
  pub fn expires(&self) -> Option<SystemTime> {
99
- match self.0.expires() {
124
+ match self.inner.expires() {
100
125
  Some(Expiration::DateTime(offset)) => Some(SystemTime::from(offset)),
101
126
  None | Some(Expiration::Session) => None,
102
127
  }
@@ -105,28 +130,34 @@ impl<'a> Cookie<'a> {
105
130
  /// Converts `self` into a `Cookie` with a static lifetime with as few allocations as possible.
106
131
  #[inline]
107
132
  pub fn into_owned(self) -> Cookie<'static> {
108
- Cookie(self.0.into_owned())
133
+ Cookie {
134
+ inner: self.inner.into_owned(),
135
+ host: self.host,
136
+ }
109
137
  }
110
138
  }
111
139
 
112
140
  impl fmt::Display for Cookie<'_> {
113
141
  #[inline]
114
142
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115
- self.0.fmt(f)
143
+ self.inner.fmt(f)
116
144
  }
117
145
  }
118
146
 
119
147
  impl<'c> From<RawCookie<'c>> for Cookie<'c> {
120
148
  #[inline]
121
149
  fn from(cookie: RawCookie<'c>) -> Cookie<'c> {
122
- Cookie(cookie)
150
+ Cookie {
151
+ inner: cookie,
152
+ host: None,
153
+ }
123
154
  }
124
155
  }
125
156
 
126
157
  impl<'c> From<Cookie<'c>> for RawCookie<'c> {
127
158
  #[inline]
128
159
  fn from(cookie: Cookie<'c>) -> RawCookie<'c> {
129
- cookie.0
160
+ cookie.inner
130
161
  }
131
162
  }
132
163
 
@@ -11,11 +11,9 @@ mod resolve;
11
11
  #[cfg(feature = "hickory-dns")]
12
12
  pub(crate) mod hickory;
13
13
 
14
- pub use self::{
15
- gai::GaiResolver,
16
- resolve::{Addrs, IntoResolve, Name, Resolve, Resolving},
17
- };
14
+ pub use self::resolve::{Addrs, IntoResolve, Name, Resolve, Resolving};
18
15
  pub(crate) use self::{
16
+ gai::GaiResolver,
19
17
  resolve::{DnsResolverWithOverrides, DynResolver},
20
18
  sealed::{DnsResolver, resolve},
21
19
  };
@@ -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`]