Skip to content

Commit

Permalink
Accept extensions: null in a GraphQL request (#4911)
Browse files Browse the repository at this point in the history
Fixes #3388

In GraphQL requests, `extensions` is an optional map. Passing an
explicit `null` was incorrectly considered a parse error. Now it is
equivalent to omiting that field entirely, or to passing an empty map.

<!-- start metadata -->
---

**Checklist**

Complete the checklist (and note appropriate exceptions) before the PR
is marked ready-for-review.

- [ ] Changes are compatible[^1]
- [ ] Documentation[^2] completed
- [ ] Performance impact assessed and acceptable
- Tests added and passing[^3]
    - [ ] Unit Tests
    - [ ] Integration Tests
    - [ ] Manual Tests

**Exceptions**

*Note any exceptions here*

**Notes**

[^1]: It may be appropriate to bring upcoming changes to the attention
of other (impacted) groups. Please endeavour to do this before seeking
PR approval. The mechanism for doing this will vary considerably, so use
your judgement as to how and when to do this.
[^2]: Configuration is an important part of many changes. Where
applicable please try to document configuration examples.
[^3]: Tick whichever testing boxes are applicable. If you are adding
Manual Tests, please document the manual testing (extensively) in the
Exceptions.

---------

Co-authored-by: Bryn Cooke <[email protected]>
Co-authored-by: bryn <[email protected]>
  • Loading branch information
3 people authored Apr 4, 2024
1 parent 9b14fe5 commit 3aa0546
Show file tree
Hide file tree
Showing 3 changed files with 126 additions and 102 deletions.
7 changes: 7 additions & 0 deletions .changesets/fix_simon_accept_request_extensions_is_null.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Accept `extensions: null` in a GraphQL request ([Issue #3388](https://github.com/apollographql/router/issues/3388))

In GraphQL requests, `extensions` is an optional map.
Passing an explicit `null` was incorrectly considered a parse error.
Now it is equivalent to omiting that field entirely, or to passing an empty map.

By [@SimonSapin](https://github.com/SimonSapin) in https://github.com/apollographql/router/pull/4911
184 changes: 82 additions & 102 deletions apollo-router/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,19 +88,14 @@ where
<Option<T>>::deserialize(deserializer).map(|x| x.unwrap_or_default())
}

fn as_object<E: Error>(value: Value, null_is_default: bool) -> Result<Object, E> {
fn as_optional_object<E: Error>(value: Value) -> Result<Object, E> {
use serde::de::Unexpected;

let exp = if null_is_default {
"a map or null"
} else {
"a map"
};
let exp = "a map or null";
match value {
Value::Object(object) => Ok(object),
// Similar to `deserialize_null_default`:
Value::Null if null_is_default => Ok(Object::default()),
Value::Null => Err(E::invalid_type(Unexpected::Unit, &exp)),
Value::Null => Ok(Object::default()),
Value::Bool(value) => Err(E::invalid_type(Unexpected::Bool(value), &exp)),
Value::Number(_) => Err(E::invalid_type(Unexpected::Other("a number"), &exp)),
Value::String(value) => Err(E::invalid_type(Unexpected::Str(value.as_str()), &exp)),
Expand Down Expand Up @@ -365,17 +360,15 @@ impl<'data, 'de> DeserializeSeed<'de> for RequestFromBytesSeed<'data> {
}
let seed = serde_json_bytes::value::BytesSeed::new(self.0);
let value = map.next_value_seed(seed)?;
let null_is_default = true;
variables = Some(as_object(value, null_is_default)?);
variables = Some(as_optional_object(value)?);
}
Field::Extensions => {
if extensions.is_some() {
return Err(Error::duplicate_field("extensions"));
}
let seed = serde_json_bytes::value::BytesSeed::new(self.0);
let value = map.next_value_seed(seed)?;
let null_is_default = false;
extensions = Some(as_object(value, null_is_default)?);
extensions = Some(as_optional_object(value)?);
}
Field::Other => {
let _: serde::de::IgnoredAny = map.next_value()?;
Expand Down Expand Up @@ -411,11 +404,10 @@ mod tests {
"operationName": "aTest",
"variables": { "arg1": "me" },
"extensions": {"extension": 1}
})
.to_string();
let result = serde_json::from_str::<Request>(data.as_str());
});
let result = check_deserialization(data);
assert_eq!(
result.unwrap(),
result,
Request::builder()
.query("query aTest($arg1: String!) { test(who: $arg1) }".to_owned())
.operation_name("aTest")
Expand All @@ -427,18 +419,14 @@ mod tests {

#[test]
fn test_no_variables() {
let result = serde_json::from_str::<Request>(
json!(
{
"query": "query aTest($arg1: String!) { test(who: $arg1) }",
"operationName": "aTest",
"extensions": {"extension": 1}
})
.to_string()
.as_str(),
);
let result = check_deserialization(json!(
{
"query": "query aTest($arg1: String!) { test(who: $arg1) }",
"operationName": "aTest",
"extensions": {"extension": 1}
}));
assert_eq!(
result.unwrap(),
result,
Request::builder()
.query("query aTest($arg1: String!) { test(who: $arg1) }".to_owned())
.operation_name("aTest")
Expand All @@ -451,19 +439,15 @@ mod tests {
// rover sends { "variables": null } when running the introspection query,
// and possibly running other queries as well.
fn test_variables_is_null() {
let result = serde_json::from_str::<Request>(
json!(
{
"query": "query aTest($arg1: String!) { test(who: $arg1) }",
"operationName": "aTest",
"variables": null,
"extensions": {"extension": 1}
})
.to_string()
.as_str(),
);
let result = check_deserialization(json!(
{
"query": "query aTest($arg1: String!) { test(who: $arg1) }",
"operationName": "aTest",
"variables": null,
"extensions": {"extension": 1}
}));
assert_eq!(
result.unwrap(),
result,
Request::builder()
.query("query aTest($arg1: String!) { test(who: $arg1) }")
.operation_name("aTest")
Expand All @@ -476,20 +460,16 @@ mod tests {
fn from_urlencoded_query_works() {
let query_string = "query=%7B+topProducts+%7B+upc+name+reviews+%7B+id+product+%7B+name+%7D+author+%7B+id+name+%7D+%7D+%7D+%7D&extensions=%7B+%22persistedQuery%22+%3A+%7B+%22version%22+%3A+1%2C+%22sha256Hash%22+%3A+%2220a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f%22+%7D+%7D".to_string();

let expected_result = serde_json::from_str::<Request>(
json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "20a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f"
}
}
})
.to_string()
.as_str(),
).unwrap();
let expected_result = check_deserialization(json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "20a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f"
}
}
}));

let req = Request::from_urlencoded_query(query_string).unwrap();

Expand All @@ -500,21 +480,17 @@ mod tests {
fn from_urlencoded_query_with_variables_works() {
let query_string = "query=%7B+topProducts+%7B+upc+name+reviews+%7B+id+product+%7B+name+%7D+author+%7B+id+name+%7D+%7D+%7D+%7D&variables=%7B%22date%22%3A%222022-01-01T00%3A00%3A00%2B00%3A00%22%7D&extensions=%7B+%22persistedQuery%22+%3A+%7B+%22version%22+%3A+1%2C+%22sha256Hash%22+%3A+%2220a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f%22+%7D+%7D".to_string();

let expected_result = serde_json::from_str::<Request>(
json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "20a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f"
}
}
})
.to_string()
.as_str(),
).unwrap();
let expected_result = check_deserialization(json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "20a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f"
}
}
}));

