diff --git a/src/main/java/graphql/execution/Execution.java b/src/main/java/graphql/execution/Execution.java index df7a0f6aeb..e563948c56 100644 --- a/src/main/java/graphql/execution/Execution.java +++ b/src/main/java/graphql/execution/Execution.java @@ -212,11 +212,21 @@ private CompletableFuture executeOperation(ExecutionContext exe .graphQLContext(graphQLContext) .build(); - MergedSelectionSet fields = fieldCollector.collectFields( - collectorParameters, - operationDefinition.getSelectionSet(), - executionContext.hasIncrementalSupport() - ); + MergedSelectionSet fields; + try { + fields = fieldCollector.collectFields( + collectorParameters, + operationDefinition.getSelectionSet(), + executionContext.hasIncrementalSupport() + ); + } catch (NonNullableValueCoercedAsNullException e) { + // a root level @skip / @include 'if' argument coerced to null - there is no enclosing field to null, + // so this is reported the same way as any other variable coercion failure + ExecutionResult executionResult = new ExecutionResultImpl(Collections.singletonList(e)); + executeOperationCtx.onDispatched(); + executeOperationCtx.onCompleted(executionResult, e); + return completedFuture(executionResult); + } ResultPath path = ResultPath.rootPath(); ExecutionStepInfo executionStepInfo = newExecutionStepInfo().type(operationRootType).path(path).build(); diff --git a/src/main/java/graphql/execution/ExecutionStrategy.java b/src/main/java/graphql/execution/ExecutionStrategy.java index 9402c65c8f..96308e56fa 100644 --- a/src/main/java/graphql/execution/ExecutionStrategy.java +++ b/src/main/java/graphql/execution/ExecutionStrategy.java @@ -6,6 +6,7 @@ import graphql.ExecutionResult; import graphql.ExecutionResultImpl; import graphql.GraphQLError; +import graphql.GraphqlErrorBuilder; import graphql.Internal; import graphql.PublicSpi; import graphql.SerializationError; @@ -805,10 +806,26 @@ protected FieldValueInfo completeValue(ExecutionContext executionContext, Execut handleUnresolvedTypeProblem(executionContext, parameters, ex); // complete field as null, validating it is nullable return getFieldValueInfoForNull(parameters); + } catch (NonNullableValueCoercedAsNullException ex) { + // a @skip / @include 'if' argument in the sub selection coerced to null - this is a field error + // on this field, so null it (propagating as usual) rather than failing the whole operation + handleSubSelectionCoercionProblem(executionContext, parameters, ex); + return getFieldValueInfoForNull(parameters); } return new FieldValueInfo(OBJECT, fieldValue); } + private void handleSubSelectionCoercionProblem(ExecutionContext context, ExecutionStrategyParameters parameters, NonNullableValueCoercedAsNullException e) { + GraphQLError error = GraphqlErrorBuilder.newError() + .message(e.getMessage()) + .locations(e.getLocations()) + .path(parameters.getPath()) + .errorType(e.getErrorType()) + .build(); + + addErrorToRightContext(error, parameters, context); + } + private void handleUnresolvedTypeProblem(ExecutionContext context, ExecutionStrategyParameters parameters, UnresolvedTypeException e) { UnresolvedTypeError error = new UnresolvedTypeError(parameters.getPath(), parameters.getExecutionStepInfo(), e); diff --git a/src/main/java/graphql/execution/NonNullableValueCoercedAsNullException.java b/src/main/java/graphql/execution/NonNullableValueCoercedAsNullException.java index 9192d50802..03002b70a3 100644 --- a/src/main/java/graphql/execution/NonNullableValueCoercedAsNullException.java +++ b/src/main/java/graphql/execution/NonNullableValueCoercedAsNullException.java @@ -6,6 +6,7 @@ import graphql.PublicApi; import graphql.language.SourceLocation; import graphql.language.VariableDefinition; +import graphql.language.VariableReference; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLInputObjectField; import graphql.schema.GraphQLType; @@ -72,6 +73,13 @@ public NonNullableValueCoercedAsNullException(GraphQLInputObjectField inputTypeF this.path = path; } + public NonNullableValueCoercedAsNullException(String directiveName, VariableReference variableReference) { + super(format("Variable '%s' has coerced Null value for the non-null 'if' argument of directive '@%s'", + variableReference.getName(), directiveName)); + SourceLocation sourceLocation = variableReference.getSourceLocation(); + this.sourceLocations = sourceLocation == null ? null : Collections.singletonList(sourceLocation); + } + public NonNullableValueCoercedAsNullException(GraphQLArgument graphQLArgument) { super(format("Argument '%s' has coerced Null value for NonNull type '%s'", graphQLArgument.getName(), graphQLArgument.getType())); } diff --git a/src/main/java/graphql/execution/conditional/ConditionalNodes.java b/src/main/java/graphql/execution/conditional/ConditionalNodes.java index e922eeb427..fd489c6fd7 100644 --- a/src/main/java/graphql/execution/conditional/ConditionalNodes.java +++ b/src/main/java/graphql/execution/conditional/ConditionalNodes.java @@ -4,6 +4,7 @@ import graphql.GraphQLContext; import graphql.Internal; import graphql.execution.CoercedVariables; +import graphql.execution.NonNullableValueCoercedAsNullException; import graphql.language.Argument; import graphql.language.BooleanValue; import graphql.language.Directive; @@ -133,12 +134,12 @@ public String getIncludeVariableName(DirectivesContainer directivesContainer) private @Nullable Boolean getDirectiveResult(Map variables, List directives, String directiveName, boolean defaultValue) { Directive foundDirective = NodeUtil.findNodeByName(directives, directiveName); if (foundDirective != null) { - return getIfValue(foundDirective.getArguments(), variables); + return getIfValue(directiveName, foundDirective.getArguments(), variables); } return defaultValue; } - private @Nullable Boolean getIfValue(List arguments, @Nullable Map variables) { + private @Nullable Boolean getIfValue(String directiveName, List arguments, @Nullable Map variables) { for (Argument argument : arguments) { if (argument.getName().equals("if")) { Object value = argument.getValue(); @@ -146,7 +147,15 @@ public String getIncludeVariableName(DirectivesContainer directivesContainer) return ((BooleanValue) value).isValue(); } if (value instanceof VariableReference && variables != null) { - return (boolean) variables.get(((VariableReference) value).getName()); + VariableReference variableReference = (VariableReference) value; + Object variableValue = variables.get(variableReference.getName()); + // the 'if' argument is Boolean! - a nullable variable with a non null default value is a legal + // usage here, so an explicit null variable value reaches this point and must be rejected as a + // coercion error rather than throwing a NullPointerException while unboxing + if (variableValue == null) { + throw new NonNullableValueCoercedAsNullException(directiveName, variableReference); + } + return (Boolean) variableValue; } return null; } diff --git a/src/test/groovy/graphql/SkipAndInclude.groovy b/src/test/groovy/graphql/SkipAndInclude.groovy index d0008f63fd..5db9db16dc 100644 --- a/src/test/groovy/graphql/SkipAndInclude.groovy +++ b/src/test/groovy/graphql/SkipAndInclude.groovy @@ -1,7 +1,20 @@ package graphql +import graphql.execution.CoercedVariables +import graphql.execution.NonNullableValueCoercedAsNullException +import graphql.execution.pubsub.CapturingSubscriber +import graphql.execution.pubsub.ReactiveStreamsObjectPublisher +import graphql.language.SourceLocation +import graphql.normalized.ExecutableNormalizedOperationFactory +import graphql.parser.Parser +import graphql.schema.DataFetcher +import org.awaitility.Awaitility +import org.reactivestreams.Publisher import spock.lang.Specification +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit + class SkipAndInclude extends Specification { private def graphQL = TestUtil.graphQL(""" @@ -78,4 +91,186 @@ class SkipAndInclude extends Specification { true | true false | false } + + private static GraphQL nestedGraphQL() { + def item = [child: "child"] + def parentFetcher = { env -> item } as DataFetcher + def asyncParentFetcher = { env -> CompletableFuture.supplyAsync({ item }) } as DataFetcher + def eventsFetcher = { env -> new ReactiveStreamsObjectPublisher(2, { i -> item }) } as DataFetcher + def schema = TestUtil.schema(""" + type Query { + ok: String + parent: Item + asyncParent: Item + wrapper: Wrapper + items: [Item] + } + type Mutation { + ok: String + parent: Item + } + type Subscription { + event: Item + } + type Wrapper { + inner: Item! + } + type Item { + child: String + } + """, [ + Query : [ok: { env -> "ok" } as DataFetcher, parent: parentFetcher, asyncParent: asyncParentFetcher, + wrapper: { env -> [inner: item] } as DataFetcher, items: { env -> [item, item] } as DataFetcher], + Mutation : [ok: { env -> "ok" } as DataFetcher, parent: parentFetcher], + Subscription: [event: eventsFetcher] + ]) + GraphQL.newGraphQL(schema).build() + } + + private static ExecutionInput nullFlagInput(String query) { + ExecutionInput.newExecutionInput().query(query).variables([flag: null]).build() + } + + private static String coercedNullMessage(String directive) { + "Variable 'flag' has coerced Null value for the non-null 'if' argument of directive '@$directive'" + } + + def "null value for a root #directive if argument is a coercion error with no data"() { + // a nullable variable with a non null default value is a legal usage in the non null 'if' position, + // so an explicit null variable value reaches the directive and must be reported as a coercion error + when: + def executionResult = graphQL.execute(nullFlagInput("""query(\$flag: Boolean = true) { + field @$directive(if: \$flag) +}""")) + + then: + !executionResult.isDataPresent() + !executionResult.toSpecification().containsKey("data") + executionResult.errors.size() == 1 + executionResult.errors[0] instanceof NonNullableValueCoercedAsNullException + executionResult.errors[0].message == coercedNullMessage(directive) + executionResult.errors[0].errorType == ErrorType.ValidationError + executionResult.errors[0].locations == [new SourceLocation(2, 15 + directive.length())] + executionResult.errors[0].path == null + + where: + directive << ["skip", "include"] + } + + def "null value for a nested #directive if argument nulls the nullable parent of #operation and keeps sibling data"() { + when: + def executionResult = nestedGraphQL().execute(nullFlagInput("""$operation(\$flag: Boolean = true) { + ok + parent { child @$directive(if: \$flag) } +}""")) + + then: + executionResult.toSpecification().data == [ok: "ok", parent: null] + executionResult.errors.size() == 1 + executionResult.errors[0].message == coercedNullMessage(directive) + executionResult.errors[0].errorType == ErrorType.ValidationError + executionResult.errors[0].path == ["parent"] + executionResult.errors[0].locations == [new SourceLocation(3, 24 + directive.length())] + + where: + directive | operation + "skip" | "query" + "include" | "query" + "skip" | "mutation" + "include" | "mutation" + } + + def "null value for a nested #directive if argument under an async parent nulls that parent"() { + when: + def executionResult = nestedGraphQL().execute(nullFlagInput("""query(\$flag: Boolean = true) { + ok + asyncParent { child @$directive(if: \$flag) } +}""")) + + then: + executionResult.toSpecification().data == [ok: "ok", asyncParent: null] + executionResult.errors.size() == 1 + executionResult.errors[0].message == coercedNullMessage(directive) + executionResult.errors[0].path == ["asyncParent"] + + where: + directive << ["skip", "include"] + } + + def "null value for a nested #directive if argument under a non-null parent propagates to the nullable grandparent"() { + when: + def executionResult = nestedGraphQL().execute(nullFlagInput("""query(\$flag: Boolean = true) { + ok + wrapper { inner { child @$directive(if: \$flag) } } +}""")) + + then: + executionResult.toSpecification().data == [ok: "ok", wrapper: null] + executionResult.errors.size() == 1 + executionResult.errors[0].message == coercedNullMessage(directive) + executionResult.errors[0].path == ["wrapper", "inner"] + executionResult.errors[0].locations == [new SourceLocation(3, 33 + directive.length())] + + where: + directive << ["skip", "include"] + } + + def "null value for a nested #directive if argument in a list nulls each list item"() { + when: + def executionResult = nestedGraphQL().execute(nullFlagInput("""query(\$flag: Boolean = true) { + ok + items { child @$directive(if: \$flag) } +}""")) + + then: + executionResult.toSpecification().data == [ok: "ok", items: [null, null]] + executionResult.errors*.path == [["items", 0], ["items", 1]] + executionResult.errors.every { it.message == coercedNullMessage(directive) } + + where: + directive << ["skip", "include"] + } + + def "null value for a nested #directive if argument in a subscription is an error on each event, not a stream failure"() { + when: + def executionResult = nestedGraphQL().execute(nullFlagInput("""subscription(\$flag: Boolean = true) { + event { child @$directive(if: \$flag) } +}""")) + Publisher publisher = executionResult.getData() + def subscriber = new CapturingSubscriber() + publisher.subscribe(subscriber) + Awaitility.await().atMost(10, TimeUnit.SECONDS).untilTrue(subscriber.isDone()) + + then: + subscriber.throwable == null + subscriber.events.size() == 2 + subscriber.events.every { er -> + er.toSpecification().data == [event: null] && + er.errors.size() == 1 && + er.errors[0].message == coercedNullMessage(directive) && + er.errors[0].path == ["event"] + } + + where: + directive << ["skip", "include"] + } + + def "null value for a #directive if argument is a coercion error when building a normalized operation"() { + given: + def schema = TestUtil.schema("type Query { field: Int }") + def document = new Parser().parseDocument("""query(\$flag: Boolean = true) { + field @$directive(if: \$flag) +}""") + + when: + ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation( + schema, document, null, CoercedVariables.of([flag: null])) + + then: + def e = thrown(NonNullableValueCoercedAsNullException) + e.message == coercedNullMessage(directive) + + where: + directive << ["skip", "include"] + } }