Skip to content

Commit 52aea4d

Browse files
authored
Disallow deserialize empty GraphQLBatchRequest (#639) (#644)
* Disallow deserialize empty GraphQLBatchRequest (#639) * Add test for empty batch request
1 parent 8453310 commit 52aea4d

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

juniper/src/http/mod.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod graphiql;
44
pub mod playground;
55

66
use serde::{
7+
de,
78
ser::{self, SerializeMap},
89
Deserialize, Serialize,
910
};
@@ -216,7 +217,7 @@ where
216217
}
217218
}
218219

219-
/// Simple wrapper around GraphQLRequest to allow the handling of Batch requests
220+
/// Simple wrapper around GraphQLRequest to allow the handling of Batch requests.
220221
#[derive(Debug, Deserialize, PartialEq)]
221222
#[serde(untagged)]
222223
#[serde(bound = "InputValue<S>: Deserialize<'de>")]
@@ -226,10 +227,29 @@ where
226227
{
227228
/// A single operation request.
228229
Single(GraphQLRequest<S>),
230+
229231
/// A batch operation request.
232+
///
233+
/// Empty batch is considered as invalid value, so cannot be deserialized.
234+
#[serde(deserialize_with = "deserialize_non_empty_vec")]
230235
Batch(Vec<GraphQLRequest<S>>),
231236
}
232237

238+
fn deserialize_non_empty_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
239+
where
240+
D: de::Deserializer<'de>,
241+
T: Deserialize<'de>,
242+
{
243+
use de::Error as _;
244+
245+
let v = Vec::<T>::deserialize(deserializer)?;
246+
if v.is_empty() {
247+
Err(D::Error::invalid_length(0, &"a positive integer"))
248+
} else {
249+
Ok(v)
250+
}
251+
}
252+
233253
impl<S> GraphQLBatchRequest<S>
234254
where
235255
S: ScalarValue,
@@ -373,6 +393,9 @@ pub mod tests {
373393
println!(" - test_batched_post");
374394
test_batched_post(integration);
375395

396+
println!(" - test_empty_batched_post");
397+
test_empty_batched_post(integration);
398+
376399
println!(" - test_invalid_json");
377400
test_invalid_json(integration);
378401

@@ -499,6 +522,11 @@ pub mod tests {
499522
);
500523
}
501524

525+
fn test_empty_batched_post<T: HTTPIntegration>(integration: &T) {
526+
let response = integration.post("/", "[]");
527+
assert_eq!(response.status_code, 400);
528+
}
529+
502530
fn test_invalid_json<T: HTTPIntegration>(integration: &T) {
503531
let response = integration.get("/?query=blah");
504532
assert_eq!(response.status_code, 400);

0 commit comments

Comments
 (0)