Skip to content

Commit 5a62f7e

Browse files
duckkiLegNeato
andauthored
Report null results for non-null fields as execution errors (#1397)
Co-authored-by: Christian Legnitto <christian@legnitto.com>
1 parent d2cb246 commit 5a62f7e

5 files changed

Lines changed: 284 additions & 2 deletions

File tree

‎juniper/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ All user visible changes to `juniper` crate will be documented in this file. Thi
7878
- Exponential execution time of fragments that spread the same fragment more than once. ([GHSA-36rq-8957-mjrx])
7979
- Quadratic validation time and memory of fields with the same response name. ([GHSA-36rq-8957-mjrx])
8080
- Incorrect non-nullable type of `__type` introspection field. A query for an unknown type now returns `{"__type": null}` instead of `null` data. ([#1402])
81+
- Missing execution errors for null values returned from non-`Null` fields. ([#1397])
8182

8283
[#864]: /../../issues/864
8384
[#1055]: /../../issues/1055
@@ -98,6 +99,7 @@ All user visible changes to `juniper` crate will be documented in this file. Thi
9899
[#1387]: /../../pull/1387
99100
[#1393]: /../../pull/1393
100101
[#1394]: /../../pull/1394
102+
[#1397]: /../../pull/1397
101103
[#1402]: /../../pull/1402
102104
[GHSA-34cw-x8g7-rcv5]: /../../security/advisories/GHSA-34cw-x8g7-rcv5
103105
[GHSA-36rq-8957-mjrx]: /../../security/advisories/GHSA-36rq-8957-mjrx

‎juniper/src/executor/mod.rs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,34 @@ where
672672
});
673673
}
674674

675+
/// Pushes an error at `location` for a `null` result of the non-null `field_name` field of the
676+
/// `parent_type`.
677+
///
678+
/// Pushes nothing if an error exists at or below the current path. The `null` result then
679+
/// comes from that error. The GraphQL specification allows only one error per field.
680+
pub(crate) fn push_non_null_violation_at(
681+
&self,
682+
parent_type: &MetaType<S>,
683+
field_name: &str,
684+
location: SourcePosition,
685+
) {
686+
let mut path = Vec::new();
687+
self.field_path.construct_path(&mut path);
688+
689+
let mut errors = self.errors.write().unwrap();
690+
if errors.iter().any(|e| e.path.starts_with(&path)) {
691+
return;
692+
}
693+
694+
let type_name = parent_type.name().map_or("<unknown>", AsRef::as_ref);
695+
errors.push(ExecutionError {
696+
location,
697+
path,
698+
error: format!("Cannot return null for non-nullable field {type_name}.{field_name}.")
699+
.into(),
700+
});
701+
}
702+
675703
/// Returns new [`ExecutionError`] at current location
676704
pub fn new_error(&self, error: FieldError<S>) -> ExecutionError<S> {
677705
let mut path = Vec::new();

‎juniper/src/executor_tests/executor.rs‎

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,252 @@ mod field_execution {
129129
}
130130
}
131131

132+
mod non_null_null_result {
133+
use std::future;
134+
135+
use arcstr::ArcStr;
136+
137+
use crate::{
138+
BoxFuture, DefaultScalarValue, EmptyMutation, EmptySubscription, ExecutionResult, Executor,
139+
FieldError, FieldResult, GraphQLType, GraphQLValue, GraphQLValueAsync, Registry, RootNode,
140+
Value, executor::ExecutionError, graphql, graphql_object, macros::reflect,
141+
marker::IsOutputType, parser::SourcePosition, schema::meta::MetaType,
142+
types::base::Arguments,
143+
};
144+
145+
struct Query;
146+
147+
impl GraphQLType<DefaultScalarValue> for Query {
148+
fn name(_: &Self::TypeInfo) -> Option<ArcStr> {
149+
Some("Query".into())
150+
}
151+
152+
fn meta(
153+
info: &Self::TypeInfo,
154+
registry: &mut Registry<DefaultScalarValue>,
155+
) -> MetaType<DefaultScalarValue> {
156+
let fields = &[registry.field::<String>("critical", &())];
157+
registry.build_object_type::<Self>(info, fields).into_meta()
158+
}
159+
}
160+
161+
impl GraphQLValue<DefaultScalarValue> for Query {
162+
type Context = ();
163+
type TypeInfo = ();
164+
165+
fn type_name(&self, info: &Self::TypeInfo) -> Option<ArcStr> {
166+
<Self as GraphQLType>::name(info)
167+
}
168+
169+
fn resolve_field(
170+
&self,
171+
_: &Self::TypeInfo,
172+
_: &str,
173+
_: &Arguments<DefaultScalarValue>,
174+
_: &Executor<Self::Context>,
175+
) -> ExecutionResult {
176+
Ok(Value::null())
177+
}
178+
}
179+
180+
impl GraphQLValueAsync<DefaultScalarValue> for Query {
181+
fn resolve_field_async<'a>(
182+
&'a self,
183+
_: &'a Self::TypeInfo,
184+
_: &'a str,
185+
_: &'a Arguments<DefaultScalarValue>,
186+
_: &'a Executor<Self::Context>,
187+
) -> BoxFuture<'a, ExecutionResult> {
188+
Box::pin(future::ready(Ok(Value::null())))
189+
}
190+
}
191+
192+
fn schema() -> RootNode<Query, EmptyMutation, EmptySubscription> {
193+
RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new())
194+
}
195+
196+
#[tokio::test]
197+
async fn direct_null_from_non_null_field_is_reported() {
198+
let document = "{ critical }";
199+
200+
for (value, errors) in [
201+
crate::execute(document, None, &schema(), &graphql::vars! {}, &())
202+
.await
203+
.expect("async execution failed"),
204+
crate::execute_sync(document, None, &schema(), &graphql::vars! {}, &())
205+
.expect("sync execution failed"),
206+
] {
207+
assert_eq!(value, graphql::value!(null));
208+
assert_eq!(
209+
errors,
210+
[ExecutionError::new(
211+
SourcePosition::new(2, 0, 2),
212+
&["critical"],
213+
FieldError::new(
214+
"Cannot return null for non-nullable field Query.critical.",
215+
graphql::value!(null),
216+
),
217+
)],
218+
);
219+
}
220+
}
221+
222+
/// Object with a non-null `value` field that resolves to `null`.
223+
struct NullValue;
224+
225+
impl GraphQLType<DefaultScalarValue> for NullValue {
226+
fn name(_: &Self::TypeInfo) -> Option<ArcStr> {
227+
Some("NullValue".into())
228+
}
229+
230+
fn meta(
231+
info: &Self::TypeInfo,
232+
registry: &mut Registry<DefaultScalarValue>,
233+
) -> MetaType<DefaultScalarValue> {
234+
let fields = &[registry.field::<String>("value", &())];
235+
registry.build_object_type::<Self>(info, fields).into_meta()
236+
}
237+
}
238+
239+
impl GraphQLValue<DefaultScalarValue> for NullValue {
240+
type Context = ();
241+
type TypeInfo = ();
242+
243+
fn type_name(&self, info: &Self::TypeInfo) -> Option<ArcStr> {
244+
<Self as GraphQLType>::name(info)
245+
}
246+
247+
fn resolve_field(
248+
&self,
249+
_: &Self::TypeInfo,
250+
_: &str,
251+
_: &Arguments<DefaultScalarValue>,
252+
_: &Executor<Self::Context>,
253+
) -> ExecutionResult {
254+
Ok(Value::null())
255+
}
256+
}
257+
258+
impl GraphQLValueAsync<DefaultScalarValue> for NullValue {
259+
fn resolve_field_async<'a>(
260+
&'a self,
261+
_: &'a Self::TypeInfo,
262+
_: &'a str,
263+
_: &'a Arguments<DefaultScalarValue>,
264+
_: &'a Executor<Self::Context>,
265+
) -> BoxFuture<'a, ExecutionResult> {
266+
Box::pin(future::ready(Ok(Value::null())))
267+
}
268+
}
269+
270+
// `#[graphql_object]` requires these traits for the types of its fields. Derived types
271+
// implement the traits automatically.
272+
impl IsOutputType<DefaultScalarValue> for NullValue {}
273+
274+
impl reflect::BaseType<DefaultScalarValue> for NullValue {
275+
const NAME: reflect::Type = "NullValue";
276+
}
277+
278+
impl reflect::BaseSubTypes<DefaultScalarValue> for NullValue {
279+
const NAMES: reflect::Types = &[<Self as reflect::BaseType<DefaultScalarValue>>::NAME];
280+
}
281+
282+
impl reflect::WrappedType<DefaultScalarValue> for NullValue {
283+
const VALUE: reflect::WrappedValue = 1;
284+
}
285+
286+
struct Nested;
287+
288+
#[graphql_object(scalar = DefaultScalarValue)]
289+
impl Nested {
290+
fn null_value() -> NullValue {
291+
NullValue
292+
}
293+
294+
fn failing() -> FieldResult<String> {
295+
Err("failure".into())
296+
}
297+
}
298+
299+
struct NestedQuery;
300+
301+
#[graphql_object(scalar = DefaultScalarValue)]
302+
impl NestedQuery {
303+
fn nested() -> Option<Nested> {
304+
Some(Nested)
305+
}
306+
307+
fn non_null_nested() -> Nested {
308+
Nested
309+
}
310+
}
311+
312+
/// Executes `document` against a [`NestedQuery`] schema asynchronously and synchronously.
313+
async fn execute_nested(
314+
document: &str,
315+
) -> [(Value, Vec<ExecutionError<DefaultScalarValue>>); 2] {
316+
let schema = RootNode::new(NestedQuery, EmptyMutation::new(), EmptySubscription::new());
317+
[
318+
crate::execute(document, None, &schema, &graphql::vars! {}, &())
319+
.await
320+
.expect("async execution failed"),
321+
crate::execute_sync(document, None, &schema, &graphql::vars! {}, &())
322+
.expect("sync execution failed"),
323+
]
324+
}
325+
326+
fn null_value_error(index: usize, path: &[&str]) -> ExecutionError<DefaultScalarValue> {
327+
ExecutionError::new(
328+
SourcePosition::new(index, 0, index),
329+
path,
330+
FieldError::new(
331+
"Cannot return null for non-nullable field NullValue.value.",
332+
graphql::value!(null),
333+
),
334+
)
335+
}
336+
337+
#[tokio::test]
338+
async fn null_propagates_to_nearest_nullable_parent() {
339+
for (value, errors) in execute_nested("{ nested { nullValue { value } } }").await {
340+
assert_eq!(value, graphql::value!({"nested": null}));
341+
assert_eq!(
342+
errors,
343+
[null_value_error(23, &["nested", "nullValue", "value"])],
344+
);
345+
}
346+
}
347+
348+
#[tokio::test]
349+
async fn non_null_parents_add_no_error_for_null_child() {
350+
for (value, errors) in execute_nested("{ nonNullNested { nullValue { value } } }").await {
351+
assert_eq!(value, graphql::value!(null));
352+
assert_eq!(
353+
errors,
354+
[null_value_error(
355+
30,
356+
&["nonNullNested", "nullValue", "value"]
357+
)],
358+
);
359+
}
360+
}
361+
362+
#[tokio::test]
363+
async fn non_null_parent_adds_no_error_for_failed_child() {
364+
for (value, errors) in execute_nested("{ nonNullNested { failing } }").await {
365+
assert_eq!(value, graphql::value!(null));
366+
assert_eq!(
367+
errors,
368+
[ExecutionError::new(
369+
SourcePosition::new(18, 0, 18),
370+
&["nonNullNested", "failing"],
371+
FieldError::new("failure", graphql::value!(null)),
372+
)],
373+
);
374+
}
375+
}
376+
}
377+
132378
mod merge_parallel_fragments {
133379
use crate::{
134380
graphql, graphql_object,

‎juniper/src/types/async_await.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,10 @@ where
268268
.await;
269269

270270
let value = match res {
271-
Ok(Value::Null) if is_non_null => None,
271+
Ok(Value::Null) if is_non_null => {
272+
sub_exec.push_non_null_violation_at(meta_type, f.name.item, pos);
273+
None
274+
}
272275
Ok(v) => Some(v),
273276
Err(e) => {
274277
sub_exec.push_error_at(e, pos);

‎juniper/src/types/base.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,10 @@ where
485485
);
486486

487487
match field_result {
488-
Ok(Value::Null) if meta_field.field_type.is_non_null() => return false,
488+
Ok(Value::Null) if meta_field.field_type.is_non_null() => {
489+
sub_exec.push_non_null_violation_at(meta_type, f.name.item, span.start);
490+
return false;
491+
}
489492
Ok(v) => merge_key_into(result, response_name, v),
490493
Err(e) => {
491494
sub_exec.push_error_at(e, span.start);

0 commit comments

Comments
 (0)