wreq 1.3.2.4 → 1.3.3
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.
- checksums.yaml +4 -4
- data/Cargo.lock +470 -50
- data/Cargo.toml +19 -16
- data/README.md +5 -12
- data/Rakefile +3 -9
- data/crates/wreq-util/Cargo.toml +1 -1
- data/crates/wreq-util/README.md +4 -2
- data/crates/wreq-util/examples/emulate.rs +7 -3
- data/crates/wreq-util/examples/tower_delay.rs +4 -4
- data/crates/wreq-util/src/emulate/macros.rs +197 -32
- data/crates/wreq-util/src/emulate/profile/chrome/header.rs +116 -0
- data/crates/wreq-util/src/emulate/profile/chrome/http2.rs +65 -0
- data/crates/wreq-util/src/emulate/profile/chrome/tls.rs +268 -0
- data/crates/wreq-util/src/emulate/profile/chrome.rs +2269 -0
- data/crates/wreq-util/src/emulate/profile/firefox/header.rs +54 -48
- data/crates/wreq-util/src/emulate/profile/firefox/http2.rs +102 -92
- data/crates/wreq-util/src/emulate/profile/firefox/tls.rs +146 -155
- data/crates/wreq-util/src/emulate/profile/firefox.rs +440 -312
- data/crates/wreq-util/src/emulate/profile/okhttp.rs +2 -3
- data/crates/wreq-util/src/emulate/profile/opera/header.rs +29 -0
- data/crates/wreq-util/src/emulate/profile/opera/http2.rs +50 -0
- data/crates/wreq-util/src/emulate/profile/opera/tls.rs +103 -0
- data/crates/wreq-util/src/emulate/profile/opera.rs +299 -0
- data/crates/wreq-util/src/emulate/profile.rs +10 -10
- data/crates/wreq-util/src/emulate.rs +1 -34
- data/crates/wreq-util/src/tower/delay/layer.rs +5 -5
- data/crates/wreq-util/src/tower/delay.rs +4 -4
- data/crates/wreq-util/tests/client.rs +50 -187
- data/crates/wreq-util/tests/emulate_chrome.rs +0 -17
- data/crates/wreq-util/tests/emulate_firefox.rs +26 -36
- data/crates/wreq-util/tests/emulate_opera.rs +0 -24
- data/crates/wreq-util/tests/support/mod.rs +1 -1
- data/lib/wreq_ruby/client.rb +27 -13
- data/lib/wreq_ruby/emulate.rb +3 -28
- data/lib/wreq_ruby/http.rb +9 -2
- data/src/client/body/json.rs +1 -2
- data/src/client/resp.rs +1 -1
- data/src/client.rs +8 -4
- data/src/emulate.rs +5 -28
- data/src/error.rs +23 -3
- data/src/lib.rs +3 -2
- data/src/options.rs +17 -19
- data/{crates/serde-magnus/src → src/serde}/de/array_deserializer.rs +2 -2
- data/{crates/serde-magnus/src → src/serde}/de/array_enumerator.rs +1 -1
- data/{crates/serde-magnus/src → src/serde}/de/deserializer.rs +31 -25
- data/{crates/serde-magnus/src → src/serde}/de/enum_deserializer.rs +3 -3
- data/{crates/serde-magnus/src → src/serde}/de/hash_deserializer.rs +2 -2
- data/{crates/serde-magnus/src → src/serde}/de/number_deserializer.rs +2 -2
- data/{crates/serde-magnus/src → src/serde}/de/variant_deserializer.rs +20 -11
- data/src/serde/de.rs +33 -0
- data/src/serde/error.rs +146 -0
- data/src/serde/ser/enums.rs +14 -0
- data/{crates/serde-magnus/src → src/serde}/ser/map_serializer.rs +2 -2
- data/src/serde/ser/seq_serializer.rs +71 -0
- data/src/serde/ser/serializer.rs +194 -0
- data/{crates/serde-magnus/src → src/serde}/ser/struct_serializer.rs +4 -4
- data/src/serde/ser/struct_variant_serializer.rs +44 -0
- data/src/serde/ser/tuple_variant_serializer.rs +41 -0
- data/src/serde/ser.rs +18 -0
- data/{crates/serde-magnus/src → src/serde}/tests.rs +68 -19
- data/src/serde.rs +202 -0
- data/test/emulation_test.rb +104 -21
- data/test/option_validation_test.rb +13 -4
- data/wreq.gemspec +15 -3
- metadata +29 -35
- data/VERSION +0 -1
- data/crates/README.md +0 -6
- data/crates/serde-magnus/Cargo.toml +0 -29
- data/crates/serde-magnus/LICENSE +0 -19
- data/crates/serde-magnus/README.md +0 -147
- data/crates/serde-magnus/src/de/mod.rs +0 -554
- data/crates/serde-magnus/src/error.rs +0 -84
- data/crates/serde-magnus/src/lib.rs +0 -137
- data/crates/serde-magnus/src/options.rs +0 -151
- data/crates/serde-magnus/src/ser/enums.rs +0 -11
- data/crates/serde-magnus/src/ser/mod.rs +0 -428
- data/crates/serde-magnus/src/ser/seq_serializer.rs +0 -68
- data/crates/serde-magnus/src/ser/serializer.rs +0 -220
- data/crates/serde-magnus/src/ser/struct_variant_serializer.rs +0 -45
- data/crates/serde-magnus/src/ser/tuple_variant_serializer.rs +0 -38
- data/crates/wreq-util/src/emulate/profile/chromium/chrome.rs +0 -731
- data/crates/wreq-util/src/emulate/profile/chromium/edge.rs +0 -418
- data/crates/wreq-util/src/emulate/profile/chromium/header.rs +0 -74
- data/crates/wreq-util/src/emulate/profile/chromium/http2.rs +0 -59
- data/crates/wreq-util/src/emulate/profile/chromium/opera.rs +0 -312
- data/crates/wreq-util/src/emulate/profile/chromium/tls.rs +0 -310
- data/crates/wreq-util/src/emulate/profile/chromium.rs +0 -9
- data/test/emulation_client_hello_test.rb +0 -142
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
use std::{collections::BTreeMap, fmt};
|
|
2
2
|
|
|
3
|
+
use ::serde::{Deserialize, Serialize, de::Visitor};
|
|
3
4
|
use magnus::{RArray, RHash, RString, Ruby, Value, encoding::EncodingCapable, value::ReprValue};
|
|
4
|
-
use serde::{Deserialize, Serialize};
|
|
5
|
-
use serde_bytes::ByteBuf;
|
|
6
5
|
|
|
7
|
-
use super::{
|
|
6
|
+
use super::{deserialize_json, deserialize_ruby, serialize};
|
|
8
7
|
|
|
9
8
|
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
|
10
9
|
struct Record {
|
|
@@ -31,13 +30,62 @@ enum State {
|
|
|
31
30
|
Failed { message: String },
|
|
32
31
|
}
|
|
33
32
|
|
|
33
|
+
/// Byte sequence that exercises Serde's owned byte-buffer entry points.
|
|
34
|
+
#[derive(Debug, PartialEq)]
|
|
35
|
+
struct ByteBuffer(Vec<u8>);
|
|
36
|
+
|
|
37
|
+
impl Serialize for ByteBuffer {
|
|
38
|
+
fn serialize<Serializer>(
|
|
39
|
+
&self,
|
|
40
|
+
serializer: Serializer,
|
|
41
|
+
) -> Result<Serializer::Ok, Serializer::Error>
|
|
42
|
+
where
|
|
43
|
+
Serializer: ::serde::Serializer,
|
|
44
|
+
{
|
|
45
|
+
serializer.serialize_bytes(&self.0)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
impl<'de> Deserialize<'de> for ByteBuffer {
|
|
50
|
+
fn deserialize<Deserializer>(deserializer: Deserializer) -> Result<Self, Deserializer::Error>
|
|
51
|
+
where
|
|
52
|
+
Deserializer: ::serde::Deserializer<'de>,
|
|
53
|
+
{
|
|
54
|
+
struct ByteBufferVisitor;
|
|
55
|
+
|
|
56
|
+
impl<'de> Visitor<'de> for ByteBufferVisitor {
|
|
57
|
+
type Value = ByteBuffer;
|
|
58
|
+
|
|
59
|
+
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
60
|
+
formatter.write_str("an owned byte buffer")
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
fn visit_bytes<Error>(self, value: &[u8]) -> Result<Self::Value, Error>
|
|
64
|
+
where
|
|
65
|
+
Error: ::serde::de::Error,
|
|
66
|
+
{
|
|
67
|
+
Ok(ByteBuffer(value.to_vec()))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
fn visit_byte_buf<Error>(self, value: Vec<u8>) -> Result<Self::Value, Error>
|
|
71
|
+
where
|
|
72
|
+
Error: ::serde::de::Error,
|
|
73
|
+
{
|
|
74
|
+
Ok(ByteBuffer(value))
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
deserializer.deserialize_byte_buf(ByteBufferVisitor)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
34
82
|
/// Assert that a supported Serde value survives conversion through Ruby.
|
|
35
83
|
fn assert_ruby_round_trip<Input>(ruby: &Ruby, input: Input) -> Result<(), magnus::Error>
|
|
36
84
|
where
|
|
37
85
|
Input: fmt::Debug + PartialEq + Serialize + for<'de> Deserialize<'de>,
|
|
38
86
|
{
|
|
39
87
|
let value: Value = serialize(ruby, &input)?;
|
|
40
|
-
let output: Input =
|
|
88
|
+
let output: Input = deserialize_ruby(ruby, value)?;
|
|
41
89
|
assert_eq!(input, output);
|
|
42
90
|
Ok(())
|
|
43
91
|
}
|
|
@@ -62,20 +110,22 @@ fn assert_scalar_conversions(ruby: &Ruby) -> Result<(), magnus::Error> {
|
|
|
62
110
|
let character: RString = serialize(ruby, &'\u{2603}')?;
|
|
63
111
|
assert_eq!("\u{2603}", character.to_string()?);
|
|
64
112
|
assert!(character.enc_get() == ruby.utf8_encindex());
|
|
65
|
-
let output: char =
|
|
113
|
+
let output: char = deserialize_ruby(ruby, character)?;
|
|
66
114
|
assert_eq!('\u{2603}', output);
|
|
67
115
|
|
|
68
116
|
let string: RString = serialize(ruby, &"Hello, world!")?;
|
|
69
117
|
assert_eq!("Hello, world!", string.to_string()?);
|
|
70
118
|
assert!(string.enc_get() == ruby.utf8_encindex());
|
|
71
|
-
assert_eq!(
|
|
119
|
+
assert_eq!(
|
|
120
|
+
"Hello, world!",
|
|
121
|
+
deserialize_ruby::<_, String>(ruby, string)?
|
|
122
|
+
);
|
|
72
123
|
|
|
73
|
-
let bytes =
|
|
124
|
+
let bytes = ByteBuffer(b"\0binary\xff".to_vec());
|
|
74
125
|
let value: RString = serialize(ruby, &bytes)?;
|
|
75
|
-
assert_eq!(bytes.
|
|
126
|
+
assert_eq!(bytes.0.as_slice(), value.to_bytes().as_ref());
|
|
76
127
|
assert!(value.enc_get() == ruby.ascii8bit_encindex());
|
|
77
|
-
|
|
78
|
-
assert_eq!(bytes, output);
|
|
128
|
+
assert_eq!(bytes, deserialize_ruby(ruby, value)?);
|
|
79
129
|
|
|
80
130
|
let none: Value = serialize(ruby, &Option::<u64>::None)?;
|
|
81
131
|
assert!(none.is_nil());
|
|
@@ -107,7 +157,7 @@ fn assert_composite_conversions(ruby: &Ruby) -> Result<(), magnus::Error> {
|
|
|
107
157
|
let value: RHash = serialize(ruby, &record)?;
|
|
108
158
|
let count: u64 = value.aref(ruby.to_symbol("count"))?;
|
|
109
159
|
assert_eq!(record.count, count);
|
|
110
|
-
assert_eq!(record,
|
|
160
|
+
assert_eq!(record, deserialize_ruby(ruby, value)?);
|
|
111
161
|
|
|
112
162
|
let map = BTreeMap::from([("first".to_owned(), 1_u64), ("second".to_owned(), 2)]);
|
|
113
163
|
assert_ruby_round_trip(ruby, map)?;
|
|
@@ -140,44 +190,43 @@ fn assert_integer_conversions(ruby: &Ruby) -> Result<(), magnus::Error> {
|
|
|
140
190
|
let value: Value = serialize(ruby, &i128::MIN)?;
|
|
141
191
|
let decimal: String = value.funcall("to_s", ())?;
|
|
142
192
|
assert_eq!(i128::MIN.to_string(), decimal);
|
|
143
|
-
assert_eq!(i128::MIN,
|
|
193
|
+
assert_eq!(i128::MIN, deserialize_ruby::<_, i128>(ruby, value)?);
|
|
144
194
|
assert_eq!(i128::MIN, deserialize_json::<_, i128>(ruby, value)?);
|
|
145
195
|
|
|
146
196
|
let value: Value = serialize(ruby, &u128::MAX)?;
|
|
147
197
|
let decimal: String = value.funcall("to_s", ())?;
|
|
148
198
|
assert_eq!(u128::MAX.to_string(), decimal);
|
|
149
|
-
assert_eq!(u128::MAX,
|
|
199
|
+
assert_eq!(u128::MAX, deserialize_ruby::<_, u128>(ruby, value)?);
|
|
150
200
|
assert_eq!(u128::MAX, deserialize_json::<_, u128>(ruby, value)?);
|
|
151
201
|
|
|
152
202
|
let value: Value = serialize(ruby, &u64::MAX)?;
|
|
153
|
-
assert_eq!(u64::MAX,
|
|
203
|
+
assert_eq!(u64::MAX, deserialize_ruby::<_, u64>(ruby, value)?);
|
|
154
204
|
assert_eq!(u64::MAX, deserialize_json::<_, u64>(ruby, value)?);
|
|
155
205
|
Ok(())
|
|
156
206
|
}
|
|
157
207
|
|
|
158
208
|
/// Verify unsupported borrowed values and malformed enum shapes return errors.
|
|
159
209
|
fn assert_conversion_errors(ruby: &Ruby) -> Result<(), magnus::Error> {
|
|
160
|
-
let error =
|
|
210
|
+
let error = deserialize_ruby::<_, &str>(ruby, ruby.str_new("borrowed"))
|
|
161
211
|
.expect_err("borrowed strings must not outlive their Ruby value");
|
|
162
212
|
assert_type_error(error, "expected a borrowed string");
|
|
163
213
|
|
|
164
|
-
let error =
|
|
214
|
+
let error = deserialize_ruby::<_, &[u8]>(ruby, ruby.str_new("borrowed"))
|
|
165
215
|
.expect_err("borrowed byte slices must not outlive their Ruby value");
|
|
166
216
|
assert_type_error(error, "can't deserialize into byte slice");
|
|
167
217
|
|
|
168
218
|
let variants = ruby.hash_new();
|
|
169
219
|
variants.aset("Ready", ruby.qnil())?;
|
|
170
220
|
variants.aset("Count", 1)?;
|
|
171
|
-
let error =
|
|
221
|
+
let error = deserialize_ruby::<_, State>(ruby, variants)
|
|
172
222
|
.expect_err("an enum hash must contain exactly one variant");
|
|
173
223
|
assert_type_error(error, "Hash of length 2");
|
|
174
224
|
Ok(())
|
|
175
225
|
}
|
|
176
226
|
|
|
177
227
|
#[test]
|
|
178
|
-
#[allow(unsafe_code)]
|
|
179
228
|
fn retains_ruby_serde_conversion_surface() -> Result<(), magnus::Error> {
|
|
180
|
-
// SAFETY: this
|
|
229
|
+
// SAFETY: this is the only test that initializes the embedded Ruby VM.
|
|
181
230
|
let ruby = unsafe { magnus::embed::init() };
|
|
182
231
|
|
|
183
232
|
assert_scalar_conversions(&ruby)?;
|
data/src/serde.rs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2022 George Claghorn
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
8
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
9
|
+
so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
//! Serde integration for Magnus with JSON-specific conversion behavior.
|
|
24
|
+
//!
|
|
25
|
+
//! This module is adapted from `serde_magnus` 0.11.0 and retains its generic
|
|
26
|
+
//! Ruby serialization and deserialization surface. Local changes add a JSON
|
|
27
|
+
//! mode with arbitrary-size integer support, finite-float and object-key
|
|
28
|
+
//! validation, insertion-order preservation, and bounded container nesting.
|
|
29
|
+
//! The bridge also avoids the upstream `Ruby::get().unwrap()` error path,
|
|
30
|
+
//! checks iterator and map state explicitly, reports unknown option fields and
|
|
31
|
+
//! conversion paths, and supports `i128` and `u128` in both directions for
|
|
32
|
+
//! typed Rust values.
|
|
33
|
+
#![allow(unsafe_code)]
|
|
34
|
+
|
|
35
|
+
mod de;
|
|
36
|
+
mod error;
|
|
37
|
+
mod ser;
|
|
38
|
+
#[cfg(test)]
|
|
39
|
+
mod tests;
|
|
40
|
+
|
|
41
|
+
use ::serde::{Deserialize, Serialize, de::DeserializeOwned};
|
|
42
|
+
use indexmap::IndexSet;
|
|
43
|
+
use magnus::{IntoValue, Ruby, TryConvert};
|
|
44
|
+
use serde_ignored::Path;
|
|
45
|
+
use serde_path_to_error::{Deserializer as PathDeserializer, Track};
|
|
46
|
+
|
|
47
|
+
use crate::error::argument_error;
|
|
48
|
+
|
|
49
|
+
pub(super) use error::Error;
|
|
50
|
+
|
|
51
|
+
/// Private map key used to carry arbitrary-precision numbers through Serde.
|
|
52
|
+
///
|
|
53
|
+
/// This mirrors the representation used by `serde_json` when its
|
|
54
|
+
/// `arbitrary_precision` feature is enabled. The precision tests protect this
|
|
55
|
+
/// integration point when `serde_json` is updated.
|
|
56
|
+
pub(super) const JSON_NUMBER_TOKEN: &str = "$serde_json::private::Number";
|
|
57
|
+
|
|
58
|
+
/// Maximum nesting accepted while converting a Ruby request value.
|
|
59
|
+
pub(super) const MAX_JSON_NESTING: usize = 100;
|
|
60
|
+
|
|
61
|
+
/// Deserialize a Ruby value using native Ruby data model semantics.
|
|
62
|
+
///
|
|
63
|
+
/// This preserves the public conversion behavior provided by the upstream
|
|
64
|
+
/// `serde_magnus::deserialize` function. JSON callers should use
|
|
65
|
+
/// [`deserialize_json`] when arbitrary-size integer precision is required.
|
|
66
|
+
///
|
|
67
|
+
/// # Errors
|
|
68
|
+
///
|
|
69
|
+
/// Returns the Ruby exception produced when the input cannot be represented by
|
|
70
|
+
/// `Output`.
|
|
71
|
+
#[allow(dead_code)] // Retained as part of the upstream-compatible Serde surface.
|
|
72
|
+
pub(crate) fn deserialize_ruby<'de, Input, Output>(
|
|
73
|
+
ruby: &Ruby,
|
|
74
|
+
input: Input,
|
|
75
|
+
) -> Result<Output, magnus::Error>
|
|
76
|
+
where
|
|
77
|
+
Input: IntoValue,
|
|
78
|
+
Output: Deserialize<'de>,
|
|
79
|
+
{
|
|
80
|
+
de::deserialize_ruby(ruby, input.into_value_with(ruby)).map_err(|error| error.into_magnus(ruby))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// Serialize any Serde value into a Ruby value.
|
|
84
|
+
///
|
|
85
|
+
/// This preserves the public conversion behavior provided by the upstream
|
|
86
|
+
/// `serde_magnus::serialize` function.
|
|
87
|
+
///
|
|
88
|
+
/// # Errors
|
|
89
|
+
///
|
|
90
|
+
/// Returns the Ruby exception produced while creating or converting the output
|
|
91
|
+
/// value.
|
|
92
|
+
pub(crate) fn serialize<Input, Output>(ruby: &Ruby, input: &Input) -> Result<Output, magnus::Error>
|
|
93
|
+
where
|
|
94
|
+
Input: Serialize + ?Sized,
|
|
95
|
+
Output: TryConvert,
|
|
96
|
+
{
|
|
97
|
+
let value = ser::serialize(ruby, input).map_err(|error| error.into_magnus(ruby))?;
|
|
98
|
+
Output::try_convert(value)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// Deserialize a Ruby value using JSON-specific conversion rules.
|
|
102
|
+
///
|
|
103
|
+
/// Unlike [`deserialize_ruby`], this preserves arbitrary-size integers and
|
|
104
|
+
/// rejects non-finite floats, unsupported object keys, and excessive nesting.
|
|
105
|
+
///
|
|
106
|
+
/// # Errors
|
|
107
|
+
///
|
|
108
|
+
/// Returns the Ruby exception produced when the input cannot be represented by
|
|
109
|
+
/// `Output`.
|
|
110
|
+
pub(crate) fn deserialize_json<'de, Input, Output>(
|
|
111
|
+
ruby: &Ruby,
|
|
112
|
+
input: Input,
|
|
113
|
+
) -> Result<Output, magnus::Error>
|
|
114
|
+
where
|
|
115
|
+
Input: IntoValue,
|
|
116
|
+
Output: Deserialize<'de>,
|
|
117
|
+
{
|
|
118
|
+
de::deserialize_json(ruby, input.into_value_with(ruby)).map_err(|error| error.into_magnus(ruby))
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// Validate Ruby option keys without inspecting their values.
|
|
122
|
+
///
|
|
123
|
+
/// The derived struct is the only list of accepted keys. Every option field is
|
|
124
|
+
/// optional, so this pass can collect unknown keys and duplicates without
|
|
125
|
+
/// converting or retaining any Ruby value.
|
|
126
|
+
///
|
|
127
|
+
/// # Errors
|
|
128
|
+
///
|
|
129
|
+
/// Returns `ArgumentError` for unknown or duplicate keys and `TypeError` for
|
|
130
|
+
/// keys that are neither Ruby Symbols nor Strings.
|
|
131
|
+
pub(crate) fn validate_option_keys<Input, Output>(
|
|
132
|
+
ruby: &Ruby,
|
|
133
|
+
input: Input,
|
|
134
|
+
) -> Result<(), magnus::Error>
|
|
135
|
+
where
|
|
136
|
+
Input: IntoValue,
|
|
137
|
+
Output: DeserializeOwned,
|
|
138
|
+
{
|
|
139
|
+
let value: magnus::Value = input.into_value_with(ruby);
|
|
140
|
+
let mut unknown = IndexSet::new();
|
|
141
|
+
{
|
|
142
|
+
let mut callback = |path: Path<'_>| {
|
|
143
|
+
if let Path::Map { key, .. } = path {
|
|
144
|
+
unknown.insert(key);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
serde_ignored::deserialize::<_, _, Output>(
|
|
148
|
+
de::Deserializer::new_option_keys(ruby, value),
|
|
149
|
+
&mut callback,
|
|
150
|
+
)
|
|
151
|
+
.map_err(|error| error.into_option_magnus(ruby, None))?;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if unknown.is_empty() {
|
|
155
|
+
return Ok(());
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let label = if unknown.len() == 1 {
|
|
159
|
+
"unknown option"
|
|
160
|
+
} else {
|
|
161
|
+
"unknown options"
|
|
162
|
+
};
|
|
163
|
+
let mut message = String::from(label);
|
|
164
|
+
message.push(':');
|
|
165
|
+
for (index, name) in unknown.into_iter().enumerate() {
|
|
166
|
+
if index > 0 {
|
|
167
|
+
message.push(',');
|
|
168
|
+
}
|
|
169
|
+
message.push(' ');
|
|
170
|
+
message.push(':');
|
|
171
|
+
message.push_str(&name);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
Err(argument_error(ruby, message))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/// Deserialize validated Ruby options and retain the failing field path.
|
|
178
|
+
///
|
|
179
|
+
/// # Errors
|
|
180
|
+
///
|
|
181
|
+
/// Returns the Ruby conversion error with the failing option path attached.
|
|
182
|
+
pub(crate) fn deserialize_options<Input, Output>(
|
|
183
|
+
ruby: &Ruby,
|
|
184
|
+
input: Input,
|
|
185
|
+
) -> Result<Output, magnus::Error>
|
|
186
|
+
where
|
|
187
|
+
Input: IntoValue,
|
|
188
|
+
Output: DeserializeOwned,
|
|
189
|
+
{
|
|
190
|
+
let value = input.into_value_with(ruby);
|
|
191
|
+
let mut track = Track::new();
|
|
192
|
+
let result = Output::deserialize(PathDeserializer::new(
|
|
193
|
+
de::Deserializer::new_ruby(ruby, value),
|
|
194
|
+
&mut track,
|
|
195
|
+
));
|
|
196
|
+
|
|
197
|
+
result.map_err(|error| {
|
|
198
|
+
let path = track.path();
|
|
199
|
+
let path = path.iter().next().is_some().then_some(&path);
|
|
200
|
+
error.into_option_magnus(ruby, path)
|
|
201
|
+
})
|
|
202
|
+
}
|
data/test/emulation_test.rb
CHANGED
|
@@ -1,36 +1,119 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "test_helper"
|
|
4
|
+
require "socket"
|
|
5
|
+
require "stringio"
|
|
6
|
+
require "timeout"
|
|
4
7
|
|
|
5
8
|
class EmulationTest < Minitest::Test
|
|
6
|
-
def
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
9
|
+
def test_reused_emulation_retains_trust_anchors_across_clients_and_requests
|
|
10
|
+
[Wreq::Profile::Chrome152, Wreq::Profile::Chrome153, Wreq::Profile::Chrome154, Wreq::Profile::Chrome155, Wreq::Profile::Chrome156, Wreq::Profile::Chrome157].each do |profile|
|
|
11
|
+
emulation = Wreq::Emulation.new(profile: profile)
|
|
12
|
+
client = Wreq::Client.new(emulation: emulation, no_proxy: true)
|
|
13
|
+
expected = capture_trust_anchors { |url| client.get(url, timeout: 5) }
|
|
14
|
+
refute_empty expected, profile.to_s
|
|
15
|
+
|
|
16
|
+
request_client = Wreq::Client.new(no_proxy: true)
|
|
17
|
+
2.times do
|
|
18
|
+
actual = capture_trust_anchors do |url|
|
|
19
|
+
request_client.get(url, emulation: emulation, timeout: 5)
|
|
20
|
+
end
|
|
21
|
+
assert_equal expected, actual, "#{profile}: reusing an object must retain its configuration"
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def test_all_emulation_device_constants_are_non_nil
|
|
27
|
+
Wreq::Profile.constants.each do |name|
|
|
28
|
+
const = Wreq::Profile.const_get(name)
|
|
29
|
+
assert_instance_of Wreq::Profile, const,
|
|
30
|
+
"#{name} should be Profile, got #{const.inspect}"
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def test_chrome151_profile_is_available
|
|
35
|
+
profile = Wreq::Profile::Chrome151
|
|
36
|
+
|
|
37
|
+
assert_equal "Chrome151", profile.to_s
|
|
38
|
+
assert_instance_of Wreq::Emulation, Wreq::Emulation.new(profile: profile)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def test_new_browser_profiles_are_available
|
|
42
|
+
{
|
|
43
|
+
Wreq::Profile::Chrome152 => "Chrome152",
|
|
44
|
+
Wreq::Profile::Chrome153 => "Chrome153",
|
|
45
|
+
Wreq::Profile::Chrome154 => "Chrome154",
|
|
46
|
+
Wreq::Profile::Chrome155 => "Chrome155",
|
|
47
|
+
Wreq::Profile::Chrome156 => "Chrome156",
|
|
48
|
+
Wreq::Profile::Chrome157 => "Chrome157",
|
|
49
|
+
Wreq::Profile::Firefox152 => "Firefox152"
|
|
50
|
+
}.each do |profile, name|
|
|
51
|
+
assert_equal name, profile.to_s
|
|
52
|
+
assert_instance_of Wreq::Emulation, Wreq::Emulation.new(profile: profile)
|
|
15
53
|
end
|
|
16
|
-
|
|
54
|
+
end
|
|
17
55
|
|
|
18
|
-
|
|
19
|
-
|
|
56
|
+
def test_all_emulation_os_constants_are_non_nil
|
|
57
|
+
Wreq::Platform.constants.each do |name|
|
|
58
|
+
const = Wreq::Platform.const_get(name)
|
|
59
|
+
assert_instance_of Wreq::Platform, const,
|
|
60
|
+
"#{name} should be Platform, got #{const.inspect}"
|
|
61
|
+
end
|
|
20
62
|
end
|
|
21
63
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
64
|
+
private
|
|
65
|
+
|
|
66
|
+
# Each listener forces a new connection. Stop after ClientHello so this test
|
|
67
|
+
# inspects the extension bytes without depending on certificates or the network.
|
|
68
|
+
def capture_trust_anchors
|
|
69
|
+
server = TCPServer.new("127.0.0.1", 0)
|
|
70
|
+
thread = Thread.new do
|
|
71
|
+
socket = nil
|
|
72
|
+
Timeout.timeout(5) do
|
|
73
|
+
socket = server.accept
|
|
74
|
+
handshake = +"".b
|
|
75
|
+
loop do
|
|
76
|
+
header = read_tls_bytes(socket, 5)
|
|
77
|
+
raise "expected a TLS handshake record" unless header.getbyte(0) == 22
|
|
78
|
+
handshake << read_tls_bytes(socket, header.byteslice(3, 2).unpack1("n"))
|
|
79
|
+
next if handshake.bytesize < 4
|
|
80
|
+
length = handshake.byteslice(1, 3).bytes.reduce(0) { |n, byte| (n << 8) | byte }
|
|
81
|
+
break if handshake.bytesize >= length + 4
|
|
82
|
+
end
|
|
83
|
+
trust_anchors_from_client_hello(handshake)
|
|
84
|
+
end
|
|
85
|
+
ensure
|
|
86
|
+
socket&.close
|
|
28
87
|
end
|
|
88
|
+
thread.report_on_exception = false
|
|
89
|
+
|
|
90
|
+
assert_raises(Wreq::ConnectionError) { yield "https://127.0.0.1:#{server.addr[1]}/" }
|
|
91
|
+
thread.value
|
|
92
|
+
ensure
|
|
93
|
+
server&.close
|
|
94
|
+
thread&.kill if thread&.alive?
|
|
95
|
+
thread&.join
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def read_tls_bytes(io, length)
|
|
99
|
+
bytes = io.read(length)
|
|
100
|
+
raise EOFError, "truncated ClientHello" unless bytes&.bytesize == length
|
|
101
|
+
bytes
|
|
29
102
|
end
|
|
30
103
|
|
|
31
|
-
def
|
|
32
|
-
|
|
33
|
-
|
|
104
|
+
def trust_anchors_from_client_hello(handshake)
|
|
105
|
+
io = StringIO.new(handshake)
|
|
106
|
+
raise "expected ClientHello" unless read_tls_bytes(io, 1).unpack1("C") == 1
|
|
107
|
+
read_tls_bytes(io, 3 + 2 + 32) # Handshake length, legacy version and random.
|
|
108
|
+
read_tls_bytes(io, read_tls_bytes(io, 1).unpack1("C")) # Session ID.
|
|
109
|
+
read_tls_bytes(io, read_tls_bytes(io, 2).unpack1("n")) # Cipher suites.
|
|
110
|
+
read_tls_bytes(io, read_tls_bytes(io, 1).unpack1("C")) # Compression methods.
|
|
111
|
+
extensions = StringIO.new(read_tls_bytes(io, read_tls_bytes(io, 2).unpack1("n")))
|
|
112
|
+
until extensions.eof?
|
|
113
|
+
type, length = read_tls_bytes(extensions, 4).unpack("nn")
|
|
114
|
+
data = read_tls_bytes(extensions, length)
|
|
115
|
+
return data if type == 51764
|
|
34
116
|
end
|
|
117
|
+
raise "missing trust_anchors extension"
|
|
35
118
|
end
|
|
36
119
|
end
|
|
@@ -227,12 +227,21 @@ class OptionValidationTest < Minitest::Test
|
|
|
227
227
|
end
|
|
228
228
|
|
|
229
229
|
def test_protocol_only_options_are_mutually_exclusive
|
|
230
|
-
|
|
231
|
-
|
|
230
|
+
[:http1_only, :http2_only, :http3_only].combination(2) do |first, second|
|
|
231
|
+
error = assert_raises(ArgumentError) do
|
|
232
|
+
Wreq::Client.new(**{first => true, second => true})
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
assert_includes error.message, ":#{first}"
|
|
236
|
+
assert_includes error.message, ":#{second}"
|
|
232
237
|
end
|
|
233
238
|
|
|
234
|
-
|
|
235
|
-
|
|
239
|
+
assert_instance_of Wreq::Client,
|
|
240
|
+
Wreq::Client.new(http3_only: true, http1_only: false, http2_only: nil)
|
|
241
|
+
assert_instance_of Wreq::Client,
|
|
242
|
+
Wreq::Client.new(http1_only: true, http3_only: false)
|
|
243
|
+
assert_instance_of Wreq::Client,
|
|
244
|
+
Wreq::Client.new(http2_only: true, http3_only: nil)
|
|
236
245
|
end
|
|
237
246
|
|
|
238
247
|
def test_validation_reports_the_first_failed_rule
|
data/wreq.gemspec
CHANGED
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
3
5
|
Gem::Specification.new do |spec|
|
|
4
6
|
spec.name = "wreq"
|
|
5
7
|
# RubyGems integrates and expects `cargo`.
|
|
6
8
|
# Read more about
|
|
7
9
|
# [Gem::Ext::CargoBuilder](https://github.com/rubygems/rubygems/blob/v3.5.23/lib/rubygems/ext/cargo_builder.rb)
|
|
8
10
|
#
|
|
9
|
-
#
|
|
10
|
-
|
|
11
|
+
# wreq relies on "version" in `Cargo.toml` for the release process. You can read this gem spec with:
|
|
12
|
+
# `bundle exec ruby -e 'puts Gem::Specification.load("wreq.gemspec")'`
|
|
13
|
+
#
|
|
14
|
+
# keep in sync the key "wreq-ruby" with `Rakefile`.
|
|
15
|
+
#
|
|
16
|
+
# uses `cargo` to extract the version.
|
|
17
|
+
cargo_output = `cargo metadata --format-version 1`
|
|
18
|
+
cargo_output.force_encoding("UTF-8")
|
|
19
|
+
spec.version = JSON.parse(cargo_output.strip)
|
|
20
|
+
.fetch("packages")
|
|
21
|
+
.find { |p| p["name"] == "wreq-ruby" }
|
|
22
|
+
.fetch("version")
|
|
11
23
|
spec.authors = ["SearchApi"]
|
|
12
24
|
spec.email = ["support@searchapi.io"]
|
|
13
25
|
spec.summary = "Ruby bindings for wreq, an HTTP client with TLS/HTTP2 browser fingerprinting"
|
|
@@ -44,7 +56,7 @@ Gem::Specification.new do |spec|
|
|
|
44
56
|
# Exclude non-Ruby files from RDoc to prevent parsing errors
|
|
45
57
|
spec.rdoc_options = ["--exclude", "Cargo\\..*", "--exclude", "\\.rs$"]
|
|
46
58
|
|
|
47
|
-
spec.requirements = ["Rust >= 1.
|
|
59
|
+
spec.requirements = ["Rust >= 1.98"]
|
|
48
60
|
# use a Ruby version which:
|
|
49
61
|
# - supports Rubygems with the ability of compilation of Rust gem
|
|
50
62
|
# - not end of life
|