let req = Request::from_urlencoded_query(query_string).unwrap();

Expand All @@ -523,50 +499,54 @@ mod tests {

#[test]
fn null_extensions() {
let expected_result = serde_json::from_str::<Request>(
json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
"extensions": null
})
.to_string()
.as_str(),
).unwrap();
let expected_result = check_deserialization(json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
"extensions": null
}));
insta::assert_yaml_snapshot!(expected_result);
}

#[test]
fn missing_extensions() {
let expected_result = serde_json::from_str::<Request>(
json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
})
.to_string()
.as_str(),
).unwrap();
let expected_result = check_deserialization(json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
}));
insta::assert_yaml_snapshot!(expected_result);
}

#[test]
fn extensions() {
let expected_result = serde_json::from_str::<Request>(
json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
"extensions": {
"something_simple": "else",
"something_complex": {
"nested": "value"
}
}
})
.to_string()
.as_str(),
).unwrap();
let expected_result = check_deserialization(json!(
{
"query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
"variables": {"date": "2022-01-01T00:00:00+00:00"},
"extensions": {
"something_simple": "else",
"something_complex": {
"nested": "value"
}
}
}));
insta::assert_yaml_snapshot!(expected_result);
}

fn check_deserialization(request: serde_json::Value) -> Request {
// check that deserialize_from_bytes agrees with Deserialize impl

let string = serde_json::to_string(&request).expect("could not serialize request");
let string_deserialized =
serde_json::from_str(&string).expect("could not deserialize string");
let bytes = Bytes::copy_from_slice(string.as_bytes());
let bytes_deserialized =
Request::deserialize_from_bytes(&bytes).expect("could not deserialize from bytes");
assert_eq!(
string_deserialized, bytes_deserialized,
"string and bytes deserialization did not match"
);
string_deserialized
}
}
37 changes: 37 additions & 0 deletions apollo-router/tests/integration/validation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use apollo_router::_private::create_test_service_factory_from_yaml;
use tower::ServiceExt;

#[tokio::test]
async fn test_supergraph_validation_errors_are_passed_on() {
Expand All @@ -10,3 +11,39 @@ async fn test_supergraph_validation_errors_are_passed_on() {
)
.await;
}

/// <https://github.com/apollographql/router/issues/3388>
#[tokio::test]
async fn test_request_extensions_is_null() {
// `extensions` is optional:
// <https://graphql.github.io/graphql-over-http/draft/#sec-Request-Parameters>

// > Specifying null for optional request parameters is equivalent to not specifying them at all
// https://graphql.github.io/graphql-over-http/draft/#note-22957

let request =
serde_json::json!({"query": "{__typename}", "extensions": serde_json::Value::Null});
let request = apollo_router::services::router::Request::fake_builder()
.body(request.to_string())
.method(hyper::Method::POST)
.header("content-type", "application/json")
.build()
.unwrap();
let response = apollo_router::TestHarness::builder()
.schema(include_str!("../fixtures/supergraph.graphql"))
.build_router()
.await
.unwrap()
.oneshot(request)
.await
.unwrap()
.next_response()
.await
.unwrap()
.unwrap();
// Used to be an INVALID_GRAPHQL_REQUEST error with "invalid type: null, expected a map"
assert_eq!(
String::from_utf8_lossy(&response),
r#"{"data":{"__typename":"Query"}}"#
);
}

0 comments on commit 3aa0546

Please sign in to comment.