From 1bdb449e51bb6a38b7d78c4b0efed85cfac4b055 Mon Sep 17 00:00:00 2001 From: Marc-Andre Giroux Date: Wed, 11 Nov 2026 08:43:28 -0500 Subject: [PATCH 1/2] Make SchemaValidator a single pass over types instead of a SchemaTraverser walk SchemaValidator now applies its rules by iterating the schema's types and directive definitions directly, instead of running ten GraphQLTypeVisitor rules over every schema element with SchemaTraverser. validateSchema keeps the same signature; getRules() and the rule visitor classes are removed. Behaviour differences: - errors are reported grouped by type, so their order changes - elements shared between several parents are checked under each of them, where the traversal only checked them under the first parent it reached - schemas whose programmatic default values form a cycle now fail with an InvalidSchemaException instead of a StackOverflowError On large-schema-4 validation drops from ~407ms to ~16ms and allocation from ~532MB to ~12MB per run (SchemaValidatorBenchmark). --- .../benchmark/SchemaValidatorBenchmark.java | 50 ++ .../AppliedDirectiveArgumentsAreValid.java | 100 --- .../validation/AppliedDirectivesAreValid.java | 59 -- .../validation/DefaultValuesAreValid.java | 91 --- ...ecatedInputObjectAndArgumentsAreValid.java | 63 -- .../InputAndOutputTypesUsedAppropriately.java | 90 -- .../NoDefaultValueCircularRefs.java | 239 ------ .../validation/NoUnbrokenInputCycles.java | 84 -- .../validation/OneOfInputObjectRules.java | 88 -- .../schema/validation/SchemaValidator.java | 772 +++++++++++++++++- .../schema/validation/TypeAndFieldRule.java | 233 ------ .../validation/TypesImplementInterfaces.java | 211 ----- .../CircularInputDefaultValuesTest.groovy | 2 +- ...nterfacesImplementingInterfacesTest.groovy | 4 +- .../graphql/schema/FastBuilderTest.groovy | 2 +- .../graphql/schema/SchemaTraverserTest.groovy | 24 + ...AndOutputTypesUsedAppropriatelyTest.groovy | 29 + .../NoDefaultValueCircularRefsTest.groovy | 87 ++ .../NoUnbrokenInputCyclesTest.groovy | 70 +- .../SchemaValidationErrorCollectorTest.groovy | 37 + .../validation/SchemaValidatorTest.groovy | 223 ++++- .../validation/TypeAndFieldRuleTest.groovy | 38 + .../TypesImplementInterfacesTest.groovy | 495 ++++------- 23 files changed, 1414 insertions(+), 1677 deletions(-) create mode 100644 src/jmh/java/benchmark/SchemaValidatorBenchmark.java delete mode 100644 src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java delete mode 100644 src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java delete mode 100644 src/main/java/graphql/schema/validation/DefaultValuesAreValid.java delete mode 100644 src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java delete mode 100644 src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java delete mode 100644 src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java delete mode 100644 src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java delete mode 100644 src/main/java/graphql/schema/validation/OneOfInputObjectRules.java delete mode 100644 src/main/java/graphql/schema/validation/TypeAndFieldRule.java delete mode 100644 src/main/java/graphql/schema/validation/TypesImplementInterfaces.java create mode 100644 src/test/groovy/graphql/schema/validation/SchemaValidationErrorCollectorTest.groovy diff --git a/src/jmh/java/benchmark/SchemaValidatorBenchmark.java b/src/jmh/java/benchmark/SchemaValidatorBenchmark.java new file mode 100644 index 0000000000..f4cff33638 --- /dev/null +++ b/src/jmh/java/benchmark/SchemaValidatorBenchmark.java @@ -0,0 +1,50 @@ +package benchmark; + +import graphql.schema.GraphQLSchema; +import graphql.schema.idl.FastSchemaGenerator; +import graphql.schema.idl.RuntimeWiring; +import graphql.schema.idl.SchemaGenerator; +import graphql.schema.idl.SchemaParser; +import graphql.schema.validation.SchemaValidator; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import java.util.concurrent.TimeUnit; + +@Warmup(iterations = 2, time = 5) +@Measurement(iterations = 3) +@Fork(2) +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class SchemaValidatorBenchmark { + + @Param({"large-schema-4.graphqls", "large-schema-federated-1.graphqls"}) + public String schemaFile; + + private GraphQLSchema schema; + + @Setup + public void setup() { + String sdl = BenchmarkUtils.loadResource(schemaFile); + schema = new FastSchemaGenerator().makeExecutableSchema( + SchemaGenerator.Options.defaultOptions().withValidation(false), + new SchemaParser().parse(sdl), + RuntimeWiring.MOCKED_WIRING); + } + + @Benchmark + public void validateSchema(Blackhole blackhole) { + blackhole.consume(new SchemaValidator().validateSchema(schema)); + } +} diff --git a/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java b/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java deleted file mode 100644 index 1eec8bff75..0000000000 --- a/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java +++ /dev/null @@ -1,100 +0,0 @@ -package graphql.schema.validation; - -import graphql.GraphQLContext; -import graphql.Internal; -import graphql.execution.NonNullableValueCoercedAsNullException; -import graphql.execution.ValuesResolver; -import graphql.language.Value; -import graphql.schema.CoercingParseValueException; -import graphql.schema.GraphQLAppliedDirective; -import graphql.schema.GraphQLAppliedDirectiveArgument; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLDirective; -import graphql.schema.GraphQLInputType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLTypeUtil; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.schema.InputValueWithState; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; -import graphql.validation.ValidationUtil; - -import java.util.Locale; - -import static java.lang.String.format; - -@Internal -public class AppliedDirectiveArgumentsAreValid extends GraphQLTypeVisitorStub { - - private ValidationUtil validationUtil = new ValidationUtil(); - - - @Override - public TraversalControl visitGraphQLDirective(GraphQLDirective directive, TraverserContext context) { - // if there is no parent it means it is just a directive definition and not an applied directive - if (context.getParentNode() != null) { - for (GraphQLArgument graphQLArgument : directive.getArguments()) { - checkArgument( - directive.getName(), - graphQLArgument.getName(), - graphQLArgument.getArgumentValue(), - graphQLArgument.getType(), - context - ); - } - } - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLAppliedDirective(GraphQLAppliedDirective directive, TraverserContext context) { - // if there is no parent it means it is just a directive definition and not an applied directive - if (context.getParentNode() != null) { - for (GraphQLAppliedDirectiveArgument graphQLArgument : directive.getArguments()) { - checkArgument( - directive.getName(), - graphQLArgument.getName(), - graphQLArgument.getArgumentValue(), - graphQLArgument.getType(), - context - ); - } - } - return TraversalControl.CONTINUE; - } - - private void checkArgument( - String directiveName, - String argumentName, - InputValueWithState argumentValue, - GraphQLInputType argumentType, - TraverserContext context - ) { - GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class); - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - boolean invalid = false; - if (argumentValue.isLiteral() && - !validationUtil.isValidLiteralValue((Value) argumentValue.getValue(), argumentType, schema, GraphQLContext.getDefault(), Locale.getDefault())) { - invalid = true; - } else if (argumentValue.isExternal() && - !isValidExternalValue(schema, argumentValue.getValue(), argumentType, GraphQLContext.getDefault(), Locale.getDefault())) { - invalid = true; - } else if (argumentValue.isNotSet() && GraphQLTypeUtil.isNonNull(argumentType)) { - invalid = true; - } - if (invalid) { - String message = format("Invalid argument '%s' for applied directive of name '%s'", argumentName, directiveName); - errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidAppliedDirectiveArgument, message)); - } - } - - private boolean isValidExternalValue(GraphQLSchema schema, Object externalValue, GraphQLInputType type, GraphQLContext graphQLContext, Locale locale) { - try { - ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, graphQLContext, locale); - return true; - } catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) { - return false; - } - } -} diff --git a/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java b/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java deleted file mode 100644 index cf2b3da5d4..0000000000 --- a/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java +++ /dev/null @@ -1,59 +0,0 @@ -package graphql.schema.validation; - -import graphql.Internal; -import graphql.schema.GraphQLDirective; -import graphql.schema.GraphQLDirectiveContainer; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import java.util.List; -import java.util.Map; - -import static graphql.schema.validation.SchemaValidationErrorType.InvalidAppliedDirective; -import static java.lang.String.format; - -@Internal -public class AppliedDirectivesAreValid extends GraphQLTypeVisitorStub { - - @Override - protected TraversalControl visitGraphQLType(GraphQLSchemaElement node, TraverserContext context) { - SchemaValidationErrorCollector collector = context.getVarFromParents(SchemaValidationErrorCollector.class); - GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class); - if (node instanceof GraphQLDirectiveContainer) { - GraphQLDirectiveContainer directiveContainer = (GraphQLDirectiveContainer) node; - for (Map.Entry> entry : directiveContainer.getAllDirectivesByName().entrySet()) { - String directiveName = entry.getKey(); - GraphQLDirective directiveDef = schema.getDirective(directiveName); - if (directiveDef != null) { - checkNonRepeatable(collector, directiveContainer, directiveDef, entry.getValue()); - } else { - addError(collector, format("A definition for directive '%s' could not be found", directiveName)); - } - } - } - - return TraversalControl.CONTINUE; - } - - private void checkNonRepeatable(SchemaValidationErrorCollector collector, GraphQLDirectiveContainer directiveContainer, GraphQLDirective directiveDef, List directives) { - if (directiveDef.isNonRepeatable() && directives.size() > 1) { - addNonRepeatableError(collector, directiveContainer, directiveDef.getName(), directives.size()); - } - } - - private void addNonRepeatableError(SchemaValidationErrorCollector collector, GraphQLDirectiveContainer directiveContainer, String name, int howMany) { - addError(collector, format("The directive '%s' on the '%s' called '%s' is a non repeatable directive but has been applied %d times", - name, - directiveContainer.getClass().getSimpleName(), - directiveContainer.getName(), - howMany)); - } - - private void addError(SchemaValidationErrorCollector collector, String message) { - collector.addError(new SchemaValidationError(InvalidAppliedDirective, message)); - } - -} diff --git a/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java b/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java deleted file mode 100644 index 4527973461..0000000000 --- a/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java +++ /dev/null @@ -1,91 +0,0 @@ -package graphql.schema.validation; - -import graphql.GraphQLContext; -import graphql.execution.NonNullableValueCoercedAsNullException; -import graphql.execution.ValuesResolver; -import graphql.language.Value; -import graphql.schema.CoercingParseValueException; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLInputType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.schema.InputValueWithState; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; -import graphql.validation.ValidationUtil; - -import java.util.Locale; - -import static graphql.schema.GraphQLTypeUtil.simplePrint; -import static java.lang.String.format; - -public class DefaultValuesAreValid extends GraphQLTypeVisitorStub { - - private ValidationUtil validationUtil = new ValidationUtil(); - - private final GraphQLContext graphQLContext = GraphQLContext.getDefault(); - - - @Override - public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType node, TraverserContext context) { - return super.visitGraphQLInputObjectType(node, context); - } - - @Override - public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField inputObjectField, TraverserContext context) { - if (!inputObjectField.hasSetDefaultValue()) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class); - InputValueWithState defaultValue = inputObjectField.getInputFieldDefaultValue(); - boolean invalid = false; - if (defaultValue.isLiteral() && - !validationUtil.isValidLiteralValue((Value) defaultValue.getValue(), inputObjectField.getType(), schema, graphQLContext, Locale.getDefault())) { - invalid = true; - } else if (defaultValue.isExternal() && - !isValidExternalValue(schema, defaultValue.getValue(), inputObjectField.getType(), graphQLContext)) { - invalid = true; - } - if (invalid) { - String message = format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(inputObjectField.getType())); - errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, message)); - } - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLArgument(GraphQLArgument argument, TraverserContext context) { - if (!argument.hasSetDefaultValue()) { - return TraversalControl.CONTINUE; - } - GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class); - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - InputValueWithState defaultValue = argument.getArgumentDefaultValue(); - boolean invalid = false; - if (defaultValue.isLiteral() && - !validationUtil.isValidLiteralValue((Value) defaultValue.getValue(), argument.getType(), schema, graphQLContext, Locale.getDefault())) { - invalid = true; - } else if (defaultValue.isExternal() && - !isValidExternalValue(schema, defaultValue.getValue(), argument.getType(), graphQLContext)) { - invalid = true; - } - if (invalid) { - String message = format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(argument.getType())); - errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, message)); - } - return TraversalControl.CONTINUE; - } - - private boolean isValidExternalValue(GraphQLSchema schema, Object externalValue, GraphQLInputType type, GraphQLContext graphQLContext) { - try { - ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, graphQLContext, Locale.getDefault()); - return true; - } catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) { - return false; - } - } -} diff --git a/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java b/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java deleted file mode 100644 index f7c1c1c776..0000000000 --- a/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java +++ /dev/null @@ -1,63 +0,0 @@ -package graphql.schema.validation; - -import graphql.Directives; -import graphql.Internal; -import graphql.schema.GraphQLAppliedDirective; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLDirective; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLTypeUtil; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import static java.lang.String.format; - -/* - From the spec: - The @deprecated directive must not appear on required (non-null without a default) arguments - or input object field definitions. - */ -@Internal -public class DeprecatedInputObjectAndArgumentsAreValid extends GraphQLTypeVisitorStub { - - @Override - public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField inputObjectField, TraverserContext context) { - // There can only be at most one @deprecated, because it is not a repeatable directive - GraphQLAppliedDirective deprecatedDirective = inputObjectField.getAppliedDirective(Directives.DEPRECATED_DIRECTIVE_DEFINITION.getName()); - - if (deprecatedDirective != null && GraphQLTypeUtil.isNonNull(inputObjectField.getType()) && !inputObjectField.hasSetDefaultValue()) { - GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) context.getParentNode(); - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - String message = format("Required input field '%s.%s' cannot be deprecated.", inputObjectType.getName(), inputObjectField.getName()); - errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.RequiredInputFieldCannotBeDeprecated, message)); - } - return TraversalControl.CONTINUE; - } - - // An argument can appear as either a field argument or a directive argument. This visitor will visit both field arguments and directive arguments. - // An applied directive's argument cannot be deprecated. - @Override - public TraversalControl visitGraphQLArgument(GraphQLArgument argument, TraverserContext context) { - // even if an argument is built using SLD or direct via code, the isDeprecated() method works - boolean isDeprecated = argument.isDeprecated(); - if (isDeprecated && GraphQLTypeUtil.isNonNull(argument.getType()) && !argument.hasSetDefaultValue()) { - if (context.getParentNode() instanceof GraphQLFieldDefinition) { - GraphQLFieldDefinition fieldDefinition = (GraphQLFieldDefinition) context.getParentNode(); - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - String message = format("Required argument '%s' on field '%s' cannot be deprecated.", argument.getName(), fieldDefinition.getName()); - errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.RequiredFieldArgumentCannotBeDeprecated, message)); - } else if (context.getParentNode() instanceof GraphQLDirective) { - GraphQLDirective directive = (GraphQLDirective) context.getParentNode(); - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - String message = format("Required argument '%s' on directive '%s' cannot be deprecated.", argument.getName(), directive.getName()); - errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.RequiredDirectiveArgumentCannotBeDeprecated, message)); - } - } - return TraversalControl.CONTINUE; - } - -} diff --git a/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java b/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java deleted file mode 100644 index 6ee43aef18..0000000000 --- a/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java +++ /dev/null @@ -1,90 +0,0 @@ -package graphql.schema.validation; - -import graphql.Internal; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputType; -import graphql.schema.GraphQLModifiedType; -import graphql.schema.GraphQLOutputType; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeUtil; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import java.util.function.BiFunction; -import java.util.function.Predicate; - -/** - * Schema validation rule ensuring no input type forms an unbroken non-nullable recursion, - * as such a type would be impossible to satisfy - */ -@Internal -public class InputAndOutputTypesUsedAppropriately extends GraphQLTypeVisitorStub { - - @Override - public TraversalControl visitGraphQLFieldDefinition(GraphQLFieldDefinition fieldDef, TraverserContext context) { - String typeName = getTypeName((GraphQLType) context.getParentNode()); - String fieldName = typeName + "." + fieldDef.getName(); - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - for (GraphQLArgument argument : fieldDef.getArguments()) { - String argName = fieldName + "." + argument.getName(); - GraphQLInputType argumentType = argument.getType(); - checkIsAllInputTypes(argumentType, validationErrorCollector, argName); - } - checkIsAllOutputTypes(fieldDef.getType(), validationErrorCollector, fieldName); - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField fieldDef, TraverserContext context) { - String typeName = getTypeName((GraphQLType) context.getParentNode()); - String fieldName = typeName + "." + fieldDef.getName(); - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - checkIsAllInputTypes(fieldDef.getType(), validationErrorCollector, fieldName); - return TraversalControl.CONTINUE; - } - - private void checkIsAllInputTypes(GraphQLInputType inputType, - SchemaValidationErrorCollector validationErrorCollector, - String argName) { - checkTypeContext(inputType, validationErrorCollector, argName, - typeToCheck -> typeToCheck instanceof GraphQLInputType, - (typeToCheck, path) -> new SchemaValidationError(SchemaValidationErrorType.OutputTypeUsedInInputTypeContext, - String.format("The output type '%s' has been used in an input type context : '%s'", typeToCheck, path))); - } - - private void checkIsAllOutputTypes(GraphQLOutputType outputType, - SchemaValidationErrorCollector validationErrorCollector, - String fieldName) { - checkTypeContext(outputType, validationErrorCollector, fieldName, - typeToCheck -> typeToCheck instanceof GraphQLOutputType, - (typeToCheck, path) -> new SchemaValidationError(SchemaValidationErrorType.InputTypeUsedInOutputTypeContext, - String.format("The input type '%s' has been used in a output type context : '%s'", typeToCheck, path))); - } - - private void checkTypeContext(GraphQLType type, - SchemaValidationErrorCollector validationErrorCollector, - String path, - Predicate typePredicate, - BiFunction errorMaker) { - while (true) { - String typeName = getTypeName(type); - boolean isOk = typePredicate.test(type); - if (!isOk) { - validationErrorCollector.addError(errorMaker.apply(typeName, path)); - } - if (type instanceof GraphQLModifiedType) { - type = ((GraphQLModifiedType) type).getWrappedType(); - } else { - return; - } - } - } - - private String getTypeName(GraphQLType type) { - return GraphQLTypeUtil.simplePrint(type); - } -} diff --git a/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java b/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java deleted file mode 100644 index d33d4526a1..0000000000 --- a/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java +++ /dev/null @@ -1,239 +0,0 @@ -package graphql.schema.validation; - -import graphql.Internal; -import graphql.language.ArrayValue; -import graphql.language.ObjectField; -import graphql.language.ObjectValue; -import graphql.language.Value; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.schema.InputValueWithState; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static graphql.schema.GraphQLTypeUtil.unwrapAll; - -/** - * Validates that {@code InputObjectDefaultValueHasCycle(inputObject)} is {@code false} - * for every input object type, as required by the Input Object type validation rules - * in the GraphQL specification. - *
- * For example, consider this type configuration: - * - * input A { b:B = {} } - * input B { a:A = {} } - * - *
- * The default values used in these types form a cycle that can create an infinitely large - * value. This validator rejects default values that can create these kinds of cycles. - * - * @see Input Objects Type Validation - */ -@Internal -public class NoDefaultValueCircularRefs extends GraphQLTypeVisitorStub { - - // Coordinates already fully traversed without finding a cycle, used to avoid duplicate error reports - // when the same coordinate is reachable from multiple input object types. - private final Set fullyExplored = new LinkedHashSet<>(); - - // The spec's "visitedFields" set, tracked as coordinate strings ("Type.field"). - // The spec creates a new immutable set at each step; this implementation mutates and backtracks - // for the same effect. - private final LinkedHashSet visitedFields = new LinkedHashSet<>(); - - @Override - public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType type, TraverserContext context) { - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - - // Implements InputObjectDefaultValueHasCycle(inputObject) from the spec: - // "If defaultValue is not provided, initialize it to an empty unordered map." - inputObjectDefaultValueHasCycle(type, ObjectValue.newObjectValue().build(), errorCollector); - - return TraversalControl.CONTINUE; - } - - /** - * Implements {@code InputObjectDefaultValueHasCycle(inputObject, defaultValue, visitedFields)} - * from the spec, for literal (AST) default values. - */ - private void inputObjectDefaultValueHasCycle( - GraphQLInputObjectType inputObject, - Value defaultValue, - SchemaValidationErrorCollector errorCollector - ) { - // "If defaultValue is a list: for each itemValue in defaultValue..." - if (defaultValue instanceof ArrayValue) { - for (Value itemValue : ((ArrayValue) defaultValue).getValues()) { - inputObjectDefaultValueHasCycle(inputObject, itemValue, errorCollector); - } - return; - } - - // "Otherwise, if defaultValue is an unordered map..." - if (!(defaultValue instanceof ObjectValue)) { - return; - } - - ObjectValue objectValue = (ObjectValue) defaultValue; - Map> defaultValueMap = new LinkedHashMap<>(); - for (ObjectField field : objectValue.getObjectFields()) { - defaultValueMap.put(field.getName(), field.getValue()); - } - - // "For each field in inputObject: if InputFieldDefaultValueHasCycle(...)" - for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { - String fieldName = field.getName(); - boolean hasDefaultValue = defaultValueMap.containsKey(fieldName); - if (!hasDefaultValue && field.getInputFieldDefaultValue().isNotSet()) { - continue; - } - - GraphQLType namedFieldType = unwrapAll(field.getType()); - if (!(namedFieldType instanceof GraphQLInputObjectType)) { - continue; - } - - GraphQLInputObjectType fieldInputObject = (GraphQLInputObjectType) namedFieldType; - if (hasDefaultValue) { - // "Let fieldDefaultValue be the value for fieldName in defaultValue. - // If fieldDefaultValue exists: InputObjectDefaultValueHasCycle(namedFieldType, fieldDefaultValue, visitedFields)" - inputObjectDefaultValueHasCycle(fieldInputObject, defaultValueMap.get(fieldName), errorCollector); - } else { - // "Otherwise: let fieldDefaultValue be the default value of field..." - inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), errorCollector); - } - } - } - - /** - * Implements {@code InputObjectDefaultValueHasCycle(inputObject, defaultValue, visitedFields)} - * from the spec, for external (programmatic Map/List) default values. - */ - private void inputObjectDefaultValueHasCycle( - GraphQLInputObjectType inputObject, - Object defaultValue, - SchemaValidationErrorCollector errorCollector - ) { - // "If defaultValue is a list: for each itemValue in defaultValue..." - if (defaultValue instanceof Iterable) { - for (Object itemValue : (Iterable) defaultValue) { - if (itemValue != null) { - inputObjectDefaultValueHasCycle(inputObject, itemValue, errorCollector); - } - } - return; - } - - // "Otherwise, if defaultValue is an unordered map..." - if (!(defaultValue instanceof Map)) { - return; - } - - @SuppressWarnings("unchecked") - Map defaultValueMap = (Map) defaultValue; - - // "For each field in inputObject: if InputFieldDefaultValueHasCycle(...)" - for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { - String fieldName = field.getName(); - boolean hasDefaultValue = defaultValueMap.containsKey(fieldName); - if (!hasDefaultValue && field.getInputFieldDefaultValue().isNotSet()) { - continue; - } - - GraphQLType namedFieldType = unwrapAll(field.getType()); - if (!(namedFieldType instanceof GraphQLInputObjectType)) { - continue; - } - - GraphQLInputObjectType fieldInputObject = (GraphQLInputObjectType) namedFieldType; - if (hasDefaultValue) { - // "Let fieldDefaultValue be the value for fieldName in defaultValue. - // If fieldDefaultValue exists: InputObjectDefaultValueHasCycle(namedFieldType, fieldDefaultValue, visitedFields)" - Object fieldDefaultValue = defaultValueMap.get(fieldName); - if (fieldDefaultValue != null) { - inputObjectDefaultValueHasCycle(fieldInputObject, fieldDefaultValue, errorCollector); - } - } else { - // "Otherwise: let fieldDefaultValue be the default value of field..." - inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), errorCollector); - } - } - } - - /** - * Implements the "Otherwise" branch of {@code InputFieldDefaultValueHasCycle(field, defaultValue, visitedFields)} - * from the spec — called when the field is not present in the parent's default value, - * so the field's own default will be used at runtime. - */ - private void inputFieldDefaultValueHasCycle( - GraphQLInputObjectField field, - GraphQLInputObjectType namedFieldType, - String parentTypeName, - SchemaValidationErrorCollector errorCollector - ) { - // "Let fieldDefaultValue be the default value of field. - // If fieldDefaultValue does not exist: return false." - InputValueWithState fieldDefaultValue = field.getInputFieldDefaultValue(); - if (fieldDefaultValue.isNotSet()) { - return; - } - - String coordinate = parentTypeName + "." + field.getName(); - - // "If field is within visitedFields: return true." - if (visitedFields.contains(coordinate)) { - // Cycle found — collect intermediate nodes (everything after the coordinate itself) - List intermediaries = new ArrayList<>(); - boolean found = false; - for (String entry : visitedFields) { - if (found) { - intermediaries.add(entry); - } - if (entry.equals(coordinate)) { - found = true; - } - } - - String message; - if (intermediaries.isEmpty()) { - message = "Invalid circular reference. The default value of Input Object field " - + coordinate + " references itself."; - } else { - message = "Invalid circular reference. The default value of Input Object field " - + coordinate + " references itself via the default values of: " - + String.join(", ", intermediaries) + "."; - } - - errorCollector.addError(new SchemaValidationError( - SchemaValidationErrorType.DefaultValueCircularRef, message)); - return; - } - - if (fullyExplored.contains(coordinate)) { - return; - } - fullyExplored.add(coordinate); - - // "Let nextVisitedFields be a new set containing field and everything from visitedFields. - // Return InputObjectDefaultValueHasCycle(namedFieldType, fieldDefaultValue, nextVisitedFields)." - visitedFields.add(coordinate); - - if (fieldDefaultValue.isLiteral() && fieldDefaultValue.getValue() instanceof Value) { - inputObjectDefaultValueHasCycle(namedFieldType, (Value) fieldDefaultValue.getValue(), errorCollector); - } else if (fieldDefaultValue.isExternal() && fieldDefaultValue.getValue() != null) { - inputObjectDefaultValueHasCycle(namedFieldType, fieldDefaultValue.getValue(), errorCollector); - } - - visitedFields.remove(coordinate); - } -} diff --git a/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java b/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java deleted file mode 100644 index 9eb061d070..0000000000 --- a/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java +++ /dev/null @@ -1,84 +0,0 @@ -package graphql.schema.validation; - -import graphql.Internal; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLInputType; -import graphql.schema.GraphQLNonNull; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import static graphql.schema.GraphQLTypeUtil.isList; -import static graphql.schema.GraphQLTypeUtil.isNonNull; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; - -/** - * Schema validation rule ensuring no input type forms an unbroken non-nullable recursion, - * as such a type would be impossible to satisfy - */ -@Internal -public class NoUnbrokenInputCycles extends GraphQLTypeVisitorStub { - - @Override - public TraversalControl visitGraphQLFieldDefinition(GraphQLFieldDefinition fieldDef, TraverserContext context) { - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - for (GraphQLArgument argument : fieldDef.getArguments()) { - GraphQLInputType argumentType = argument.getType(); - if (argumentType instanceof GraphQLInputObjectType) { - List path = new ArrayList<>(); - check((GraphQLInputObjectType) argumentType, new LinkedHashSet<>(), path, validationErrorCollector); - } - } - return TraversalControl.CONTINUE; - } - - private void check(GraphQLInputObjectType type, Set seen, List path, SchemaValidationErrorCollector validationErrorCollector) { - if (seen.contains(type)) { - validationErrorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.UnbrokenInputCycle, getErrorMessage(path))); - return; - } - seen.add(type); - - for (GraphQLInputObjectField field : type.getFieldDefinitions()) { - if (isNonNull(field.getType())) { - GraphQLType unwrapped = unwrapNonNull((GraphQLNonNull) field.getType()); - if (unwrapped instanceof GraphQLInputObjectType) { - path = new ArrayList<>(path); - path.add(field.getName() + "!"); - check((GraphQLInputObjectType) unwrapped, new LinkedHashSet<>(seen), path, validationErrorCollector); - } - } - } - } - - private GraphQLType unwrapNonNull(GraphQLNonNull type) { - GraphQLType wrappedType = type.getWrappedType(); - if (isList(wrappedType)) { - return wrappedType; - } - return unwrapAll(wrappedType); - } - - private String getErrorMessage(List path) { - StringBuilder message = new StringBuilder(); - message.append("["); - for (int i = 0; i < path.size(); i++) { - if (i != 0) { - message.append("."); - } - message.append(path.get(i)); - } - message.append("] forms an unsatisfiable cycle"); - return message.toString(); - } -} diff --git a/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java b/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java deleted file mode 100644 index 72e1aba67c..0000000000 --- a/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java +++ /dev/null @@ -1,88 +0,0 @@ -package graphql.schema.validation; - -import graphql.ExperimentalApi; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeUtil; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.schema.GraphQLUnmodifiedType; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; -import org.jspecify.annotations.NullMarked; - -import java.util.LinkedHashSet; -import java.util.Set; - -import static graphql.Assert.assertNotNull; -import static java.lang.String.format; - -/* - * Spec: If the Input Object is a OneOf Input Object then: - * The type of the input field must be nullable. - * The input field must not have a default value. - */ -@NullMarked -@ExperimentalApi -public class OneOfInputObjectRules extends GraphQLTypeVisitorStub { - - @Override - public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType inputObjectType, TraverserContext context) { - if (!inputObjectType.isOneOf()) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - if (!canBeProvidedAFiniteValue(inputObjectType, new LinkedHashSet<>())) { - String message = format("OneOf Input Object %s must be inhabited but all fields recursively reference only other OneOf Input Objects forming an unresolvable cycle.", inputObjectType.getName()); - assertNotNull(errorCollector, "Schema validation requires an error collector").addError(new SchemaValidationError(SchemaValidationErrorType.OneOfNotInhabited, message)); - } - return TraversalControl.CONTINUE; - } - - private boolean canBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { - if (visited.contains(oneOfInputObject)) { - return false; - } - Set nextVisited = new LinkedHashSet<>(visited); - nextVisited.add(oneOfInputObject); - for (GraphQLInputObjectField field : oneOfInputObject.getFieldDefinitions()) { - GraphQLType fieldType = field.getType(); - if (GraphQLTypeUtil.isList(fieldType)) { - return true; - } - GraphQLUnmodifiedType namedFieldType = GraphQLTypeUtil.unwrapAll(fieldType); - if (!(namedFieldType instanceof GraphQLInputObjectType)) { - return true; - } - GraphQLInputObjectType inputFieldType = (GraphQLInputObjectType) namedFieldType; - if (!inputFieldType.isOneOf()) { - return true; - } - if (canBeProvidedAFiniteValue(inputFieldType, nextVisited)) { - return true; - } - } - return false; - } - - @Override - public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField inputObjectField, TraverserContext context) { - GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) assertNotNull(context.getParentNode(), "Input field validation requires its containing input object"); - if (!inputObjectType.isOneOf()) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - // error messages take from the reference implementation - if (inputObjectField.hasSetDefaultValue()) { - String message = format("OneOf input field %s.%s cannot have a default value.", inputObjectType.getName(), inputObjectField.getName()); - assertNotNull(errorCollector, "Schema validation requires an error collector").addError(new SchemaValidationError(SchemaValidationErrorType.OneOfDefaultValueOnField, message)); - } - - if (GraphQLTypeUtil.isNonNull(inputObjectField.getType())) { - String message = format("OneOf input field %s.%s must be nullable.", inputObjectType.getName(), inputObjectField.getName()); - assertNotNull(errorCollector, "Schema validation requires an error collector").addError(new SchemaValidationError(SchemaValidationErrorType.OneOfNonNullableField, message)); - } - return TraversalControl.CONTINUE; - } -} diff --git a/src/main/java/graphql/schema/validation/SchemaValidator.java b/src/main/java/graphql/schema/validation/SchemaValidator.java index 815cfd4403..e50944d910 100644 --- a/src/main/java/graphql/schema/validation/SchemaValidator.java +++ b/src/main/java/graphql/schema/validation/SchemaValidator.java @@ -1,51 +1,771 @@ package graphql.schema.validation; +import graphql.Directives; +import graphql.GraphQLContext; import graphql.Internal; import graphql.execution.InputValueLimits; +import graphql.execution.NonNullableValueCoercedAsNullException; +import graphql.execution.ValuesResolver; +import graphql.language.ArrayValue; +import graphql.language.ObjectField; +import graphql.language.ObjectValue; +import graphql.language.Value; +import graphql.schema.CoercingParseValueException; +import graphql.schema.GraphQLAppliedDirective; +import graphql.schema.GraphQLAppliedDirectiveArgument; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLDirective; +import graphql.schema.GraphQLDirectiveContainer; +import graphql.schema.GraphQLEnumType; +import graphql.schema.GraphQLEnumValueDefinition; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.GraphQLImplementingType; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInputType; +import graphql.schema.GraphQLInterfaceType; +import graphql.schema.GraphQLModifiedType; +import graphql.schema.GraphQLNamedOutputType; +import graphql.schema.GraphQLNamedType; +import graphql.schema.GraphQLNonNull; +import graphql.schema.GraphQLObjectType; +import graphql.schema.GraphQLOutputType; +import graphql.schema.GraphQLScalarType; import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLTypeVisitor; -import graphql.schema.SchemaTraverser; +import graphql.schema.GraphQLSchemaElement; +import graphql.schema.GraphQLType; +import graphql.schema.GraphQLUnionType; +import graphql.schema.InputValueWithState; +import graphql.validation.ValidationUtil; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; +import static graphql.introspection.Introspection.INTROSPECTION_SYSTEM_FIELDS; +import static graphql.introspection.Introspection.isIntrospectionTypes; +import static graphql.schema.GraphQLTypeUtil.isList; +import static graphql.schema.GraphQLTypeUtil.isNonNull; +import static graphql.schema.GraphQLTypeUtil.simplePrint; +import static graphql.schema.GraphQLTypeUtil.unwrapAll; +import static graphql.schema.GraphQLTypeUtil.unwrapOne; +import static graphql.schema.validation.SchemaValidationErrorType.ObjectDoesNotImplementItsInterfaces; +import static java.lang.String.format; + @Internal +@NullMarked public class SchemaValidator { + private static final String DEPRECATED_DIRECTIVE_NAME = Directives.DEPRECATED_DIRECTIVE_DEFINITION.getName(); + + private final ValidationUtil validationUtil = new ValidationUtil(); - private final List rules = new ArrayList<>(); + public Set validateSchema(GraphQLSchema schema) { + GraphQLContext context = GraphQLContext.getDefault(); + SchemaValidationErrorCollector errors = new SchemaValidationErrorCollector(); + new DefaultValueDepth(InputValueLimits.getDefaultLimits().getMaxDepth()).check(schema, errors); + if (!errors.getErrors().isEmpty()) { + return errors.getErrors(); + } + // unbroken input cycle results only depend on the argument's input type, so each type is explored once + Set checkedCycleRoots = newIdentitySet(); - public SchemaValidator() { - rules.add(new NoUnbrokenInputCycles()); - rules.add(new NoDefaultValueCircularRefs()); - rules.add(new TypesImplementInterfaces()); - rules.add(new TypeAndFieldRule()); - rules.add(new DefaultValuesAreValid()); - rules.add(new AppliedDirectivesAreValid()); - rules.add(new AppliedDirectiveArgumentsAreValid()); - rules.add(new InputAndOutputTypesUsedAppropriately()); - rules.add(new OneOfInputObjectRules()); - rules.add(new DeprecatedInputObjectAndArgumentsAreValid()); + List types = schema.getAllTypesAsList(); + checkDefaultValueCycles(types, errors); + for (GraphQLNamedType type : types) { + if (type instanceof GraphQLObjectType) { + validateObjectType((GraphQLObjectType) type, checkedCycleRoots, schema, context, errors); + } else if (type instanceof GraphQLInterfaceType) { + validateInterfaceType((GraphQLInterfaceType) type, checkedCycleRoots, schema, context, errors); + } else if (type instanceof GraphQLInputObjectType) { + validateInputObjectType((GraphQLInputObjectType) type, schema, context, errors); + } else if (type instanceof GraphQLEnumType) { + validateEnumType((GraphQLEnumType) type, schema, context, errors); + } else if (type instanceof GraphQLUnionType) { + validateUnionType((GraphQLUnionType) type, schema, context, errors); + } else if (type instanceof GraphQLScalarType) { + checkDirectiveContainer((GraphQLScalarType) type, schema, context, errors); + } + } + for (GraphQLDirective directive : schema.getDirectives()) { + validateDirectiveDefinition(directive, schema, context, errors); + } + return errors.getErrors(); } - public List getRules() { - return rules; + private Set newIdentitySet() { + return Collections.newSetFromMap(new IdentityHashMap<>()); } - public Set validateSchema(GraphQLSchema schema) { - SchemaValidationErrorCollector validationErrorCollector = new SchemaValidationErrorCollector(); - new DefaultValueDepth(InputValueLimits.getDefaultLimits().getMaxDepth()).check(schema, validationErrorCollector); - if (!validationErrorCollector.getErrors().isEmpty()) { - return validationErrorCollector.getErrors(); + private void validateObjectType(GraphQLObjectType type, Set checkedCycleRoots, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + List fieldDefinitions = type.getFieldDefinitions(); + checkImplementsInterfaces(type, errors); + if (!isIntrospectionTypes(type)) { + checkFieldsContainer(type, fieldDefinitions, errors); + } + checkDirectiveContainer(type, schema, context, errors); + for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { + validateFieldDefinition(type, fieldDefinition, checkedCycleRoots, schema, context, errors); + } + } + + private void validateInterfaceType(GraphQLInterfaceType type, Set checkedCycleRoots, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + List fieldDefinitions = type.getFieldDefinitions(); + checkImplementsInterfaces(type, errors); + checkFieldsContainer(type, fieldDefinitions, errors); + checkDirectiveContainer(type, schema, context, errors); + for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { + validateFieldDefinition(type, fieldDefinition, checkedCycleRoots, schema, context, errors); + } + } + + private void validateUnionType(GraphQLUnionType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + if (!isIntrospectionTypes(type)) { + checkUnion(type, errors); + } + checkDirectiveContainer(type, schema, context, errors); + } + + private void validateEnumType(GraphQLEnumType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + List values = type.getValues(); + if (!isIntrospectionTypes(type)) { + checkEnum(type, values, errors); + } + checkDirectiveContainer(type, schema, context, errors); + for (GraphQLEnumValueDefinition value : values) { + checkDirectiveContainer(value, schema, context, errors); + } + } + + private void validateInputObjectType(GraphQLInputObjectType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + List fields = type.getFieldDefinitions(); + if (!isIntrospectionTypes(type)) { + checkInputObject(type, fields, errors); + } + checkDirectiveContainer(type, schema, context, errors); + checkOneOfInhabited(type, errors); + for (GraphQLInputObjectField field : fields) { + validateInputObjectField(type, field, schema, context, errors); + } + } + + private void validateFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition, Set checkedCycleRoots, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + checkNoUnbrokenInputCycles(fieldDefinition, checkedCycleRoots, errors); + checkDirectiveContainer(fieldDefinition, schema, context, errors); + checkFieldTypesUsedAppropriately(container, fieldDefinition, errors); + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + validateArgument(argument, fieldDefinition, schema, context, errors); + } + } + + private void validateInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField field, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + if (field.hasSetDefaultValue()) { + checkDefaultValue(field.getInputFieldDefaultValue(), field.getType(), schema, context, errors); + } + checkDirectiveContainer(field, schema, context, errors); + checkInputFieldTypeUsedAppropriately(type, field, errors); + checkOneOfField(type, field, errors); + checkDeprecatedInputField(type, field, errors); + } + + private void validateArgument(GraphQLArgument argument, GraphQLSchemaElement fieldOrDirective, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + if (argument.hasSetDefaultValue()) { + checkDefaultValue(argument.getArgumentDefaultValue(), argument.getType(), schema, context, errors); + } + checkDirectiveContainer(argument, schema, context, errors); + checkDeprecatedArgument(argument, fieldOrDirective, errors); + } + + private void validateDirectiveDefinition(GraphQLDirective directive, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + checkDirectiveContainer(directive, schema, context, errors); + for (GraphQLArgument argument : directive.getArguments()) { + validateArgument(argument, directive, schema, context, errors); + } + } + + private void checkDirectiveContainer(GraphQLDirectiveContainer container, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + checkAppliedDirectives(container, schema, errors); + for (GraphQLDirective directive : container.getDirectives()) { + for (GraphQLArgument argument : directive.getArguments()) { + checkAppliedDirectiveArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType(), schema, context, errors); + } + } + for (GraphQLAppliedDirective directive : container.getAppliedDirectives()) { + for (GraphQLAppliedDirectiveArgument argument : directive.getArguments()) { + checkAppliedDirectiveArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType(), schema, context, errors); + } + } + } + + private void addError(SchemaValidationErrorCollector errors, SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); + } + + private void checkNoUnbrokenInputCycles(GraphQLFieldDefinition fieldDefinition, Set checkedCycleRoots, SchemaValidationErrorCollector errors) { + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + GraphQLInputType argumentType = argument.getType(); + if (argumentType instanceof GraphQLInputObjectType && checkedCycleRoots.add((GraphQLInputObjectType) argumentType)) { + checkUnbrokenInputCycle((GraphQLInputObjectType) argumentType, newIdentitySet(), new ArrayList<>(), errors); + } + } + } + + // path entries deliberately accumulate across sibling fields, which existing error messages rely on + private void checkUnbrokenInputCycle(GraphQLInputObjectType type, Set pathTypes, List path, SchemaValidationErrorCollector errors) { + if (!pathTypes.add(type)) { + addError(errors, SchemaValidationErrorType.UnbrokenInputCycle, "[" + String.join(".", path) + "] forms an unsatisfiable cycle"); + return; + } + int pathSizeOnEntry = path.size(); + for (GraphQLInputObjectField field : type.getFieldDefinitions()) { + GraphQLInputObjectType next = nonNullInputObjectType(field.getType()); + if (next != null) { + path.add(field.getName() + "!"); + checkUnbrokenInputCycle(next, pathTypes, path, errors); + } + } + path.subList(pathSizeOnEntry, path.size()).clear(); + pathTypes.remove(type); + } + + private @Nullable GraphQLInputObjectType nonNullInputObjectType(GraphQLInputType type) { + if (!(type instanceof GraphQLNonNull)) { + return null; + } + GraphQLType wrappedType = ((GraphQLNonNull) type).getWrappedType(); + if (isList(wrappedType)) { + return null; + } + GraphQLType unwrapped = unwrapAll(wrappedType); + return unwrapped instanceof GraphQLInputObjectType ? (GraphQLInputObjectType) unwrapped : null; + } + + private void checkDefaultValueCycles(List types, SchemaValidationErrorCollector errors) { + // coordinates already explored, so each cycle is reported only once + Set exploredDefaults = new LinkedHashSet<>(); + for (GraphQLNamedType type : types) { + if (type instanceof GraphQLInputObjectType) { + checkNoDefaultValueCircularRefs((GraphQLInputObjectType) type, exploredDefaults, errors); + } + } + } + + private void checkNoDefaultValueCircularRefs(GraphQLInputObjectType type, Set exploredDefaults, SchemaValidationErrorCollector errors) { + @Nullable LinkedHashSet visitedFields = null; + // equivalent to InputObjectDefaultValueHasCycle(type, {}) without building the empty map + for (GraphQLInputObjectField field : type.getFieldDefinitions()) { + if (field.getInputFieldDefaultValue().isNotSet()) { + continue; + } + GraphQLType namedFieldType = unwrapAll(field.getType()); + if (namedFieldType instanceof GraphQLInputObjectType) { + visitedFields = visitedFields == null ? new LinkedHashSet<>() : visitedFields; + inputFieldDefaultValueHasCycle(field, (GraphQLInputObjectType) namedFieldType, type.getName(), exploredDefaults, visitedFields, errors); + } + } + } + + private void literalDefaultValueHasCycle(GraphQLInputObjectType inputObject, @Nullable Value defaultValue, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { + if (defaultValue instanceof ArrayValue) { + for (Value itemValue : ((ArrayValue) defaultValue).getValues()) { + literalDefaultValueHasCycle(inputObject, itemValue, exploredDefaults, visitedFields, errors); + } + return; + } + if (!(defaultValue instanceof ObjectValue)) { + return; + } + Map> defaultValueMap = new LinkedHashMap<>(); + for (ObjectField field : ((ObjectValue) defaultValue).getObjectFields()) { + defaultValueMap.put(field.getName(), field.getValue()); + } + for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { + boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); + if (fieldInputObject == null) { + continue; + } + if (hasDefaultValue) { + literalDefaultValueHasCycle(fieldInputObject, defaultValueMap.get(field.getName()), exploredDefaults, visitedFields, errors); + } else { + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), exploredDefaults, visitedFields, errors); + } + } + } + + private void externalDefaultValueHasCycle(GraphQLInputObjectType inputObject, Object defaultValue, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { + if (defaultValue instanceof Iterable) { + externalListDefaultValueHasCycle(inputObject, (Iterable) defaultValue, exploredDefaults, visitedFields, errors); + return; + } + if (!(defaultValue instanceof Map)) { + return; + } + Map defaultValueMap = (Map) defaultValue; + for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { + boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); + if (fieldInputObject == null) { + continue; + } + if (!hasDefaultValue) { + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), exploredDefaults, visitedFields, errors); + continue; + } + Object fieldDefaultValue = defaultValueMap.get(field.getName()); + if (fieldDefaultValue != null) { + externalDefaultValueHasCycle(fieldInputObject, fieldDefaultValue, exploredDefaults, visitedFields, errors); + } + } + } + + private void externalListDefaultValueHasCycle(GraphQLInputObjectType inputObject, Iterable defaultValues, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { + for (Object itemValue : defaultValues) { + if (itemValue != null) { + externalDefaultValueHasCycle(inputObject, itemValue, exploredDefaults, visitedFields, errors); + } + } + } + + private @Nullable GraphQLInputObjectType inputObjectTypeWithDefault(GraphQLInputObjectField field, boolean hasDefaultInParent) { + if (!hasDefaultInParent && field.getInputFieldDefaultValue().isNotSet()) { + return null; + } + GraphQLType namedFieldType = unwrapAll(field.getType()); + return namedFieldType instanceof GraphQLInputObjectType ? (GraphQLInputObjectType) namedFieldType : null; + } + + private void inputFieldDefaultValueHasCycle(GraphQLInputObjectField field, GraphQLInputObjectType namedFieldType, String parentTypeName, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { + InputValueWithState fieldDefaultValue = field.getInputFieldDefaultValue(); + String coordinate = parentTypeName + "." + field.getName(); + if (visitedFields.contains(coordinate)) { + addError(errors, SchemaValidationErrorType.DefaultValueCircularRef, defaultValueCycleMessage(coordinate, visitedFields)); + return; + } + if (!exploredDefaults.add(coordinate)) { + return; + } + visitedFields.add(coordinate); + if (fieldDefaultValue.isLiteral() && fieldDefaultValue.getValue() instanceof Value) { + literalDefaultValueHasCycle(namedFieldType, (Value) fieldDefaultValue.getValue(), exploredDefaults, visitedFields, errors); + } else if (fieldDefaultValue.isExternal() && fieldDefaultValue.getValue() != null) { + externalDefaultValueHasCycle(namedFieldType, fieldDefaultValue.getValue(), exploredDefaults, visitedFields, errors); + } + visitedFields.remove(coordinate); + } + + private String defaultValueCycleMessage(String coordinate, LinkedHashSet visitedFields) { + List intermediaries = new ArrayList<>(); + boolean found = false; + for (String entry : visitedFields) { + if (found) { + intermediaries.add(entry); + } + if (entry.equals(coordinate)) { + found = true; + } + } + if (intermediaries.isEmpty()) { + return "Invalid circular reference. The default value of Input Object field " + + coordinate + " references itself."; + } + return "Invalid circular reference. The default value of Input Object field " + + coordinate + " references itself via the default values of: " + + String.join(", ", intermediaries) + "."; + } + + private void checkImplementsInterfaces(GraphQLImplementingType implementingType, SchemaValidationErrorCollector errors) { + List interfaces = implementingType.getInterfaces(); + for (GraphQLNamedOutputType interfaceType : interfaces) { + checkObjectImplementsInterface(implementingType, (GraphQLInterfaceType) interfaceType, errors); + } + } + + private void checkObjectImplementsInterface(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector errors) { + for (GraphQLFieldDefinition interfaceFieldDef : interfaceType.getFieldDefinitions()) { + GraphQLFieldDefinition objectFieldDef = implementingType.getFieldDefinition(interfaceFieldDef.getName()); + if (objectFieldDef == null) { + addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' is missing", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName())); + } else { + checkFieldTypeCompatibility(implementingType, interfaceType, interfaceFieldDef, objectFieldDef, errors); + } + } + checkTransitiveImplementations(implementingType, interfaceType, errors); + } + + private void checkTransitiveImplementations(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector errors) { + List implementedInterfaces = implementingType.getInterfaces(); + for (GraphQLNamedOutputType transitiveInterface : interfaceType.getInterfaces()) { + if (transitiveInterface.equals(implementingType)) { + addInterfaceError(errors, format("%s type '%s' cannot implement '%s' because that would result on a circular reference", + typeOf(implementingType), implementingType.getName(), interfaceType.getName())); + } else if (!implementedInterfaces.contains(transitiveInterface)) { + addInterfaceError(errors, format("%s type '%s' must implement '%s' because it is implemented by '%s'", + typeOf(implementingType), implementingType.getName(), transitiveInterface.getName(), interfaceType.getName())); + } + } + } + + private void checkFieldTypeCompatibility(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef, SchemaValidationErrorCollector errors) { + if (isCompatible(interfaceFieldDef.getType(), objectFieldDef.getType())) { + checkFieldArgumentEquivalence(implementingType, interfaceType, interfaceFieldDef, objectFieldDef, errors); + return; + } + addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' is defined as '%s' type and not as '%s' type", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), + simplePrint(objectFieldDef.getType()), simplePrint(interfaceFieldDef.getType()))); + } + + private void checkFieldArgumentEquivalence(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef, SchemaValidationErrorCollector errors) { + List interfaceArgs = interfaceFieldDef.getArguments(); + for (GraphQLArgument interfaceArg : interfaceArgs) { + if (objectFieldDef.getArgument(interfaceArg.getName()) == null) { + addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' is missing argument(s): '%s'", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), + missingArgumentNames(interfaceArgs, objectFieldDef))); + return; + } + } + for (GraphQLArgument objectArg : objectFieldDef.getArguments()) { + GraphQLArgument interfaceArg = interfaceFieldDef.getArgument(objectArg.getName()); + if (interfaceArg == null) { + checkAdditionalArgumentIsOptional(implementingType, interfaceType, objectFieldDef, objectArg, errors); + } else if (!isSameType(objectArg.getType(), interfaceArg.getType())) { + addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' argument '%s' is defined differently", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), objectArg.getName())); + } + } + } + + private void checkAdditionalArgumentIsOptional(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition objectFieldDef, GraphQLArgument objectArg, SchemaValidationErrorCollector errors) { + if (objectArg.getType() instanceof GraphQLNonNull) { + addInterfaceError(errors, format("%s type '%s' field '%s' defines an additional non-optional argument '%s' which is not allowed because field is also defined in interface '%s'", + typeOf(implementingType), implementingType.getName(), objectFieldDef.getName(), objectArg.getName(), interfaceType.getName())); + } + } + + private String missingArgumentNames(List interfaceArgs, GraphQLFieldDefinition objectFieldDef) { + Set missing = new LinkedHashSet<>(); + for (GraphQLArgument interfaceArg : interfaceArgs) { + if (objectFieldDef.getArgument(interfaceArg.getName()) == null) { + missing.add(interfaceArg.getName()); + } + } + return String.join(", ", missing); + } + + private void addInterfaceError(SchemaValidationErrorCollector errors, String message) { + addError(errors, ObjectDoesNotImplementItsInterfaces, message); + } + + private String typeOf(GraphQLImplementingType implementingType) { + return implementingType instanceof GraphQLObjectType ? "object" : "interface"; + } + + private boolean isCompatible(GraphQLOutputType constraintType, GraphQLOutputType objectType) { + if (isSameType(constraintType, objectType)) { + return true; + } else if (constraintType instanceof GraphQLUnionType) { + return ((GraphQLUnionType) constraintType).getTypes().contains(objectType); + } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLObjectType) { + return ((GraphQLObjectType) objectType).getInterfaces().contains(constraintType); + } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLInterfaceType) { + return ((GraphQLInterfaceType) objectType).getInterfaces().contains(constraintType); + } else if (isList(constraintType) && isList(objectType)) { + return isCompatible((GraphQLOutputType) unwrapOne(constraintType), (GraphQLOutputType) unwrapOne(objectType)); + } else if (isNonNull(objectType)) { + GraphQLOutputType nullableConstraint = isNonNull(constraintType) ? (GraphQLOutputType) unwrapOne(constraintType) : constraintType; + return isCompatible(nullableConstraint, (GraphQLOutputType) unwrapOne(objectType)); + } + return false; + } + + // equivalent to comparing GraphQLTypeUtil.simplePrint() of both types + private boolean isSameType(GraphQLType first, GraphQLType second) { + GraphQLType left = first; + GraphQLType right = second; + while (true) { + boolean leftNonNull = isNonNull(left); + boolean leftList = isList(left); + if (leftNonNull != isNonNull(right) || leftList != isList(right)) { + return false; + } + if (!leftNonNull && !leftList) { + return ((GraphQLNamedType) left).getName().equals(((GraphQLNamedType) right).getName()); + } + left = unwrapOne(left); + right = unwrapOne(right); + } + } + + private void checkFieldsContainer(GraphQLFieldsContainer type, List fieldDefinitions, SchemaValidationErrorCollector errors) { + if (fieldDefinitions.isEmpty()) { + addError(errors, SchemaValidationErrorType.ImplementingTypeLackOfFieldError, format("\"%s\" must define one or more fields.", type.getName())); + return; + } + for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { + checkFieldName(type.getName(), fieldDefinition.getName(), errors); + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + checkArgumentName(type.getName(), fieldDefinition.getName(), argument.getName(), errors); + } + } + } + + private void checkInputObject(GraphQLInputObjectType type, List fields, SchemaValidationErrorCollector errors) { + if (fields.isEmpty()) { + addError(errors, SchemaValidationErrorType.InputObjectTypeLackOfFieldError, format("\"%s\" must define one or more fields.", type.getName())); + return; + } + for (GraphQLInputObjectField field : fields) { + checkFieldName(type.getName(), field.getName(), errors); + } + } + + private void checkUnion(GraphQLUnionType type, SchemaValidationErrorCollector errors) { + List memberTypes = type.getTypes(); + if (memberTypes.isEmpty()) { + addError(errors, SchemaValidationErrorType.UnionTypeLackOfTypeError, format("Union type \"%s\" must include one or more unique member types.", type.getName())); + } + Set typeNames = new LinkedHashSet<>(); + for (GraphQLNamedOutputType memberType : memberTypes) { + if (!(memberType instanceof GraphQLObjectType)) { + addError(errors, SchemaValidationErrorType.InvalidUnionMemberTypeError, + format("The member types of a Union type must all be Object base types. member type \"%s\" in Union \"%s\" is invalid.", memberType.getName(), type.getName())); + } + if (!typeNames.add(memberType.getName())) { + addError(errors, SchemaValidationErrorType.RepetitiveElementError, + format("The member types of a Union type must be unique. member type \"%s\" in Union \"%s\" is not unique.", memberType.getName(), type.getName())); + } + } + } + + private void checkEnum(GraphQLEnumType type, List values, SchemaValidationErrorCollector errors) { + if (values.isEmpty()) { + addError(errors, SchemaValidationErrorType.EnumLackOfValueError, format("Enum type \"%s\" must define one or more enum values.", type.getName())); + return; + } + for (GraphQLEnumValueDefinition value : values) { + if (isReservedName(value.getName())) { + addError(errors, SchemaValidationErrorType.InvalidCustomizedNameError, + format("EnumValueDefinition \"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", value.getName(), type.getName())); + } + } + } + + private void checkFieldName(String typeName, String fieldName, SchemaValidationErrorCollector errors) { + if (isReservedName(fieldName) && !INTROSPECTION_SYSTEM_FIELDS.contains(fieldName)) { + addError(errors, SchemaValidationErrorType.InvalidCustomizedNameError, + format("\"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", fieldName, typeName)); + } + } + + private void checkArgumentName(String typeName, String fieldName, String argumentName, SchemaValidationErrorCollector errors) { + if (isReservedName(argumentName)) { + addError(errors, SchemaValidationErrorType.InvalidCustomizedNameError, + format("Argument name \"%s\" in \"%s-%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", argumentName, typeName, fieldName)); + } + } + + private boolean isReservedName(String name) { + return name.startsWith("__"); + } + + private void checkDefaultValue(InputValueWithState defaultValue, GraphQLInputType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + if (isValidValue(defaultValue, type, schema, context, errors)) { + return; + } + addError(errors, SchemaValidationErrorType.InvalidDefaultValue, + format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(type))); + } + + private void checkAppliedDirectiveArgument(String directiveName, String argumentName, InputValueWithState argumentValue, GraphQLInputType argumentType, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + boolean invalid = !isValidValue(argumentValue, argumentType, schema, context, errors) + || (argumentValue.isNotSet() && isNonNull(argumentType)); + if (invalid) { + addError(errors, SchemaValidationErrorType.InvalidAppliedDirectiveArgument, + format("Invalid argument '%s' for applied directive of name '%s'", argumentName, directiveName)); + } + } + + private boolean isValidValue(InputValueWithState value, GraphQLInputType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { + if (value.isLiteral()) { + return validationUtil.isValidLiteralValue((Value) value.getValue(), type, schema, context, Locale.getDefault()); + } + // coercing external values expands input field defaults, which never terminates once defaults form a cycle + if (!value.isExternal() || errors.containsValidationError(SchemaValidationErrorType.DefaultValueCircularRef)) { + return true; + } + return isValidExternalValue(value.getValue(), type, schema, context); + } + + private boolean isValidExternalValue(@Nullable Object externalValue, GraphQLInputType type, GraphQLSchema schema, GraphQLContext context) { + try { + ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, context, Locale.getDefault()); + return true; + } catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) { + return false; + } + } + + private void checkAppliedDirectives(GraphQLDirectiveContainer container, GraphQLSchema schema, SchemaValidationErrorCollector errors) { + Map> directivesByName = container.getAllDirectivesByName(); + if (directivesByName.isEmpty()) { + return; + } + for (Map.Entry> entry : directivesByName.entrySet()) { + GraphQLDirective directiveDef = schema.getDirective(entry.getKey()); + if (directiveDef == null) { + addError(errors, SchemaValidationErrorType.InvalidAppliedDirective, format("A definition for directive '%s' could not be found", entry.getKey())); + } else if (directiveDef.isNonRepeatable() && entry.getValue().size() > 1) { + addError(errors, SchemaValidationErrorType.InvalidAppliedDirective, + format("The directive '%s' on the '%s' called '%s' is a non repeatable directive but has been applied %d times", + directiveDef.getName(), container.getClass().getSimpleName(), container.getName(), entry.getValue().size())); + } + } + } + + private void checkFieldTypesUsedAppropriately(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition, SchemaValidationErrorCollector errors) { + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + if (hasMisusedType(argument.getType(), true)) { + String path = container.getName() + "." + fieldDefinition.getName() + "." + argument.getName(); + addTypeContextErrors(argument.getType(), true, path, errors); + } + } + if (hasMisusedType(fieldDefinition.getType(), false)) { + String path = container.getName() + "." + fieldDefinition.getName(); + addTypeContextErrors(fieldDefinition.getType(), false, path, errors); + } + } + + private void checkInputFieldTypeUsedAppropriately(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errors) { + if (hasMisusedType(inputObjectField.getType(), true)) { + String path = type.getName() + "." + inputObjectField.getName(); + addTypeContextErrors(inputObjectField.getType(), true, path, errors); + } + } + + private boolean hasMisusedType(GraphQLType type, boolean inputContext) { + GraphQLType current = type; + while (true) { + if (isMisused(current, inputContext)) { + return true; + } + if (!(current instanceof GraphQLModifiedType)) { + return false; + } + current = ((GraphQLModifiedType) current).getWrappedType(); + } + } + + private void addTypeContextErrors(GraphQLType type, boolean inputContext, String path, SchemaValidationErrorCollector errors) { + GraphQLType current = type; + while (true) { + if (isMisused(current, inputContext)) { + addTypeContextError(current, inputContext, path, errors); + } + if (!(current instanceof GraphQLModifiedType)) { + return; + } + current = ((GraphQLModifiedType) current).getWrappedType(); + } + } + + private void addTypeContextError(GraphQLType misusedType, boolean inputContext, String path, SchemaValidationErrorCollector errors) { + if (inputContext) { + addError(errors, SchemaValidationErrorType.OutputTypeUsedInInputTypeContext, + format("The output type '%s' has been used in an input type context : '%s'", simplePrint(misusedType), path)); + } else { + addError(errors, SchemaValidationErrorType.InputTypeUsedInOutputTypeContext, + format("The input type '%s' has been used in a output type context : '%s'", simplePrint(misusedType), path)); } - Map, Object> rootVars = new LinkedHashMap<>(); - rootVars.put(GraphQLSchema.class, schema); - rootVars.put(SchemaValidationErrorCollector.class, validationErrorCollector); - new SchemaTraverser().depthFirstFullSchema(rules, schema, rootVars); - return validationErrorCollector.getErrors(); } + private boolean isMisused(GraphQLType type, boolean inputContext) { + return inputContext ? !(type instanceof GraphQLInputType) : !(type instanceof GraphQLOutputType); + } + + private void checkOneOfInhabited(GraphQLInputObjectType inputObjectType, SchemaValidationErrorCollector errors) { + if (!inputObjectType.isOneOf()) { + return; + } + if (!canBeProvidedAFiniteValue(inputObjectType, newIdentitySet())) { + addError(errors, SchemaValidationErrorType.OneOfNotInhabited, + format("OneOf Input Object %s must be inhabited but all fields recursively reference only other OneOf Input Objects forming an unresolvable cycle.", inputObjectType.getName())); + } + } + + private boolean canBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { + if (!visited.add(oneOfInputObject)) { + return false; + } + boolean result = anyFieldCanBeProvidedAFiniteValue(oneOfInputObject, visited); + visited.remove(oneOfInputObject); + return result; + } + + private boolean anyFieldCanBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { + for (GraphQLInputObjectField field : oneOfInputObject.getFieldDefinitions()) { + GraphQLType fieldType = field.getType(); + if (isList(fieldType)) { + return true; + } + GraphQLType namedFieldType = unwrapAll(fieldType); + if (!(namedFieldType instanceof GraphQLInputObjectType)) { + return true; + } + GraphQLInputObjectType inputFieldType = (GraphQLInputObjectType) namedFieldType; + if (!inputFieldType.isOneOf() || canBeProvidedAFiniteValue(inputFieldType, visited)) { + return true; + } + } + return false; + } + + private void checkOneOfField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errors) { + if (!inputObjectType.isOneOf()) { + return; + } + if (inputObjectField.hasSetDefaultValue()) { + addError(errors, SchemaValidationErrorType.OneOfDefaultValueOnField, + format("OneOf input field %s.%s cannot have a default value.", inputObjectType.getName(), inputObjectField.getName())); + } + if (isNonNull(inputObjectField.getType())) { + addError(errors, SchemaValidationErrorType.OneOfNonNullableField, + format("OneOf input field %s.%s must be nullable.", inputObjectType.getName(), inputObjectField.getName())); + } + } + + private void checkDeprecatedInputField(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errors) { + if (!isNonNull(inputObjectField.getType()) || inputObjectField.hasSetDefaultValue()) { + return; + } + if (inputObjectField.getAppliedDirective(DEPRECATED_DIRECTIVE_NAME) == null) { + return; + } + addError(errors, SchemaValidationErrorType.RequiredInputFieldCannotBeDeprecated, + format("Required input field '%s.%s' cannot be deprecated.", type.getName(), inputObjectField.getName())); + } + + private void checkDeprecatedArgument(GraphQLArgument argument, GraphQLSchemaElement fieldOrDirective, SchemaValidationErrorCollector errors) { + if (!argument.isDeprecated() || !isNonNull(argument.getType()) || argument.hasSetDefaultValue()) { + return; + } + if (fieldOrDirective instanceof GraphQLFieldDefinition) { + addError(errors, SchemaValidationErrorType.RequiredFieldArgumentCannotBeDeprecated, + format("Required argument '%s' on field '%s' cannot be deprecated.", argument.getName(), ((GraphQLFieldDefinition) fieldOrDirective).getName())); + } else if (fieldOrDirective instanceof GraphQLDirective) { + addError(errors, SchemaValidationErrorType.RequiredDirectiveArgumentCannotBeDeprecated, + format("Required argument '%s' on directive '%s' cannot be deprecated.", argument.getName(), ((GraphQLDirective) fieldOrDirective).getName())); + } + } } diff --git a/src/main/java/graphql/schema/validation/TypeAndFieldRule.java b/src/main/java/graphql/schema/validation/TypeAndFieldRule.java deleted file mode 100644 index 84a768479d..0000000000 --- a/src/main/java/graphql/schema/validation/TypeAndFieldRule.java +++ /dev/null @@ -1,233 +0,0 @@ -package graphql.schema.validation; - -import graphql.collect.ImmutableKit; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLEnumType; -import graphql.schema.GraphQLEnumValueDefinition; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLFieldsContainer; -import graphql.schema.GraphQLInputObjectField; -import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLNamedOutputType; -import graphql.schema.GraphQLNamedType; -import graphql.schema.GraphQLNonNull; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLScalarType; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeUtil; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.schema.GraphQLUnionType; -import graphql.util.FpKit; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import static graphql.introspection.Introspection.INTROSPECTION_SYSTEM_FIELDS; -import static graphql.introspection.Introspection.isIntrospectionTypes; -import static graphql.schema.idl.ScalarInfo.isGraphqlSpecifiedScalar; - -/** - * The validation about GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLScalarType. - *
    - *
  • Types must define one or more fields;
  • - *
  • Enum type must define one or more enum values;
  • - *
  • Union type must include one or more unique member types;
  • - *
  • The member types of a Union type must all be Object base types;
  • - *
  • Non‐Null type must not wrap another Non‐Null type;
  • - *
  • Invalid name begin with "__" (two underscores).
  • - *
- *

- * details in https://spec.graphql.org/June2018/#sec-Type-System - */ -public class TypeAndFieldRule extends GraphQLTypeVisitorStub { - - @Override - public TraversalControl visitGraphQLInterfaceType(GraphQLInterfaceType type, TraverserContext context) { - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateContainsField((GraphQLFieldsContainer) type, errorCollector); - return super.visitGraphQLInterfaceType(type, context); - } - - @Override - public TraversalControl visitGraphQLObjectType(GraphQLObjectType type, TraverserContext context) { - if (isIntrospectionTypes(type)) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateContainsField((GraphQLFieldsContainer) type, errorCollector); - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLUnionType(GraphQLUnionType type, TraverserContext context) { - if (isIntrospectionTypes(type)) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateUnion((GraphQLUnionType) type, errorCollector); - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLEnumType(GraphQLEnumType type, TraverserContext context) { - if (isIntrospectionTypes(type)) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateEnum((GraphQLEnumType) type, errorCollector); - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType type, TraverserContext context) { - if (isIntrospectionTypes(type)) { - return TraversalControl.CONTINUE; - } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateInputObject((GraphQLInputObjectType) type, errorCollector); - return TraversalControl.CONTINUE; - } - - - private void validateContainsField(GraphQLFieldsContainer type, SchemaValidationErrorCollector errorCollector) { - List fieldDefinitions = type.getFieldDefinitions(); - if (fieldDefinitions == null || fieldDefinitions.size() == 0) { - SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.ImplementingTypeLackOfFieldError, String.format("\"%s\" must define one or more fields.", type.getName())); - errorCollector.addError(validationError); - return; - } - - for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { - validateFieldDefinition(type.getName(), fieldDefinition, errorCollector); - } - } - - private void validateInputObject(GraphQLInputObjectType type, SchemaValidationErrorCollector errorCollector) { - List inputObjectFields = type.getFields(); - if (inputObjectFields == null || inputObjectFields.size() == 0) { - SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.InputObjectTypeLackOfFieldError, String.format("\"%s\" must define one or more fields.", type.getName())); - errorCollector.addError(validationError); - return; - } - - for (GraphQLInputObjectField inputObjectField : inputObjectFields) { - validateInputFieldDefinition(type.getName(), inputObjectField, errorCollector); - } - } - - private void validateUnion(GraphQLUnionType type, SchemaValidationErrorCollector errorCollector) { - List memberTypes = type.getTypes(); - if (memberTypes.size() == 0) { - SchemaValidationError validationError = - new SchemaValidationError(SchemaValidationErrorType.UnionTypeLackOfTypeError, String.format("Union type \"%s\" must include one or more unique member types.", type.getName())); - errorCollector.addError(validationError); - } - - Set typeNames = new HashSet<>(); - for (GraphQLNamedOutputType memberType : type.getTypes()) { - String typeName = memberType.getName(); -// GraphQLNamedType graphQLNamedType = schemaTypeHolder.get(typeName); - if (!(memberType instanceof GraphQLObjectType)) { - SchemaValidationError validationError = - new SchemaValidationError(SchemaValidationErrorType.InvalidUnionMemberTypeError, String.format("The member types of a Union type must all be Object base types. member type \"%s\" in Union \"%s\" is invalid.", memberType.getName(), type.getName())); - errorCollector.addError(validationError); - } - if (typeNames.contains(typeName)) { - SchemaValidationError validationError = - new SchemaValidationError(SchemaValidationErrorType.RepetitiveElementError, String.format("The member types of a Union type must be unique. member type \"%s\" in Union \"%s\" is not unique.", memberType.getName(), type.getName())); - errorCollector.addError(validationError); - } - typeNames.add(typeName); - } - } - - private void validateEnum(GraphQLEnumType type, SchemaValidationErrorCollector errorCollector) { - List enumValueDefinitions = type.getValues(); - if (enumValueDefinitions == null || enumValueDefinitions.size() == 0) { - SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.EnumLackOfValueError, String.format("Enum type \"%s\" must define one or more enum values.", type.getName())); - errorCollector.addError(validationError); - } else { - for (GraphQLEnumValueDefinition enumValueDefinition : enumValueDefinitions) { - assertEnumValueDefinitionName(type.getName(), enumValueDefinition.getName(), errorCollector); - } - } - - } - - private void validateFieldDefinition(String typeName, GraphQLFieldDefinition fieldDefinition, SchemaValidationErrorCollector errorCollector) { - assertFieldName(typeName, fieldDefinition.getName(), errorCollector); - assertNonNullType(fieldDefinition.getType(), errorCollector); - - List fieldDefinitionArguments = fieldDefinition.getArguments(); - for (GraphQLArgument fieldDefinitionArgument : fieldDefinitionArguments) { - validateFieldDefinitionArgument(typeName, fieldDefinition.getName(), fieldDefinitionArgument, errorCollector); - } - } - - private void validateInputFieldDefinition(String typeName, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errorCollector) { - assertFieldName(typeName, inputObjectField.getName(), errorCollector); - assertNonNullType(inputObjectField.getType(), errorCollector); - } - - private void validateFieldDefinitionArgument(String typeName, String fieldName, GraphQLArgument argument, SchemaValidationErrorCollector errorCollector) { - assertArgumentName(typeName, fieldName, argument.getName(), errorCollector); - assertNonNullType(argument.getType(), errorCollector); - } - - private void assertArgumentName(String typeName, String fieldName, String argumentName, SchemaValidationErrorCollector errorCollector) { - if (argumentName.length() >= 2 && argumentName.startsWith("__")) { - SchemaValidationError schemaValidationError = new SchemaValidationError(SchemaValidationErrorType.InvalidCustomizedNameError, - String.format("Argument name \"%s\" in \"%s-%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", argumentName, typeName, fieldName)); - errorCollector.addError(schemaValidationError); - } - } - - private void assertEnumValueDefinitionName(String typeName, String enumValueDefinitionName, SchemaValidationErrorCollector errorCollector) { - if (enumValueDefinitionName.length() >= 2 && enumValueDefinitionName.startsWith("__")) { - SchemaValidationError schemaValidationError = new SchemaValidationError(SchemaValidationErrorType.InvalidCustomizedNameError, - String.format("EnumValueDefinition \"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", enumValueDefinitionName, typeName)); - errorCollector.addError(schemaValidationError); - } - } - - private void assertNonNullType(GraphQLType type, SchemaValidationErrorCollector errorCollector) { - if (type instanceof GraphQLNonNull && ((GraphQLNonNull) type).getWrappedType() instanceof GraphQLNonNull) { - SchemaValidationError schemaValidationError = new SchemaValidationError(SchemaValidationErrorType.NonNullWrapNonNullError, - String.format("Non‐Null type must not wrap another Non‐Null type: \"%s\" is invalid.", GraphQLTypeUtil.simplePrint(type))); - errorCollector.addError(schemaValidationError); - } - } - - private List filterBuiltInTypes(List graphQLNamedTypes) { - if (graphQLNamedTypes == null || graphQLNamedTypes.isEmpty()) { - return ImmutableKit.emptyList(); - } - - Predicate filterFunction = namedType -> { - if (isIntrospectionTypes(namedType)) { - return false; - } - return !(namedType instanceof GraphQLScalarType) || !isGraphqlSpecifiedScalar((GraphQLScalarType) namedType); - }; - - return FpKit.filterList(graphQLNamedTypes, filterFunction); - } - - - private void assertFieldName(String typeName, String fieldName, SchemaValidationErrorCollector errorCollector) { - if (INTROSPECTION_SYSTEM_FIELDS.contains(fieldName)) { - return; - } - if (fieldName.length() >= 2 && fieldName.startsWith("__")) { - SchemaValidationError schemaValidationError = new SchemaValidationError(SchemaValidationErrorType.InvalidCustomizedNameError, - String.format("\"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", fieldName, typeName)); - errorCollector.addError(schemaValidationError); - } - } -} \ No newline at end of file diff --git a/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java b/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java deleted file mode 100644 index ef1ef84b48..0000000000 --- a/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java +++ /dev/null @@ -1,211 +0,0 @@ -package graphql.schema.validation; - -import graphql.Internal; -import graphql.schema.GraphQLArgument; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLImplementingType; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLNamedOutputType; -import graphql.schema.GraphQLNonNull; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLOutputType; -import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.schema.GraphQLUnionType; -import graphql.util.FpKit; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static graphql.collect.ImmutableKit.map; -import static graphql.schema.GraphQLTypeUtil.isList; -import static graphql.schema.GraphQLTypeUtil.isNonNull; -import static graphql.schema.GraphQLTypeUtil.simplePrint; -import static graphql.schema.GraphQLTypeUtil.unwrapOne; -import static graphql.schema.validation.SchemaValidationErrorType.ObjectDoesNotImplementItsInterfaces; -import static java.lang.String.format; - -/** - * Schema validation rule ensuring object and interface types have all the fields that they need to - * implement the interfaces they say they implement. - */ -@Internal -public class TypesImplementInterfaces extends GraphQLTypeVisitorStub { - private static final Map, String> TYPE_OF_MAP = new HashMap<>(); - - static { - TYPE_OF_MAP.put(GraphQLObjectType.class, "object"); - TYPE_OF_MAP.put(GraphQLInterfaceType.class, "interface"); - } - - @Override - public TraversalControl visitGraphQLObjectType(GraphQLObjectType type, TraverserContext context) { - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - check((GraphQLImplementingType) type, validationErrorCollector); - return TraversalControl.CONTINUE; - } - - @Override - public TraversalControl visitGraphQLInterfaceType(GraphQLInterfaceType type, TraverserContext context) { - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - check((GraphQLImplementingType) type, validationErrorCollector); - return TraversalControl.CONTINUE; - } - - - private void check(GraphQLImplementingType implementingType, SchemaValidationErrorCollector validationErrorCollector) { - List interfaces = implementingType.getInterfaces(); - interfaces.forEach(interfaceType -> { - // we have resolved the interfaces at this point and hence the cast is ok - checkObjectImplementsInterface(implementingType, (GraphQLInterfaceType) interfaceType, validationErrorCollector); - }); - - } - - // this deliberately has open field visibility here since it's validating the schema - // when completely open - private void checkObjectImplementsInterface(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector validationErrorCollector) { - List fieldDefinitions = interfaceType.getFieldDefinitions(); - for (GraphQLFieldDefinition interfaceFieldDef : fieldDefinitions) { - GraphQLFieldDefinition objectFieldDef = implementingType.getFieldDefinition(interfaceFieldDef.getName()); - if (objectFieldDef == null) { - validationErrorCollector.addError( - error(format("%s type '%s' does not implement interface '%s' because field '%s' is missing", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName()))); - } else { - checkFieldTypeCompatibility(implementingType, interfaceType, validationErrorCollector, interfaceFieldDef, objectFieldDef); - } - } - - checkTransitiveImplementations(implementingType, interfaceType, validationErrorCollector); - } - - private void checkTransitiveImplementations(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector validationErrorCollector) { - List implementedInterfaces = implementingType.getInterfaces(); - interfaceType.getInterfaces().forEach(transitiveInterface -> { - if (transitiveInterface.equals(implementingType)) { - validationErrorCollector.addError( - error(format("%s type '%s' cannot implement '%s' because that would result on a circular reference", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), interfaceType.getName())) - ); - } else if (!implementedInterfaces.contains(transitiveInterface)) { - validationErrorCollector.addError( - error(format("%s type '%s' must implement '%s' because it is implemented by '%s'", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), transitiveInterface.getName(), interfaceType.getName()))); - } - }); - } - - private void checkFieldTypeCompatibility(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector validationErrorCollector, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef) { - String interfaceFieldDefStr = simplePrint(interfaceFieldDef.getType()); - String objectFieldDefStr = simplePrint(objectFieldDef.getType()); - - if (!isCompatible(interfaceFieldDef.getType(), objectFieldDef.getType())) { - validationErrorCollector.addError( - error(format("%s type '%s' does not implement interface '%s' because field '%s' is defined as '%s' type and not as '%s' type", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), objectFieldDefStr, interfaceFieldDefStr))); - } else { - checkFieldArgumentEquivalence(implementingType, interfaceType, validationErrorCollector, interfaceFieldDef, objectFieldDef); - } - } - - private void checkFieldArgumentEquivalence(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector validationErrorCollector, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef) { - List interfaceArgs = interfaceFieldDef.getArguments(); - List objectArgs = objectFieldDef.getArguments(); - - Map interfaceArgsByName = FpKit.getByName(interfaceArgs, GraphQLArgument::getName); - List objectArgsNames = map(objectArgs, GraphQLArgument::getName); - - if (!objectArgsNames.containsAll(interfaceArgsByName.keySet())) { - final String missingArgsNames = interfaceArgsByName.keySet().stream() - .filter(name -> !objectArgsNames.contains(name)) - .collect(Collectors.joining(", ")); - - validationErrorCollector.addError( - error(format("%s type '%s' does not implement interface '%s' because field '%s' is missing argument(s): '%s'", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), missingArgsNames))); - } else { - objectArgs.forEach(objectArg -> { - GraphQLArgument interfaceArg = interfaceArgsByName.get(objectArg.getName()); - - if (interfaceArg == null) { - if (objectArg.getType() instanceof GraphQLNonNull) { - validationErrorCollector.addError( - error(format("%s type '%s' field '%s' defines an additional non-optional argument '%s' which is not allowed because field is also defined in interface '%s'", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), objectFieldDef.getName(), objectArg.getName(), interfaceType.getName()))); - } - } else { - if (!makeArgStr(objectArg).equals(makeArgStr(interfaceArg))) { - validationErrorCollector.addError( - error(format("%s type '%s' does not implement interface '%s' because field '%s' argument '%s' is defined differently", - TYPE_OF_MAP.get(implementingType.getClass()), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), objectArg.getName()))); - } - } - }); - } - } - - private String makeArgStr(GraphQLArgument argument) { - return argument.getName() + - ":" + - simplePrint(argument.getType()); - - } - - private SchemaValidationError error(String msg) { - return new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, msg); - } - - /** - * @return {@code true} if the specified implementingType satisfies the constraintType. - */ - boolean isCompatible(GraphQLOutputType constraintType, GraphQLOutputType objectType) { - if (isSameType(constraintType, objectType)) { - return true; - } else if (constraintType instanceof GraphQLUnionType) { - return objectIsMemberOfUnion((GraphQLUnionType) constraintType, objectType); - } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLObjectType) { - return objectImplementsInterface((GraphQLInterfaceType) constraintType, (GraphQLObjectType) objectType); - } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLInterfaceType) { - return interfaceImplementsInterface((GraphQLInterfaceType) constraintType, (GraphQLInterfaceType) objectType); - } else if (isList(constraintType) && isList(objectType)) { - GraphQLOutputType wrappedConstraintType = (GraphQLOutputType) unwrapOne(constraintType); - GraphQLOutputType wrappedObjectType = (GraphQLOutputType) unwrapOne(objectType); - return isCompatible(wrappedConstraintType, wrappedObjectType); - } else if (isNonNull(objectType)) { - GraphQLOutputType nullableConstraint; - if (isNonNull(constraintType)) { - nullableConstraint = (GraphQLOutputType) unwrapOne(constraintType); - } else { - nullableConstraint = constraintType; - } - GraphQLOutputType nullableObjectType = (GraphQLOutputType) unwrapOne(objectType); - return isCompatible(nullableConstraint, nullableObjectType); - } else { - return false; - } - } - - boolean isSameType(GraphQLOutputType a, GraphQLOutputType b) { - String aDefString = simplePrint(a); - String bDefString = simplePrint(b); - return aDefString.equals(bDefString); - } - - boolean objectImplementsInterface(GraphQLInterfaceType interfaceType, GraphQLObjectType objectType) { - return objectType.getInterfaces().contains(interfaceType); - } - - boolean interfaceImplementsInterface(GraphQLInterfaceType interfaceType, GraphQLInterfaceType implementingType) { - return implementingType.getInterfaces().contains(interfaceType); - } - - boolean objectIsMemberOfUnion(GraphQLUnionType unionType, GraphQLOutputType objectType) { - return unionType.getTypes().contains(objectType); - } - -} diff --git a/src/test/groovy/graphql/CircularInputDefaultValuesTest.groovy b/src/test/groovy/graphql/CircularInputDefaultValuesTest.groovy index 43a92975e3..2157423fb1 100644 --- a/src/test/groovy/graphql/CircularInputDefaultValuesTest.groovy +++ b/src/test/groovy/graphql/CircularInputDefaultValuesTest.groovy @@ -6,7 +6,7 @@ import spock.lang.Specification /** * Tests for mutually recursive input types with default values. * - * These schemas are now rejected at build time by NoDefaultValueCircularRefs, + * These schemas are now rejected at build time by schema validation, * which detects circular references in input object field default values. * * Previously, graphql-java accepted these schemas at build time but hit a diff --git a/src/test/groovy/graphql/InterfacesImplementingInterfacesTest.groovy b/src/test/groovy/graphql/InterfacesImplementingInterfacesTest.groovy index 0442820eed..59e685d71c 100644 --- a/src/test/groovy/graphql/InterfacesImplementingInterfacesTest.groovy +++ b/src/test/groovy/graphql/InterfacesImplementingInterfacesTest.groovy @@ -1359,9 +1359,7 @@ type Query { } def assertErrorMessage(InvalidSchemaException exception, String... expectedErrors) { - def expectedMessage = "invalid schema:\n" + expectedErrors.join("\n") - - return exception.message == expectedMessage + return exception.errors*.description as Set == expectedErrors as Set } def parseSchema(schema) { diff --git a/src/test/groovy/graphql/schema/FastBuilderTest.groovy b/src/test/groovy/graphql/schema/FastBuilderTest.groovy index 833c256edb..4ae112f4a0 100644 --- a/src/test/groovy/graphql/schema/FastBuilderTest.groovy +++ b/src/test/groovy/graphql/schema/FastBuilderTest.groovy @@ -2222,7 +2222,7 @@ class FastBuilderTest extends Specification { // Regression tests for ShallowTypeRefCollector bug: // Applied directives on field arguments and enum values were not scanned for type // references, leaving GraphQLTypeReference unresolved and causing spurious - // InvalidSchemaException from AppliedDirectiveArgumentsAreValid validator. + // InvalidSchemaException from applied directive argument validation. def "applied directive on object type field argument with type-ref enum arg resolves correctly"() { given: "an enum type used as a directive argument type" diff --git a/src/test/groovy/graphql/schema/SchemaTraverserTest.groovy b/src/test/groovy/graphql/schema/SchemaTraverserTest.groovy index f7a6fc8a9c..942b2f9dc7 100644 --- a/src/test/groovy/graphql/schema/SchemaTraverserTest.groovy +++ b/src/test/groovy/graphql/schema/SchemaTraverserTest.groovy @@ -408,6 +408,30 @@ class SchemaTraverserTest extends Specification { ] } + def "depthFirstFullSchema visits mutation and subscription types only when the schema has them"() { + given: + def visited = [] + def visitor = new GraphQLTypeVisitorStub() { + @Override + TraversalControl visitGraphQLObjectType(GraphQLObjectType node, TraverserContext context) { + visited.add(node.getName()) + return TraversalControl.CONTINUE + } + } + + when: + new SchemaTraverser().depthFirstFullSchema(visitor, TestUtil.schema(sdl)) + + then: + visited.containsAll(rootTypes) + notVisited.every { !visited.contains(it) } + + where: + sdl | rootTypes | notVisited + "type Query { q: String }" | ["Query"] | ["Mutation", "Subscription"] + "type Query { q: String } type Mutation { m: String } type Subscription { s: String }" | ["Query", "Mutation", "Subscription"] | [] + } + class GraphQLTestingVisitor extends GraphQLTypeVisitorStub { def stack = [] diff --git a/src/test/groovy/graphql/schema/validation/InputAndOutputTypesUsedAppropriatelyTest.groovy b/src/test/groovy/graphql/schema/validation/InputAndOutputTypesUsedAppropriatelyTest.groovy index 0c5a60208f..c29703799c 100644 --- a/src/test/groovy/graphql/schema/validation/InputAndOutputTypesUsedAppropriatelyTest.groovy +++ b/src/test/groovy/graphql/schema/validation/InputAndOutputTypesUsedAppropriatelyTest.groovy @@ -90,4 +90,33 @@ class InputAndOutputTypesUsedAppropriatelyTest extends Specification { def errors = schemaException.getErrors().collect { it.description } errors.contains("The input type 'Person' has been used in a output type context : 'Query.outputField'") } + + def "output type as field argument is caught"() { + given: + GraphQLObjectType OutputType = newObject() + .name("OutputType") + .field(newFieldDefinition().name("field").type(GraphQLString)) + .build() + + GraphQLObjectType queryType = newObject() + .name("Query") + .field(newFieldDefinition() + .name("exists") + .type(GraphQLBoolean) + .argument(GraphQLArgument.newArgument() + .name("arg") + .type(list(typeRef("OutputType"))))) + .build() + + when: + GraphQLSchema.newSchema() + .query(queryType) + .additionalTypes([OutputType] as Set) + .build() + + then: + def schemaException = thrown(InvalidSchemaException) + def errors = schemaException.getErrors().collect { it.description } + errors.contains("The output type 'OutputType' has been used in an input type context : 'Query.exists.arg'") + } } diff --git a/src/test/groovy/graphql/schema/validation/NoDefaultValueCircularRefsTest.groovy b/src/test/groovy/graphql/schema/validation/NoDefaultValueCircularRefsTest.groovy index bd35006c25..684d4ab3dc 100644 --- a/src/test/groovy/graphql/schema/validation/NoDefaultValueCircularRefsTest.groovy +++ b/src/test/groovy/graphql/schema/validation/NoDefaultValueCircularRefsTest.groovy @@ -1,8 +1,19 @@ package graphql.schema.validation import graphql.TestUtil +import graphql.schema.GraphQLInputObjectType import spock.lang.Specification +import static graphql.Scalars.GraphQLString +import static graphql.schema.GraphQLArgument.newArgument +import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition +import static graphql.schema.GraphQLInputObjectField.newInputObjectField +import static graphql.schema.GraphQLInputObjectType.newInputObject +import static graphql.schema.GraphQLList.list +import static graphql.schema.GraphQLObjectType.newObject +import static graphql.schema.GraphQLSchema.newSchema +import static graphql.schema.GraphQLTypeReference.typeRef + class NoDefaultValueCircularRefsTest extends Specification { def "self-referential default value is rejected"() { when: @@ -199,4 +210,80 @@ class NoDefaultValueCircularRefsTest extends Specification { noExceptionThrown() schema.getType("A") != null } + + static Set programmaticSchemaErrors(GraphQLInputObjectType argumentType, List otherTypes = []) { + def query = newObject().name("Query") + .field(newFieldDefinition().name("test").type(GraphQLString).argument(newArgument().name("arg").type(argumentType))) + .build() + try { + newSchema().query(query).additionalTypes(otherTypes as Set).build() + return [] as Set + } catch (InvalidSchemaException e) { + return e.errors.collect { it.description } as Set + } + } + + def "programmatic self-referential default value is rejected"() { + given: + def a = newInputObject().name("A") + .field(newInputObjectField().name("x").type(typeRef("A")).defaultValueProgrammatic([:])) + .build() + + expect: + programmaticSchemaErrors(a) == ["Invalid circular reference. The default value of Input Object field A.x references itself."] as Set + } + + def "programmatic mutual recursion through defaults is rejected"() { + given: + def a = newInputObject().name("A") + .field(newInputObjectField().name("b").type(typeRef("B")).defaultValueProgrammatic([:])) + .build() + def b = newInputObject().name("B") + .field(newInputObjectField().name("a").type(typeRef("A")).defaultValueProgrammatic([:])) + .build() + + expect: + programmaticSchemaErrors(a, [b]) == ["Invalid circular reference. The default value of Input Object field A.b references itself via the default values of: B.a."] as Set + } + + def "programmatic nested default value that eventually cycles is rejected"() { + given: + def a = newInputObject().name("A") + .field(newInputObjectField().name("x").type(typeRef("A")).defaultValueProgrammatic([x: [x: [:]]])) + .field(newInputObjectField().name("name").type(GraphQLString)) + .build() + + expect: + programmaticSchemaErrors(a) == ["Invalid circular reference. The default value of Input Object field A.x references itself."] as Set + } + + def "programmatic self-reference through list default is rejected, skipping null items"() { + given: + def a = newInputObject().name("A") + .field(newInputObjectField().name("x").type(list(typeRef("A"))).defaultValueProgrammatic([null, [:]])) + .build() + + expect: + programmaticSchemaErrors(a) == ["Invalid circular reference. The default value of Input Object field A.x references itself."] as Set + } + + def "programmatic explicit null breaks self-reference"() { + given: + def a = newInputObject().name("A") + .field(newInputObjectField().name("x").type(typeRef("A")).defaultValueProgrammatic([x: null])) + .build() + + expect: + programmaticSchemaErrors(a).isEmpty() + } + + def "programmatic non-map default value is not treated as a cycle"() { + given: + def a = newInputObject().name("A") + .field(newInputObjectField().name("x").type(typeRef("A")).defaultValueProgrammatic("notAnObject")) + .build() + + expect: + programmaticSchemaErrors(a) == ["Invalid default value notAnObject for type A"] as Set + } } diff --git a/src/test/groovy/graphql/schema/validation/NoUnbrokenInputCyclesTest.groovy b/src/test/groovy/graphql/schema/validation/NoUnbrokenInputCyclesTest.groovy index a9f0889e3d..68db2eb2ad 100644 --- a/src/test/groovy/graphql/schema/validation/NoUnbrokenInputCyclesTest.groovy +++ b/src/test/groovy/graphql/schema/validation/NoUnbrokenInputCyclesTest.groovy @@ -1,50 +1,50 @@ package graphql.schema.validation import graphql.TestUtil -import graphql.schema.GraphQLArgument -import graphql.schema.GraphQLFieldDefinition -import graphql.schema.GraphQLInputObjectField -import graphql.schema.GraphQLInputObjectType import graphql.schema.idl.SchemaGenerator import graphql.schema.idl.SchemaParser -import graphql.util.TraverserContext import spock.lang.Specification -import static graphql.Scalars.GraphQLBoolean -import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition -import static graphql.schema.GraphQLInputObjectType.newInputObject -import static graphql.schema.GraphQLNonNull.nonNull -import static graphql.schema.GraphQLTypeReference.typeRef - class NoUnbrokenInputCyclesTest extends Specification { - SchemaValidationErrorCollector errorCollector = new SchemaValidationErrorCollector() - def "infinitely recursive input type results in error"() { - given: - GraphQLInputObjectType PersonInputType = newInputObject() - .name("Person") - .field(GraphQLInputObjectField.newInputObjectField() - .name("friend") - .type(typeRef("Person")) - .build()) - .build() - - GraphQLFieldDefinition field = newFieldDefinition() - .name("exists") - .type(GraphQLBoolean) - .argument(GraphQLArgument.newArgument() - .name("person") - .type(PersonInputType)) - .build() - - PersonInputType.getFieldDefinition("friend").replacedType = nonNull(PersonInputType) - def context = Mock(TraverserContext) - context.getVarFromParents(SchemaValidationErrorCollector) >> errorCollector when: - new NoUnbrokenInputCycles().visitGraphQLFieldDefinition(field, context) + TestUtil.schema(''' + type Query { exists(person: Person): Boolean } + input Person { friend: Person! } + ''') + + then: + def e = thrown(InvalidSchemaException) + e.errors*.description == ["[friend!] forms an unsatisfiable cycle"] + } + + def "cycle paths include earlier sibling fields"() { + when: + TestUtil.schema(''' + type Query { a(arg: A): String } + input A { x: B! y: A! } + input B { a: A! } + ''') + then: - errorCollector.containsValidationError(SchemaValidationErrorType.UnbrokenInputCycle) + def e = thrown(InvalidSchemaException) + e.errors*.description as Set == [ + "[x!.a!] forms an unsatisfiable cycle", + "[x!.y!] forms an unsatisfiable cycle", + ] as Set + } + + def "input object cycles through a nullable field are allowed"() { + when: + TestUtil.schema(''' + type Query { f(a: A): String } + input A { b: B } + input B { a: A! } + ''') + + then: + noExceptionThrown() } def "input object cycles through a non-null list are allowed"() { diff --git a/src/test/groovy/graphql/schema/validation/SchemaValidationErrorCollectorTest.groovy b/src/test/groovy/graphql/schema/validation/SchemaValidationErrorCollectorTest.groovy new file mode 100644 index 0000000000..60e7b549bb --- /dev/null +++ b/src/test/groovy/graphql/schema/validation/SchemaValidationErrorCollectorTest.groovy @@ -0,0 +1,37 @@ +package graphql.schema.validation + +import spock.lang.Specification + +class SchemaValidationErrorCollectorTest extends Specification { + + def "collects distinct errors in insertion order"() { + given: + def collector = new SchemaValidationErrorCollector() + def first = new SchemaValidationError(SchemaValidationErrorType.UnbrokenInputCycle, "first") + def second = new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, "second") + + when: + collector.addError(first) + collector.addError(second) + collector.addError(new SchemaValidationError(SchemaValidationErrorType.UnbrokenInputCycle, "first")) + + then: + collector.getErrors() as List == [first, second] + } + + def "containsValidationError matches on classification"() { + given: + def collector = new SchemaValidationErrorCollector() + + expect: + !collector.containsValidationError(SchemaValidationErrorType.UnbrokenInputCycle) + + when: + collector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, "invalid")) + collector.addError(new SchemaValidationError(SchemaValidationErrorType.UnbrokenInputCycle, "cycle")) + + then: + collector.containsValidationError(SchemaValidationErrorType.UnbrokenInputCycle) + !collector.containsValidationError(SchemaValidationErrorType.OneOfNotInhabited) + } +} diff --git a/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy b/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy index a854129d41..00000bfe96 100644 --- a/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy +++ b/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy @@ -1,26 +1,219 @@ package graphql.schema.validation - +import graphql.Directives +import graphql.TestUtil +import graphql.collect.ImmutableKit +import graphql.schema.GraphQLCodeRegistry +import graphql.schema.GraphQLInputObjectField +import graphql.schema.GraphQLSchema +import graphql.schema.idl.FastSchemaGenerator +import graphql.schema.idl.RuntimeWiring +import graphql.schema.idl.SchemaGenerator +import graphql.schema.idl.SchemaParser import spock.lang.Specification +import static graphql.Scalars.GraphQLInt +import static graphql.Scalars.GraphQLString +import static graphql.TestUtil.mkDirective +import static graphql.introspection.Introspection.DirectiveLocation.ARGUMENT_DEFINITION +import static graphql.introspection.Introspection.DirectiveLocation.FIELD_DEFINITION +import static graphql.schema.GraphQLArgument.newArgument +import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition +import static graphql.schema.GraphQLInputObjectField.newInputObjectField +import static graphql.schema.GraphQLInputObjectType.newInputObject +import static graphql.schema.GraphQLNonNull.nonNull +import static graphql.schema.GraphQLObjectType.newObject +import static graphql.schema.GraphQLSchema.newSchema + class SchemaValidatorTest extends Specification { + static Set sdlErrors(String sdl) { + try { + TestUtil.schema(sdl) + return [] as Set + } catch (InvalidSchemaException e) { + return e.errors.collect { it.description } as Set + } + } + + static Set errors(Closure buildSchema) { + try { + buildSchema() + return [] as Set + } catch (InvalidSchemaException e) { + return e.errors.collect { it.description } as Set + } + } + + static String loadResource(String name) { + SchemaValidatorTest.class.getClassLoader().getResource(name).getText("UTF-8") + } + + def "large schemas are valid"() { + given: + def schema = new FastSchemaGenerator().makeExecutableSchema( + SchemaGenerator.Options.defaultOptions().withValidation(false), + new SchemaParser().parse(loadResource(schemaFile)), + RuntimeWiring.MOCKED_WIRING) + + expect: + new SchemaValidator().validateSchema(schema).isEmpty() + + where: + schemaFile << [ + "large-schema-1.graphqls", + "large-schema-2.graphqls", + "large-schema-3.graphqls", + "large-schema-4.graphqls", + "large-schema-federated-1.graphqls", + "extra-large-schema-1.graphqls", + ] + } - def "check used rules"() { + def "reports errors from every rule in a single validation"() { when: - def validator = new SchemaValidator() - def rules = validator.rules + TestUtil.schema(''' + type Query { + a(cycle: Cycle, old: Int! @deprecated, filter: Filter): String + b(defaults: DefaultCycleA): String + c(oneOf: OneOfA, other: OneOfC): String + } + + input Cycle { first: Cycle! } + input Filter { required: Int! @deprecated } + input DefaultCycleA { b: DefaultCycleB = {} } + input DefaultCycleB { a: DefaultCycleA = {} } + input OneOfA @oneOf { b: OneOfB } + input OneOfB @oneOf { a: OneOfA } + input OneOfC @oneOf { x: Int! y: Int = 1 } + ''') + then: - rules.size() == 10 - rules[0] instanceof NoUnbrokenInputCycles - rules[1] instanceof NoDefaultValueCircularRefs - rules[2] instanceof TypesImplementInterfaces - rules[3] instanceof TypeAndFieldRule - rules[4] instanceof DefaultValuesAreValid - rules[5] instanceof AppliedDirectivesAreValid - rules[6] instanceof AppliedDirectiveArgumentsAreValid - rules[7] instanceof InputAndOutputTypesUsedAppropriately - rules[8] instanceof OneOfInputObjectRules - rules[9] instanceof DeprecatedInputObjectAndArgumentsAreValid + def e = thrown(InvalidSchemaException) + e.errors*.classification as Set == [ + SchemaValidationErrorType.UnbrokenInputCycle, + SchemaValidationErrorType.RequiredFieldArgumentCannotBeDeprecated, + SchemaValidationErrorType.RequiredInputFieldCannotBeDeprecated, + SchemaValidationErrorType.DefaultValueCircularRef, + SchemaValidationErrorType.OneOfNotInhabited, + SchemaValidationErrorType.OneOfNonNullableField, + SchemaValidationErrorType.OneOfDefaultValueOnField, + ] as Set + } + + def "elements shared between parents are validated under each of them"() { + given: + GraphQLInputObjectField sharedField = newInputObjectField().name("shared").type(nonNull(GraphQLString)).build() + def plainInput = newInputObject().name("Plain").field(sharedField).build() + def oneOfInput = newInputObject().name("Choice").field(sharedField) + .withAppliedDirective(Directives.OneOfDirective.toAppliedDirective()) + .build() + def sharedArgument = newArgument().name("required").type(nonNull(GraphQLInt)).deprecate("old").build() + def query = newObject().name("Query") + .field(newFieldDefinition().name("plain").type(GraphQLString).argument(newArgument().name("arg").type(plainInput))) + .field(newFieldDefinition().name("choice").type(GraphQLString).argument(newArgument().name("arg").type(oneOfInput))) + .field(newFieldDefinition().name("first").type(GraphQLString).argument(sharedArgument)) + .field(newFieldDefinition().name("second").type(GraphQLString).argument(sharedArgument)) + .build() + + expect: + errors { newSchema().query(query).build() } == [ + "OneOf input field Choice.shared must be nullable.", + "Required argument 'required' on field 'first' cannot be deprecated.", + "Required argument 'required' on field 'second' cannot be deprecated.", + ] as Set + } + + def "FastBuilder validates schemas when validation is enabled"() { + given: + def query = newObject().name("Query") + .field(newFieldDefinition().name("__bad").type(GraphQLString)) + .build() + + expect: + errors { + new GraphQLSchema.FastBuilder(GraphQLCodeRegistry.newCodeRegistry(), query, null, null) + .withValidation(true) + .build() + } == ['"__bad" in "Query" must not begin with "__", which is reserved by GraphQL introspection.'] as Set + } + + def "applied directives without a definition are rejected"() { + given: + def query = newObject() + .name("Query") + .field(newFieldDefinition().name("hello").type(GraphQLString).withDirective(mkDirective("unknown", FIELD_DEFINITION))) + .build() + + expect: + errors { newSchema().query(query).build() } == ["A definition for directive 'unknown' could not be found"] as Set + } + + def "applied directive arguments are validated for programmatic schemas"() { + given: + def arg = newArgument().name("arg").type(nonNull(GraphQLInt)).build() + def directive = mkDirective("cached", ARGUMENT_DEFINITION, arg) + def query = newObject() + .name("Query") + .field(newFieldDefinition().name("hello").type(GraphQLString).withAppliedDirective(directive.toAppliedDirective())) + .build() + + expect: + errors { newSchema().query(query).additionalDirective(directive).build() } == ["Invalid argument 'arg' for applied directive of name 'cached'"] as Set + } + + def "legacy applied directive arguments are validated for programmatic schemas"() { + given: + def arg = newArgument().name("arg").type(GraphQLInt).valueProgrammatic(ImmutableKit.emptyMap()).build() + def directive = mkDirective("cached", ARGUMENT_DEFINITION, arg) + def query = newObject() + .name("Query") + .field(newFieldDefinition().name("hello").type(GraphQLString).argument(arg).withDirective(directive)) + .build() + + expect: + errors { newSchema().query(query).additionalDirective(directive).build() } + .contains("Invalid argument 'arg' for applied directive of name 'cached'") + } + + def "valid applied directive arguments are accepted"() { + expect: + sdlErrors(''' + directive @cached(key: String, ttl: Int! = 10) on FIELD_DEFINITION + type Query { hello: String @cached(key: "k") other: String @cached(key: "k", ttl: 5) } + ''').isEmpty() + } + + def "invalid default values are rejected: #scenario"() { + expect: + sdlErrors(sdl).size() == 1 + sdlErrors(sdl).every { it.startsWith("Invalid default value") } + + where: + scenario | sdl + "argument default missing required field" | 'type Query { foo(arg: Input = {}): String } input Input { required: String! }' + "argument default with null required field" | 'type Query { foo(arg: Input = {required: null}): String } input Input { required: String! }' + "input field default of the wrong type" | 'type Query { foo(arg: Input): String } input Input { count: Int = "many" }' + } + + def "valid default values are accepted"() { + expect: + sdlErrors(''' + type Query { foo(arg: Input = {required: "x"}, limit: Int = 10, tags: [String] = ["a"]): String } + input Input { required: String! optional: Int = 1 } + ''').isEmpty() + } + + def "a validator instance can validate several schemas"() { + given: + def validator = new SchemaValidator() + def schema = new FastSchemaGenerator().makeExecutableSchema( + SchemaGenerator.Options.defaultOptions().withValidation(false), + new SchemaParser().parse('type Query { a(arg: A): String } input A { b: A = {} }'), + RuntimeWiring.MOCKED_WIRING) + + expect: + validator.validateSchema(schema) == validator.validateSchema(schema) + validator.validateSchema(schema).size() == 1 } } diff --git a/src/test/groovy/graphql/schema/validation/TypeAndFieldRuleTest.groovy b/src/test/groovy/graphql/schema/validation/TypeAndFieldRuleTest.groovy index 8c3f4fc2a3..f704f45159 100644 --- a/src/test/groovy/graphql/schema/validation/TypeAndFieldRuleTest.groovy +++ b/src/test/groovy/graphql/schema/validation/TypeAndFieldRuleTest.groovy @@ -7,6 +7,11 @@ import graphql.schema.GraphQLTypeReference import graphql.schema.TypeResolverProxy import spock.lang.Specification +import static graphql.Scalars.GraphQLString +import static graphql.schema.GraphQLEnumType.newEnum +import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition +import static graphql.schema.GraphQLObjectType.newObject +import static graphql.schema.GraphQLSchema.newSchema import static graphql.schema.GraphQLUnionType.newUnionType class TypeAndFieldRuleTest extends Specification { @@ -165,4 +170,37 @@ class TypeAndFieldRuleTest extends Specification { !e.getErrors().isEmpty() e.getErrors()[0].classification == SchemaValidationErrorType.RepetitiveElementError } + + def "enum value name must not begin with __"() { + given: + def enumType = newEnum().name("EnumType").value("__reserved").value("OK").build() + def query = newObject().name("Query").field(newFieldDefinition().name("e").type(enumType)).build() + + when: + newSchema().query(query).build() + + then: + InvalidSchemaException e = thrown(InvalidSchemaException) + e.errors*.description == ['EnumValueDefinition "__reserved" in "EnumType" must not begin with "__", which is reserved by GraphQL introspection.'] + } + + def "union type must include one or more member types"() { + given: + def object = newObject().name("Object").field(newFieldDefinition().name("dummy").type(GraphQLString)).build() + def union = newUnionType().name("EmptyUnion").possibleType(object).build() + def query = newObject().name("Query").field(newFieldDefinition().name("u").type(union)).build() + def codeRegistry = GraphQLCodeRegistry.newCodeRegistry().typeResolver("EmptyUnion", { null }).build() + def schema = new graphql.schema.GraphQLSchema.FastBuilder(GraphQLCodeRegistry.newCodeRegistry(codeRegistry), query, null, null) + .addType(object) + .addType(union) + .build() + // the union builder rejects empty member lists, so the members are cleared after the schema is built + union.replaceTypes([]) + + when: + def errors = new SchemaValidator().validateSchema(schema) + + then: + errors*.description == ['Union type "EmptyUnion" must include one or more unique member types.'] + } } diff --git a/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy b/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy index bfb034ea77..2b13f33cd1 100644 --- a/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy +++ b/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy @@ -1,10 +1,15 @@ package graphql.schema.validation +import graphql.TestUtil +import graphql.schema.GraphQLCodeRegistry import graphql.schema.GraphQLInterfaceType import graphql.schema.GraphQLObjectType +import graphql.schema.GraphQLOutputType +import graphql.schema.GraphQLSchemaElement +import graphql.schema.GraphQLUnionType +import graphql.schema.TypeResolver import spock.lang.Specification -import static SchemaValidationErrorType.ObjectDoesNotImplementItsInterfaces import static graphql.Scalars.GraphQLBoolean import static graphql.Scalars.GraphQLInt import static graphql.Scalars.GraphQLString @@ -14,10 +19,41 @@ import static graphql.schema.GraphQLInterfaceType.newInterface import static graphql.schema.GraphQLList.list import static graphql.schema.GraphQLNonNull.nonNull import static graphql.schema.GraphQLObjectType.newObject +import static graphql.schema.GraphQLSchema.newSchema import static graphql.schema.GraphQLUnionType.newUnionType class TypesImplementInterfacesTest extends Specification { + // each implementing type gets a schema of its own so its errors can be checked in isolation + static Set errorsFor(GraphQLObjectType implementingType) { + def query = newObject().name("Query") + .field(newFieldDefinition().name("impl").type(implementingType)) + .build() + try { + newSchema().query(query).codeRegistry(codeRegistryWithTypeResolvers(query)).build() + return [] as Set + } catch (InvalidSchemaException e) { + return e.errors.collect { it.description } as Set + } + } + + static GraphQLCodeRegistry codeRegistryWithTypeResolvers(GraphQLObjectType queryType) { + def codeRegistry = GraphQLCodeRegistry.newCodeRegistry() + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()) + Deque stack = new ArrayDeque<>([queryType]) + while (!stack.isEmpty()) { + def element = stack.pop() + if (!seen.add(element)) { + continue + } + if (element instanceof GraphQLInterfaceType || element instanceof GraphQLUnionType) { + codeRegistry.typeResolver(element.name, { null } as TypeResolver) + } + stack.addAll(element.children) + } + codeRegistry.build() + } + def "field argument defaults do not affect interface implementation validity"() { given: def interfaceArgument = newArgument().name("limit").type(GraphQLInt) @@ -37,13 +73,9 @@ class TypesImplementInterfacesTest extends Specification { .withInterface(account) .field(newFieldDefinition().name("memberOf").type(GraphQLString).argument(implementingArgument)) .build() - def errors = new SchemaValidationErrorCollector() - when: - new TypesImplementInterfaces().check(host, errors) - - then: - errors.getErrors().isEmpty() + expect: + errorsFor(host).isEmpty() where: interfaceDefault | implementingDefault @@ -52,438 +84,225 @@ class TypesImplementInterfacesTest extends Specification { null | 150 } - GraphQLInterfaceType InterfaceType = newInterface() - .name("Interface") - - .field(newFieldDefinition().name("name").type(GraphQLString)) - .field(newFieldDefinition().name("friends").type(list(GraphQLString))) - .field(newFieldDefinition().name("age").type(GraphQLInt)) - .field(newFieldDefinition().name("address").type(list(GraphQLString))) - - .field(newFieldDefinition().name("argField1").type(GraphQLString) - .argument(newArgument().name("arg1").type(GraphQLString)) - .argument(newArgument().name("arg2").type(GraphQLInt)) - .argument(newArgument().name("arg3").type(GraphQLBoolean)) - .argument(newArgument().name("arg4").type(GraphQLString).defaultValueProgrammatic("ABC")) - ) - - .field(newFieldDefinition().name("argField2").type(GraphQLString) - .argument(newArgument().name("arg1").type(GraphQLString)) - .argument(newArgument().name("arg2").type(GraphQLInt)) - .argument(newArgument().name("arg3").type(GraphQLBoolean)) - ) - .build() - def "objects implement interfaces"() { given: - - SchemaValidationErrorCollector errorCollector = new SchemaValidationErrorCollector() - GraphQLObjectType objType = newObject() + def interfaceType = newInterface() + .name("Interface") + .field(newFieldDefinition().name("name").type(GraphQLString)) + .field(newFieldDefinition().name("friends").type(list(GraphQLString))) + .field(newFieldDefinition().name("age").type(GraphQLInt)) + .field(newFieldDefinition().name("address").type(list(GraphQLString))) + .field(newFieldDefinition().name("argField1").type(GraphQLString) + .argument(newArgument().name("arg1").type(GraphQLString)) + .argument(newArgument().name("arg2").type(GraphQLInt)) + .argument(newArgument().name("arg3").type(GraphQLBoolean)) + .argument(newArgument().name("arg4").type(GraphQLString).defaultValueProgrammatic("ABC"))) + .field(newFieldDefinition().name("argField2").type(GraphQLString) + .argument(newArgument().name("arg1").type(GraphQLString)) + .argument(newArgument().name("arg2").type(GraphQLInt)) + .argument(newArgument().name("arg3").type(GraphQLBoolean))) + .build() + def objType = newObject() .name("obj") - .withInterface(InterfaceType) + .withInterface(interfaceType) .field(newFieldDefinition().name("name").type(GraphQLString)) .field(newFieldDefinition().name("missing").type(list(GraphQLString))) .field(newFieldDefinition().name("age").type(GraphQLString)) .field(newFieldDefinition().name("address").type(list(nonNull(GraphQLString)))) - .field(newFieldDefinition().name("argField1").type(GraphQLString) - .argument(newArgument().name("arg1").type(GraphQLInt)) - .argument(newArgument().name("arg2").type(GraphQLInt)) - .argument(newArgument().name("arg3").type(GraphQLInt)) - .argument(newArgument().name("arg4").type(GraphQLString).defaultValueProgrammatic("XYZ")) - ) - + .argument(newArgument().name("arg1").type(GraphQLInt)) + .argument(newArgument().name("arg2").type(GraphQLInt)) + .argument(newArgument().name("arg3").type(GraphQLInt)) + .argument(newArgument().name("arg4").type(GraphQLString).defaultValueProgrammatic("XYZ"))) .field(newFieldDefinition().name("argField2").type(GraphQLString) - .argument(newArgument().name("arg1").type(GraphQLString)) - ) - + .argument(newArgument().name("arg1").type(GraphQLString))) .build() when: - new TypesImplementInterfaces().check(objType, errorCollector) + def errors = errorsFor(objType) then: - - errorCollector.containsValidationError(ObjectDoesNotImplementItsInterfaces) - def errors = errorCollector.getErrors() - errors.size() == 5 - errors.contains(new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, - "object type 'obj' does not implement interface 'Interface' because field 'friends' is missing")) - errors.contains(new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, - "object type 'obj' does not implement interface 'Interface' because field 'age' is defined as 'String' type and not as 'Int' type")) - errors.contains(new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, - "object type 'obj' does not implement interface 'Interface' because field 'argField1' argument 'arg1' is defined differently")) - errors.contains(new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, - "object type 'obj' does not implement interface 'Interface' because field 'argField1' argument 'arg3' is defined differently")) - errors.contains(new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, - "object type 'obj' does not implement interface 'Interface' because field 'argField2' is missing argument(s): 'arg2, arg3'")) + errors == [ + "object type 'obj' does not implement interface 'Interface' because field 'friends' is missing", + "object type 'obj' does not implement interface 'Interface' because field 'age' is defined as 'String' type and not as 'Int' type", + "object type 'obj' does not implement interface 'Interface' because field 'argField1' argument 'arg1' is defined differently", + "object type 'obj' does not implement interface 'Interface' because field 'argField1' argument 'arg3' is defined differently", + "object type 'obj' does not implement interface 'Interface' because field 'argField2' is missing argument(s): 'arg2, arg3'", + ] as Set } - def "field is object implementing interface"() { + def "field type compatibility: #scenario"() { given: - def person = newInterface() - .name("Person") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - def actor = newObject() - .name("Actor") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .withInterface(person) - .build() - - def prop = newObject() - .name("Prop") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - GraphQLInterfaceType interfaceType = newInterface() + def (interfaceFieldType, goodFieldType, badFieldType) = fieldTypes(scenario) + def interfaceType = newInterface() .name("TestInterface") - .field(newFieldDefinition().name("field").type(person).build()) + .field(newFieldDefinition().name("field").type(interfaceFieldType)) .build() - - GraphQLObjectType goodImpl = newObject() + def goodImpl = newObject() .name("GoodImpl") - .field(newFieldDefinition().name("field").type(actor).build()) + .field(newFieldDefinition().name("field").type(goodFieldType)) .withInterface(interfaceType) .build() - - GraphQLObjectType badImpl = newObject() + def badImpl = newObject() .name("BadImpl") - .field(newFieldDefinition().name("field").type(prop).build()) + .field(newFieldDefinition().name("field").type(badFieldType)) .withInterface(interfaceType) .build() - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(goodImpl, goodErrorCollector) - new TypesImplementInterfaces().check(badImpl, badErrorCollector) + expect: + errorsFor(goodImpl).isEmpty() + !errorsFor(badImpl).isEmpty() - then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() - } - - def "field is list of objects implementing interface"() { - given: - def person = newInterface() - .name("Person") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - def actor = newObject() - .name("Actor") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .withInterface(person) - .build() - - def prop = newObject() - .name("Prop") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - GraphQLInterfaceType interfaceType = newInterface() - .name("TestInterface") - .field(newFieldDefinition().name("field").type(list(person)).build()) - .build() - - GraphQLObjectType goodImpl = newObject() - .name("GoodImpl") - .field(newFieldDefinition().name("field").type(list(actor)).build()) - .withInterface(interfaceType) - .build() - - GraphQLObjectType badImpl = newObject() - .name("BadImpl") - .field(newFieldDefinition().name("field").type(list(prop)).build()) - .withInterface(interfaceType) - .build() - - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(goodImpl, goodErrorCollector) - new TypesImplementInterfaces().check(badImpl, badErrorCollector) - - then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() - } - - def "field is list of interfaces implementing interface" () { - given: - def person = newInterface() - .name("Person") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - def actor = newInterface() - .name("Actor") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .withInterface(person) - .build() - - def prop = newObject() - .name("Prop") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - GraphQLInterfaceType interfaceType = newInterface() - .name("TestInterface") - .field(newFieldDefinition().name("field").type(list(person)).build()) - .build() - - GraphQLObjectType goodImpl = newObject() - .name("GoodImpl") - .field(newFieldDefinition().name("field").type(list(actor)).build()) - .withInterface(interfaceType) - .build() - - GraphQLObjectType badImpl = newObject() - .name("BadImpl") - .field(newFieldDefinition().name("field").type(list(prop)).build()) - .withInterface(interfaceType) - .build() - - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(goodImpl, goodErrorCollector) - new TypesImplementInterfaces().check(badImpl, badErrorCollector) - - then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() + where: + scenario << [ + "object implementing interface", + "list of objects implementing interface", + "list of interfaces implementing interface", + "member of union", + "non-null", + ] } - def "field is member of union"() { - given: - def actor = newObject() - .name("Actor") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - def director = newObject() - .name("Director") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - def person = newUnionType() - .name("Person") - .possibleType(actor) - .possibleType(director) - .build() - - def prop = newObject() - .name("Prop") - .field(newFieldDefinition().name("name").type(GraphQLString).build()) - .build() - - GraphQLInterfaceType interfaceType = newInterface() - .name("TestInterface") - .field(newFieldDefinition().name("field").type(person).build()) - .build() - - GraphQLObjectType goodImpl = newObject() - .name("GoodImpl") - .field(newFieldDefinition().name("field").type(actor).build()) - .withInterface(interfaceType) - .build() - - GraphQLObjectType badImpl = newObject() - .name("BadImpl") - .field(newFieldDefinition().name("field").type(prop).build()) - .withInterface(interfaceType) - .build() - - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(goodImpl, goodErrorCollector) - new TypesImplementInterfaces().check(badImpl, badErrorCollector) - - then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() + // returns the interface field type, a compatible implementing field type and an incompatible one + static List fieldTypes(String scenario) { + def person = newInterface().name("Person").field(newFieldDefinition().name("name").type(GraphQLString)).build() + def prop = newObject().name("Prop").field(newFieldDefinition().name("name").type(GraphQLString)).build() + switch (scenario) { + case "object implementing interface": + return [person, actorImplementing(person), prop] + case "list of objects implementing interface": + return [list(person), list(actorImplementing(person)), list(prop)] + case "list of interfaces implementing interface": + def actor = newInterface().name("Actor").field(newFieldDefinition().name("name").type(GraphQLString)).withInterface(person).build() + return [list(person), list(actor), list(prop)] + case "member of union": + def actor = newObject().name("Actor").field(newFieldDefinition().name("name").type(GraphQLString)).build() + def director = newObject().name("Director").field(newFieldDefinition().name("name").type(GraphQLString)).build() + def union = newUnionType().name("Person").possibleType(actor).possibleType(director).build() + return [union, actor, prop] + case "non-null": + return [GraphQLString, nonNull(GraphQLString), nonNull(GraphQLInt)] + } + throw new IllegalArgumentException(scenario) } - def "field is non-null"() { - given: - GraphQLInterfaceType interfaceType = newInterface() - .name("TestInterface") - .field(newFieldDefinition().name("field").type(GraphQLString).build()) - .build() - - GraphQLObjectType goodImpl = newObject() - .name("GoodImpl") - .field(newFieldDefinition().name("field").type(nonNull(GraphQLString)).build()) - .withInterface(interfaceType) - .build() - - GraphQLObjectType badImpl = newObject() - .name("BadImpl") - .field(newFieldDefinition().name("field").type(nonNull(GraphQLInt)).build()) - .withInterface(interfaceType) - .build() - - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(goodImpl, goodErrorCollector) - new TypesImplementInterfaces().check(badImpl, badErrorCollector) - - then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() + static GraphQLObjectType actorImplementing(GraphQLInterfaceType person) { + newObject().name("Actor").field(newFieldDefinition().name("name").type(GraphQLString)).withInterface(person).build() } - def "field is a non null object"() { given: - GraphQLInterfaceType memberInterface = newInterface() + def memberInterface = newInterface() .name("TestMemberInterface") - .field(newFieldDefinition().name("field").type(GraphQLString).build()) + .field(newFieldDefinition().name("field").type(GraphQLString)) .build() - - GraphQLObjectType memberInterfaceImpl = newObject() + def memberInterfaceImpl = newObject() .name("TestMemberInterfaceImpl") - .field(newFieldDefinition().name("field").type(GraphQLString).build()) + .field(newFieldDefinition().name("field").type(GraphQLString)) .withInterface(memberInterface) .build() - - GraphQLInterfaceType testInterface = newInterface() + def testInterface = newInterface() .name("TestInterface") - .field(newFieldDefinition().name("field").type(nonNull(memberInterface)).build()) + .field(newFieldDefinition().name("field").type(nonNull(memberInterface))) .build() - - GraphQLObjectType testInterfaceImpl = newObject() + def testInterfaceImpl = newObject() .name("TestInterfaceImpl") - .field(newFieldDefinition().name("field").type(nonNull(memberInterfaceImpl)).build()) + .field(newFieldDefinition().name("field").type(nonNull(memberInterfaceImpl))) .withInterface(testInterface) .build() - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(testInterfaceImpl, goodErrorCollector) - - then: - goodErrorCollector.getErrors().isEmpty() + expect: + errorsFor(testInterfaceImpl).isEmpty() } def "type can declare extra optional field arguments"() { given: - - GraphQLInterfaceType InterfaceType = newInterface() + def interfaceType = newInterface() .name("Interface") .field(newFieldDefinition().name("argField").type(GraphQLString)) .build() - - SchemaValidationErrorCollector errorCollector = new SchemaValidationErrorCollector() - - GraphQLObjectType objType = newObject() + def objType = newObject() .name("Object") - .withInterface(InterfaceType) + .withInterface(interfaceType) .field(newFieldDefinition().name("argField").type(GraphQLString) - .argument(newArgument().name("arg1").type(GraphQLInt)) - ) + .argument(newArgument().name("arg1").type(GraphQLInt))) .build() - when: - new TypesImplementInterfaces().check(objType, errorCollector) - - then: - def errors = errorCollector.getErrors() - errors.isEmpty() + expect: + errorsFor(objType).isEmpty() } def "type should declare all arguments present in implemented interface"() { given: - - GraphQLInterfaceType InterfaceType = newInterface() + def interfaceType = newInterface() .name("Interface") .field(newFieldDefinition().name("argField").type(GraphQLString) .argument(newArgument().name("arg1").type(GraphQLInt)) - .argument(newArgument().name("arg2").type(GraphQLInt)) - ) + .argument(newArgument().name("arg2").type(GraphQLInt))) .build() - - SchemaValidationErrorCollector errorCollector = new SchemaValidationErrorCollector() - - GraphQLObjectType objType = newObject() + def objType = newObject() .name("Object") - .withInterface(InterfaceType) + .withInterface(interfaceType) .field(newFieldDefinition().name("argField").type(GraphQLString) .argument(newArgument().name("argX").type(GraphQLInt)) - .argument(newArgument().name("argZ").type(GraphQLInt)) - ) + .argument(newArgument().name("argZ").type(GraphQLInt))) .build() when: - new TypesImplementInterfaces().check(objType, errorCollector) + def errors = errorsFor(objType) then: - def errors = errorCollector.getErrors() - errors.size() == 1 - errors.iterator().next().description == "object type 'Object' does not implement interface 'Interface' because field 'argField' is missing argument(s): 'arg1, arg2'" + errors == ["object type 'Object' does not implement interface 'Interface' because field 'argField' is missing argument(s): 'arg1, arg2'"] as Set } def "type cannot declare extra non-null field arguments"() { given: - - GraphQLInterfaceType InterfaceType = newInterface() + def interfaceType = newInterface() .name("Interface") .field(newFieldDefinition().name("argField").type(GraphQLString)) .build() - - SchemaValidationErrorCollector errorCollector = new SchemaValidationErrorCollector() - - GraphQLObjectType objType = newObject() + def objType = newObject() .name("Object") - .withInterface(InterfaceType) + .withInterface(interfaceType) .field(newFieldDefinition().name("argField").type(GraphQLString) - .argument(newArgument().name("arg1").type(nonNull(GraphQLInt))) - ) + .argument(newArgument().name("arg1").type(nonNull(GraphQLInt)))) .build() when: - new TypesImplementInterfaces().check(objType, errorCollector) + def errors = errorsFor(objType) then: - def errors = errorCollector.getErrors() - errors.size() == 1 - errors.iterator().next().description == "object type 'Object' field 'argField' defines an additional non-optional argument 'arg1' which is not allowed because field is also defined in interface 'Interface'" + errors == ["object type 'Object' field 'argField' defines an additional non-optional argument 'arg1' which is not allowed because field is also defined in interface 'Interface'"] as Set } - def "type can change order of field arguments"() { + def "type can change order of fields"() { given: - - GraphQLInterfaceType InterfaceType = newInterface() + def interfaceType = newInterface() .name("Interface") .field(newFieldDefinition().name("argField1").type(GraphQLString)) .field(newFieldDefinition().name("argField2").type(GraphQLString)) .build() - - SchemaValidationErrorCollector errorCollector = new SchemaValidationErrorCollector() - - GraphQLObjectType objType = newObject() + def objType = newObject() .name("Object") - .withInterface(InterfaceType) + .withInterface(interfaceType) .field(newFieldDefinition().name("argField2").type(GraphQLString)) .field(newFieldDefinition().name("argField1").type(GraphQLString)) .build() + expect: + errorsFor(objType).isEmpty() + } + + def "interfaces declaring their transitive interfaces are valid"() { when: - new TypesImplementInterfaces().check(objType, errorCollector) + TestUtil.schema(''' + type Query { find: Image } + interface Node { id: ID! } + interface Resource implements Node { id: ID! url: String } + interface Image implements Resource & Node { id: ID! url: String thumbnail: String } + ''') then: - def errors = errorCollector.getErrors() - errors.isEmpty() + noExceptionThrown() } } From 56c99ea01d85aaa1bf2e10d0c32b256a7dc98348 Mon Sep 17 00:00:00 2001 From: Marc-Andre Giroux Date: Wed, 11 Nov 2026 18:15:46 -0500 Subject: [PATCH 2/2] Split SchemaValidator rules into SchemaValidationRule classes SchemaValidator keeps the single loop over types and directive definitions and calls the hooks of a SchemaValidationRule per rule class. Each validateSchema call creates its own rule instances, so per-validation state stays in final fields. InputValueValidator holds the value coercion shared by DefaultValuesAreValid and AppliedDirectiveArgumentsAreValid. --- .../AppliedDirectiveArgumentsAreValid.java | 53 ++ .../validation/AppliedDirectivesAreValid.java | 51 ++ .../validation/DefaultValuesAreValid.java | 51 ++ ...ecatedInputObjectAndArgumentsAreValid.java | 61 ++ .../InputAndOutputTypesUsedAppropriately.java | 96 +++ .../validation/InputValueValidator.java | 54 ++ .../NoDefaultValueCircularRefs.java | 175 ++++ .../validation/NoUnbrokenInputCycles.java | 79 ++ .../validation/OneOfInputObjectRules.java | 88 ++ .../validation/SchemaValidationRule.java | 60 ++ .../schema/validation/SchemaValidator.java | 765 ++---------------- .../schema/validation/TypeAndFieldRule.java | 155 ++++ .../validation/TypesImplementInterfaces.java | 175 ++++ .../validation/SchemaValidatorTest.groovy | 35 + .../TypesImplementInterfacesTest.groovy | 25 + 15 files changed, 1245 insertions(+), 678 deletions(-) create mode 100644 src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java create mode 100644 src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java create mode 100644 src/main/java/graphql/schema/validation/DefaultValuesAreValid.java create mode 100644 src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java create mode 100644 src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java create mode 100644 src/main/java/graphql/schema/validation/InputValueValidator.java create mode 100644 src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java create mode 100644 src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java create mode 100644 src/main/java/graphql/schema/validation/OneOfInputObjectRules.java create mode 100644 src/main/java/graphql/schema/validation/SchemaValidationRule.java create mode 100644 src/main/java/graphql/schema/validation/TypeAndFieldRule.java create mode 100644 src/main/java/graphql/schema/validation/TypesImplementInterfaces.java diff --git a/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java b/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java new file mode 100644 index 0000000000..8d76e0f530 --- /dev/null +++ b/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java @@ -0,0 +1,53 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLAppliedDirective; +import graphql.schema.GraphQLAppliedDirectiveArgument; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLDirective; +import graphql.schema.GraphQLDirectiveContainer; +import graphql.schema.GraphQLInputType; +import graphql.schema.InputValueWithState; +import org.jspecify.annotations.NullMarked; + +import static graphql.schema.GraphQLTypeUtil.isNonNull; +import static java.lang.String.format; + +/** + * Schema validation rule ensuring the argument values of applied directives are valid for their types. + */ +@Internal +@NullMarked +public class AppliedDirectiveArgumentsAreValid implements SchemaValidationRule { + + private final InputValueValidator inputValueValidator; + private final SchemaValidationErrorCollector errors; + + public AppliedDirectiveArgumentsAreValid(InputValueValidator inputValueValidator, SchemaValidationErrorCollector errors) { + this.inputValueValidator = inputValueValidator; + this.errors = errors; + } + + @Override + public void checkDirectiveContainer(GraphQLDirectiveContainer container) { + for (GraphQLDirective directive : container.getDirectives()) { + for (GraphQLArgument argument : directive.getArguments()) { + checkArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType()); + } + } + for (GraphQLAppliedDirective directive : container.getAppliedDirectives()) { + for (GraphQLAppliedDirectiveArgument argument : directive.getArguments()) { + checkArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType()); + } + } + } + + private void checkArgument(String directiveName, String argumentName, InputValueWithState argumentValue, GraphQLInputType argumentType) { + boolean invalid = !inputValueValidator.isValidValue(argumentValue, argumentType) + || (argumentValue.isNotSet() && isNonNull(argumentType)); + if (invalid) { + errors.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidAppliedDirectiveArgument, + format("Invalid argument '%s' for applied directive of name '%s'", argumentName, directiveName))); + } + } +} diff --git a/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java b/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java new file mode 100644 index 0000000000..9b880f7ede --- /dev/null +++ b/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java @@ -0,0 +1,51 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLDirective; +import graphql.schema.GraphQLDirectiveContainer; +import graphql.schema.GraphQLSchema; +import org.jspecify.annotations.NullMarked; + +import java.util.List; +import java.util.Map; + +import static java.lang.String.format; + +/** + * Schema validation rule ensuring applied directives are defined in the schema and that non repeatable + * directives are applied at most once. + */ +@Internal +@NullMarked +public class AppliedDirectivesAreValid implements SchemaValidationRule { + + private final GraphQLSchema schema; + private final SchemaValidationErrorCollector errors; + + public AppliedDirectivesAreValid(GraphQLSchema schema, SchemaValidationErrorCollector errors) { + this.schema = schema; + this.errors = errors; + } + + @Override + public void checkDirectiveContainer(GraphQLDirectiveContainer container) { + Map> directivesByName = container.getAllDirectivesByName(); + if (directivesByName.isEmpty()) { + return; + } + for (Map.Entry> entry : directivesByName.entrySet()) { + GraphQLDirective directiveDef = schema.getDirective(entry.getKey()); + if (directiveDef == null) { + addError(SchemaValidationErrorType.InvalidAppliedDirective, format("A definition for directive '%s' could not be found", entry.getKey())); + } else if (directiveDef.isNonRepeatable() && entry.getValue().size() > 1) { + addError(SchemaValidationErrorType.InvalidAppliedDirective, + format("The directive '%s' on the '%s' called '%s' is a non repeatable directive but has been applied %d times", + directiveDef.getName(), container.getClass().getSimpleName(), container.getName(), entry.getValue().size())); + } + } + } + + private void addError(SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); + } +} diff --git a/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java b/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java new file mode 100644 index 0000000000..caa14f5324 --- /dev/null +++ b/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java @@ -0,0 +1,51 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInputType; +import graphql.schema.GraphQLSchemaElement; +import graphql.schema.InputValueWithState; +import org.jspecify.annotations.NullMarked; + +import static graphql.schema.GraphQLTypeUtil.simplePrint; +import static java.lang.String.format; + +/** + * Schema validation rule ensuring argument and input field default values are valid for their types. + */ +@Internal +@NullMarked +public class DefaultValuesAreValid implements SchemaValidationRule { + + private final InputValueValidator inputValueValidator; + private final SchemaValidationErrorCollector errors; + + public DefaultValuesAreValid(InputValueValidator inputValueValidator, SchemaValidationErrorCollector errors) { + this.inputValueValidator = inputValueValidator; + this.errors = errors; + } + + @Override + public void checkInputObjectField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField) { + if (inputObjectField.hasSetDefaultValue()) { + checkDefaultValue(inputObjectField.getInputFieldDefaultValue(), inputObjectField.getType()); + } + } + + @Override + public void checkArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument) { + if (argument.hasSetDefaultValue()) { + checkDefaultValue(argument.getArgumentDefaultValue(), argument.getType()); + } + } + + private void checkDefaultValue(InputValueWithState defaultValue, GraphQLInputType type) { + if (inputValueValidator.isValidValue(defaultValue, type)) { + return; + } + errors.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidDefaultValue, + format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(type)))); + } +} diff --git a/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java b/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java new file mode 100644 index 0000000000..33ca884c8a --- /dev/null +++ b/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java @@ -0,0 +1,61 @@ +package graphql.schema.validation; + +import graphql.Directives; +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLDirective; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLSchemaElement; +import org.jspecify.annotations.NullMarked; + +import static graphql.schema.GraphQLTypeUtil.isNonNull; +import static java.lang.String.format; + +/** + * Spec: the @deprecated directive must not appear on required (non-null without a default) arguments + * or input object field definitions. + */ +@Internal +@NullMarked +public class DeprecatedInputObjectAndArgumentsAreValid implements SchemaValidationRule { + + private static final String DEPRECATED_DIRECTIVE_NAME = Directives.DEPRECATED_DIRECTIVE_DEFINITION.getName(); + + private final SchemaValidationErrorCollector errors; + + public DeprecatedInputObjectAndArgumentsAreValid(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField) { + if (!isNonNull(inputObjectField.getType()) || inputObjectField.hasSetDefaultValue()) { + return; + } + if (inputObjectField.getAppliedDirective(DEPRECATED_DIRECTIVE_NAME) == null) { + return; + } + addError(SchemaValidationErrorType.RequiredInputFieldCannotBeDeprecated, + format("Required input field '%s.%s' cannot be deprecated.", type.getName(), inputObjectField.getName())); + } + + @Override + public void checkArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument) { + if (!argument.isDeprecated() || !isNonNull(argument.getType()) || argument.hasSetDefaultValue()) { + return; + } + if (fieldOrDirective instanceof GraphQLFieldDefinition) { + addError(SchemaValidationErrorType.RequiredFieldArgumentCannotBeDeprecated, + format("Required argument '%s' on field '%s' cannot be deprecated.", argument.getName(), ((GraphQLFieldDefinition) fieldOrDirective).getName())); + } else if (fieldOrDirective instanceof GraphQLDirective) { + addError(SchemaValidationErrorType.RequiredDirectiveArgumentCannotBeDeprecated, + format("Required argument '%s' on directive '%s' cannot be deprecated.", argument.getName(), ((GraphQLDirective) fieldOrDirective).getName())); + } + } + + private void addError(SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); + } +} diff --git a/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java b/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java new file mode 100644 index 0000000000..531a8524c5 --- /dev/null +++ b/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java @@ -0,0 +1,96 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInputType; +import graphql.schema.GraphQLModifiedType; +import graphql.schema.GraphQLOutputType; +import graphql.schema.GraphQLType; +import org.jspecify.annotations.NullMarked; + +import static graphql.schema.GraphQLTypeUtil.simplePrint; +import static java.lang.String.format; + +/** + * Schema validation rule ensuring output types are only used in output positions and input types only in input positions. + */ +@Internal +@NullMarked +public class InputAndOutputTypesUsedAppropriately implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + + public InputAndOutputTypesUsedAppropriately(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition) { + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + if (hasMisusedType(argument.getType(), true)) { + String path = container.getName() + "." + fieldDefinition.getName() + "." + argument.getName(); + addTypeContextErrors(argument.getType(), true, path); + } + } + if (hasMisusedType(fieldDefinition.getType(), false)) { + String path = container.getName() + "." + fieldDefinition.getName(); + addTypeContextErrors(fieldDefinition.getType(), false, path); + } + } + + @Override + public void checkInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField) { + if (hasMisusedType(inputObjectField.getType(), true)) { + String path = type.getName() + "." + inputObjectField.getName(); + addTypeContextErrors(inputObjectField.getType(), true, path); + } + } + + private boolean hasMisusedType(GraphQLType type, boolean inputContext) { + GraphQLType current = type; + while (true) { + if (isMisused(current, inputContext)) { + return true; + } + if (!(current instanceof GraphQLModifiedType)) { + return false; + } + current = ((GraphQLModifiedType) current).getWrappedType(); + } + } + + private void addTypeContextErrors(GraphQLType type, boolean inputContext, String path) { + GraphQLType current = type; + while (true) { + if (isMisused(current, inputContext)) { + addTypeContextError(current, inputContext, path); + } + if (!(current instanceof GraphQLModifiedType)) { + return; + } + current = ((GraphQLModifiedType) current).getWrappedType(); + } + } + + private void addTypeContextError(GraphQLType misusedType, boolean inputContext, String path) { + if (inputContext) { + addError(SchemaValidationErrorType.OutputTypeUsedInInputTypeContext, + format("The output type '%s' has been used in an input type context : '%s'", simplePrint(misusedType), path)); + } else { + addError(SchemaValidationErrorType.InputTypeUsedInOutputTypeContext, + format("The input type '%s' has been used in a output type context : '%s'", simplePrint(misusedType), path)); + } + } + + private boolean isMisused(GraphQLType type, boolean inputContext) { + return inputContext ? !(type instanceof GraphQLInputType) : !(type instanceof GraphQLOutputType); + } + + private void addError(SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); + } +} diff --git a/src/main/java/graphql/schema/validation/InputValueValidator.java b/src/main/java/graphql/schema/validation/InputValueValidator.java new file mode 100644 index 0000000000..d3c28fbf35 --- /dev/null +++ b/src/main/java/graphql/schema/validation/InputValueValidator.java @@ -0,0 +1,54 @@ +package graphql.schema.validation; + +import graphql.GraphQLContext; +import graphql.Internal; +import graphql.execution.NonNullableValueCoercedAsNullException; +import graphql.execution.ValuesResolver; +import graphql.language.Value; +import graphql.schema.CoercingParseValueException; +import graphql.schema.GraphQLInputType; +import graphql.schema.GraphQLSchema; +import graphql.schema.InputValueWithState; +import graphql.validation.ValidationUtil; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.util.Locale; + +/** + * Checks that default values and applied directive argument values are valid for their input types. + */ +@Internal +@NullMarked +public class InputValueValidator { + + private final ValidationUtil validationUtil = new ValidationUtil(); + private final GraphQLContext graphQLContext = GraphQLContext.getDefault(); + private final GraphQLSchema schema; + private final SchemaValidationErrorCollector errors; + + public InputValueValidator(GraphQLSchema schema, SchemaValidationErrorCollector errors) { + this.schema = schema; + this.errors = errors; + } + + public boolean isValidValue(InputValueWithState value, GraphQLInputType type) { + if (value.isLiteral()) { + return validationUtil.isValidLiteralValue((Value) value.getValue(), type, schema, graphQLContext, Locale.getDefault()); + } + // coercing external values expands input field defaults, which never terminates once defaults form a cycle + if (!value.isExternal() || errors.containsValidationError(SchemaValidationErrorType.DefaultValueCircularRef)) { + return true; + } + return isValidExternalValue(value.getValue(), type); + } + + private boolean isValidExternalValue(@Nullable Object externalValue, GraphQLInputType type) { + try { + ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, graphQLContext, Locale.getDefault()); + return true; + } catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) { + return false; + } + } +} diff --git a/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java b/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java new file mode 100644 index 0000000000..1079a58c53 --- /dev/null +++ b/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java @@ -0,0 +1,175 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.language.ArrayValue; +import graphql.language.ObjectField; +import graphql.language.ObjectValue; +import graphql.language.Value; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLType; +import graphql.schema.InputValueWithState; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static graphql.schema.GraphQLTypeUtil.unwrapAll; + +/** + * Validates that {@code InputObjectDefaultValueHasCycle(inputObject)} is {@code false} + * for every input object type, as required by the Input Object type validation rules + * in the GraphQL specification. + *
+ * For example, consider this type configuration: + * + * input A { b:B = {} } + * input B { a:A = {} } + * + *
+ * The default values used in these types form a cycle that can create an infinitely large + * value. This validator rejects default values that can create these kinds of cycles. + * + * @see Input Objects Type Validation + */ +@Internal +@NullMarked +public class NoDefaultValueCircularRefs implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + + // coordinates already explored, so each cycle is reported only once + private final Set fullyExplored = new LinkedHashSet<>(); + + // the spec's "visitedFields" set, mutated and backtracked instead of copied at each step + private final LinkedHashSet visitedFields = new LinkedHashSet<>(); + + public NoDefaultValueCircularRefs(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkInputObjectType(GraphQLInputObjectType inputObjectType) { + // equivalent to InputObjectDefaultValueHasCycle(type, {}) without building the empty map + for (GraphQLInputObjectField field : inputObjectType.getFieldDefinitions()) { + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, false); + if (fieldInputObject != null) { + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObjectType.getName()); + } + } + } + + private void literalDefaultValueHasCycle(GraphQLInputObjectType inputObject, @Nullable Value defaultValue) { + if (defaultValue instanceof ArrayValue) { + for (Value itemValue : ((ArrayValue) defaultValue).getValues()) { + literalDefaultValueHasCycle(inputObject, itemValue); + } + return; + } + if (!(defaultValue instanceof ObjectValue)) { + return; + } + Map> defaultValueMap = new LinkedHashMap<>(); + for (ObjectField field : ((ObjectValue) defaultValue).getObjectFields()) { + defaultValueMap.put(field.getName(), field.getValue()); + } + for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { + boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); + if (fieldInputObject == null) { + continue; + } + if (hasDefaultValue) { + literalDefaultValueHasCycle(fieldInputObject, defaultValueMap.get(field.getName())); + } else { + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName()); + } + } + } + + private void externalDefaultValueHasCycle(GraphQLInputObjectType inputObject, Object defaultValue) { + if (defaultValue instanceof Iterable) { + externalListDefaultValueHasCycle(inputObject, (Iterable) defaultValue); + return; + } + if (!(defaultValue instanceof Map)) { + return; + } + Map defaultValueMap = (Map) defaultValue; + for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { + boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); + if (fieldInputObject == null) { + continue; + } + if (!hasDefaultValue) { + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName()); + continue; + } + Object fieldDefaultValue = defaultValueMap.get(field.getName()); + if (fieldDefaultValue != null) { + externalDefaultValueHasCycle(fieldInputObject, fieldDefaultValue); + } + } + } + + private void externalListDefaultValueHasCycle(GraphQLInputObjectType inputObject, Iterable defaultValues) { + for (Object itemValue : defaultValues) { + if (itemValue != null) { + externalDefaultValueHasCycle(inputObject, itemValue); + } + } + } + + private @Nullable GraphQLInputObjectType inputObjectTypeWithDefault(GraphQLInputObjectField field, boolean hasDefaultInParent) { + if (!hasDefaultInParent && field.getInputFieldDefaultValue().isNotSet()) { + return null; + } + GraphQLType namedFieldType = unwrapAll(field.getType()); + return namedFieldType instanceof GraphQLInputObjectType ? (GraphQLInputObjectType) namedFieldType : null; + } + + private void inputFieldDefaultValueHasCycle(GraphQLInputObjectField field, GraphQLInputObjectType namedFieldType, String parentTypeName) { + InputValueWithState fieldDefaultValue = field.getInputFieldDefaultValue(); + String coordinate = parentTypeName + "." + field.getName(); + if (visitedFields.contains(coordinate)) { + errors.addError(new SchemaValidationError(SchemaValidationErrorType.DefaultValueCircularRef, cycleMessage(coordinate))); + return; + } + if (!fullyExplored.add(coordinate)) { + return; + } + visitedFields.add(coordinate); + if (fieldDefaultValue.isLiteral() && fieldDefaultValue.getValue() instanceof Value) { + literalDefaultValueHasCycle(namedFieldType, (Value) fieldDefaultValue.getValue()); + } else if (fieldDefaultValue.isExternal() && fieldDefaultValue.getValue() != null) { + externalDefaultValueHasCycle(namedFieldType, fieldDefaultValue.getValue()); + } + visitedFields.remove(coordinate); + } + + private String cycleMessage(String coordinate) { + List intermediaries = new ArrayList<>(); + boolean found = false; + for (String entry : visitedFields) { + if (found) { + intermediaries.add(entry); + } + if (entry.equals(coordinate)) { + found = true; + } + } + if (intermediaries.isEmpty()) { + return "Invalid circular reference. The default value of Input Object field " + + coordinate + " references itself."; + } + return "Invalid circular reference. The default value of Input Object field " + + coordinate + " references itself via the default values of: " + + String.join(", ", intermediaries) + "."; + } +} diff --git a/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java b/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java new file mode 100644 index 0000000000..6382f4594f --- /dev/null +++ b/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java @@ -0,0 +1,79 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInputType; +import graphql.schema.GraphQLNonNull; +import graphql.schema.GraphQLType; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; + +import static graphql.schema.GraphQLTypeUtil.isList; +import static graphql.schema.GraphQLTypeUtil.unwrapAll; + +/** + * Schema validation rule ensuring no input type forms an unbroken non-nullable recursion, + * as such a type would be impossible to satisfy + */ +@Internal +@NullMarked +public class NoUnbrokenInputCycles implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + // results only depend on the argument's input type, so each type is explored once + private final Set checkedArgumentTypes = Collections.newSetFromMap(new IdentityHashMap<>()); + + public NoUnbrokenInputCycles(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition) { + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + GraphQLInputType argumentType = argument.getType(); + if (argumentType instanceof GraphQLInputObjectType && checkedArgumentTypes.add((GraphQLInputObjectType) argumentType)) { + check((GraphQLInputObjectType) argumentType, Collections.newSetFromMap(new IdentityHashMap<>()), new ArrayList<>()); + } + } + } + + // path entries deliberately accumulate across sibling fields, which existing error messages rely on + private void check(GraphQLInputObjectType type, Set pathTypes, List path) { + if (!pathTypes.add(type)) { + errors.addError(new SchemaValidationError(SchemaValidationErrorType.UnbrokenInputCycle, "[" + String.join(".", path) + "] forms an unsatisfiable cycle")); + return; + } + int pathSizeOnEntry = path.size(); + for (GraphQLInputObjectField field : type.getFieldDefinitions()) { + GraphQLInputObjectType next = nonNullInputObjectType(field.getType()); + if (next != null) { + path.add(field.getName() + "!"); + check(next, pathTypes, path); + } + } + path.subList(pathSizeOnEntry, path.size()).clear(); + pathTypes.remove(type); + } + + private @Nullable GraphQLInputObjectType nonNullInputObjectType(GraphQLInputType type) { + if (!(type instanceof GraphQLNonNull)) { + return null; + } + GraphQLType wrappedType = ((GraphQLNonNull) type).getWrappedType(); + if (isList(wrappedType)) { + return null; + } + GraphQLType unwrapped = unwrapAll(wrappedType); + return unwrapped instanceof GraphQLInputObjectType ? (GraphQLInputObjectType) unwrapped : null; + } +} diff --git a/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java b/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java new file mode 100644 index 0000000000..8f6c20a783 --- /dev/null +++ b/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java @@ -0,0 +1,88 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLType; +import org.jspecify.annotations.NullMarked; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import static graphql.schema.GraphQLTypeUtil.isList; +import static graphql.schema.GraphQLTypeUtil.isNonNull; +import static graphql.schema.GraphQLTypeUtil.unwrapAll; +import static java.lang.String.format; + +/** + * Spec: if the Input Object is a OneOf Input Object then the type of each input field must be nullable, + * no input field can have a default value, and the type must be inhabited by a finite value. + */ +@Internal +@NullMarked +public class OneOfInputObjectRules implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + + public OneOfInputObjectRules(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkInputObjectType(GraphQLInputObjectType inputObjectType) { + if (!inputObjectType.isOneOf()) { + return; + } + if (!canBeProvidedAFiniteValue(inputObjectType, Collections.newSetFromMap(new IdentityHashMap<>()))) { + addError(SchemaValidationErrorType.OneOfNotInhabited, + format("OneOf Input Object %s must be inhabited but all fields recursively reference only other OneOf Input Objects forming an unresolvable cycle.", inputObjectType.getName())); + } + } + + private boolean canBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { + if (!visited.add(oneOfInputObject)) { + return false; + } + boolean result = anyFieldCanBeProvidedAFiniteValue(oneOfInputObject, visited); + visited.remove(oneOfInputObject); + return result; + } + + private boolean anyFieldCanBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { + for (GraphQLInputObjectField field : oneOfInputObject.getFieldDefinitions()) { + GraphQLType fieldType = field.getType(); + if (isList(fieldType)) { + return true; + } + GraphQLType namedFieldType = unwrapAll(fieldType); + if (!(namedFieldType instanceof GraphQLInputObjectType)) { + return true; + } + GraphQLInputObjectType inputFieldType = (GraphQLInputObjectType) namedFieldType; + if (!inputFieldType.isOneOf() || canBeProvidedAFiniteValue(inputFieldType, visited)) { + return true; + } + } + return false; + } + + @Override + public void checkInputObjectField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField) { + if (!inputObjectType.isOneOf()) { + return; + } + if (inputObjectField.hasSetDefaultValue()) { + addError(SchemaValidationErrorType.OneOfDefaultValueOnField, + format("OneOf input field %s.%s cannot have a default value.", inputObjectType.getName(), inputObjectField.getName())); + } + if (isNonNull(inputObjectField.getType())) { + addError(SchemaValidationErrorType.OneOfNonNullableField, + format("OneOf input field %s.%s must be nullable.", inputObjectType.getName(), inputObjectField.getName())); + } + } + + private void addError(SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); + } +} diff --git a/src/main/java/graphql/schema/validation/SchemaValidationRule.java b/src/main/java/graphql/schema/validation/SchemaValidationRule.java new file mode 100644 index 0000000000..340cb6fad0 --- /dev/null +++ b/src/main/java/graphql/schema/validation/SchemaValidationRule.java @@ -0,0 +1,60 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLDirectiveContainer; +import graphql.schema.GraphQLEnumType; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInterfaceType; +import graphql.schema.GraphQLObjectType; +import graphql.schema.GraphQLSchemaElement; +import graphql.schema.GraphQLUnionType; +import org.jspecify.annotations.NullMarked; + +/** + * A schema validation rule. {@link SchemaValidator} calls each hook once for every matching element of the schema; + * rules override the hooks they need and report problems to the error collector they were created with. + */ +@Internal +@NullMarked +public interface SchemaValidationRule { + + default void checkObjectType(GraphQLObjectType objectType) { + } + + default void checkInterfaceType(GraphQLInterfaceType interfaceType) { + } + + default void checkUnionType(GraphQLUnionType unionType) { + } + + default void checkEnumType(GraphQLEnumType enumType) { + } + + default void checkInputObjectType(GraphQLInputObjectType inputObjectType) { + } + + default void checkFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition) { + } + + default void checkInputObjectField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField) { + } + + /** + * @param fieldOrDirective the field definition or directive definition declaring the argument + * @param argument the argument + */ + default void checkArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument) { + } + + /** + * Called for every type, field, argument, input field, enum value and directive definition. + * + * @param container the element that directives can be applied to + */ + default void checkDirectiveContainer(GraphQLDirectiveContainer container) { + } +} diff --git a/src/main/java/graphql/schema/validation/SchemaValidator.java b/src/main/java/graphql/schema/validation/SchemaValidator.java index e50944d910..828abc87f8 100644 --- a/src/main/java/graphql/schema/validation/SchemaValidator.java +++ b/src/main/java/graphql/schema/validation/SchemaValidator.java @@ -1,18 +1,7 @@ package graphql.schema.validation; -import graphql.Directives; -import graphql.GraphQLContext; import graphql.Internal; import graphql.execution.InputValueLimits; -import graphql.execution.NonNullableValueCoercedAsNullException; -import graphql.execution.ValuesResolver; -import graphql.language.ArrayValue; -import graphql.language.ObjectField; -import graphql.language.ObjectValue; -import graphql.language.Value; -import graphql.schema.CoercingParseValueException; -import graphql.schema.GraphQLAppliedDirective; -import graphql.schema.GraphQLAppliedDirectiveArgument; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLDirective; import graphql.schema.GraphQLDirectiveContainer; @@ -20,752 +9,172 @@ import graphql.schema.GraphQLEnumValueDefinition; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLFieldsContainer; -import graphql.schema.GraphQLImplementingType; import graphql.schema.GraphQLInputObjectField; import graphql.schema.GraphQLInputObjectType; -import graphql.schema.GraphQLInputType; import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLModifiedType; -import graphql.schema.GraphQLNamedOutputType; import graphql.schema.GraphQLNamedType; -import graphql.schema.GraphQLNonNull; import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLOutputType; import graphql.schema.GraphQLScalarType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLSchemaElement; -import graphql.schema.GraphQLType; import graphql.schema.GraphQLUnionType; -import graphql.schema.InputValueWithState; -import graphql.validation.ValidationUtil; import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Locale; -import java.util.Map; import java.util.Set; -import static graphql.introspection.Introspection.INTROSPECTION_SYSTEM_FIELDS; -import static graphql.introspection.Introspection.isIntrospectionTypes; -import static graphql.schema.GraphQLTypeUtil.isList; -import static graphql.schema.GraphQLTypeUtil.isNonNull; -import static graphql.schema.GraphQLTypeUtil.simplePrint; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; -import static graphql.schema.GraphQLTypeUtil.unwrapOne; -import static graphql.schema.validation.SchemaValidationErrorType.ObjectDoesNotImplementItsInterfaces; -import static java.lang.String.format; - +/** + * Validates a schema by visiting each of its types, their fields, arguments, input fields and enum values, and each + * directive definition once, calling the matching {@link SchemaValidationRule} hooks for every element. + */ @Internal @NullMarked public class SchemaValidator { - private static final String DEPRECATED_DIRECTIVE_NAME = Directives.DEPRECATED_DIRECTIVE_DEFINITION.getName(); - - private final ValidationUtil validationUtil = new ValidationUtil(); - public Set validateSchema(GraphQLSchema schema) { - GraphQLContext context = GraphQLContext.getDefault(); SchemaValidationErrorCollector errors = new SchemaValidationErrorCollector(); new DefaultValueDepth(InputValueLimits.getDefaultLimits().getMaxDepth()).check(schema, errors); if (!errors.getErrors().isEmpty()) { return errors.getErrors(); } - // unbroken input cycle results only depend on the argument's input type, so each type is explored once - Set checkedCycleRoots = newIdentitySet(); - List types = schema.getAllTypesAsList(); + + // runs first because value validation must not coerce default values that form a cycle checkDefaultValueCycles(types, errors); + + SchemaValidationRule[] rules = createRules(schema, errors); for (GraphQLNamedType type : types) { - if (type instanceof GraphQLObjectType) { - validateObjectType((GraphQLObjectType) type, checkedCycleRoots, schema, context, errors); - } else if (type instanceof GraphQLInterfaceType) { - validateInterfaceType((GraphQLInterfaceType) type, checkedCycleRoots, schema, context, errors); - } else if (type instanceof GraphQLInputObjectType) { - validateInputObjectType((GraphQLInputObjectType) type, schema, context, errors); - } else if (type instanceof GraphQLEnumType) { - validateEnumType((GraphQLEnumType) type, schema, context, errors); - } else if (type instanceof GraphQLUnionType) { - validateUnionType((GraphQLUnionType) type, schema, context, errors); - } else if (type instanceof GraphQLScalarType) { - checkDirectiveContainer((GraphQLScalarType) type, schema, context, errors); - } + validateType(type, rules); } for (GraphQLDirective directive : schema.getDirectives()) { - validateDirectiveDefinition(directive, schema, context, errors); + validateDirectiveDefinition(directive, rules); } return errors.getErrors(); } - private Set newIdentitySet() { - return Collections.newSetFromMap(new IdentityHashMap<>()); - } - - private void validateObjectType(GraphQLObjectType type, Set checkedCycleRoots, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - List fieldDefinitions = type.getFieldDefinitions(); - checkImplementsInterfaces(type, errors); - if (!isIntrospectionTypes(type)) { - checkFieldsContainer(type, fieldDefinitions, errors); - } - checkDirectiveContainer(type, schema, context, errors); - for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { - validateFieldDefinition(type, fieldDefinition, checkedCycleRoots, schema, context, errors); - } - } - - private void validateInterfaceType(GraphQLInterfaceType type, Set checkedCycleRoots, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - List fieldDefinitions = type.getFieldDefinitions(); - checkImplementsInterfaces(type, errors); - checkFieldsContainer(type, fieldDefinitions, errors); - checkDirectiveContainer(type, schema, context, errors); - for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { - validateFieldDefinition(type, fieldDefinition, checkedCycleRoots, schema, context, errors); - } - } - - private void validateUnionType(GraphQLUnionType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - if (!isIntrospectionTypes(type)) { - checkUnion(type, errors); - } - checkDirectiveContainer(type, schema, context, errors); - } - - private void validateEnumType(GraphQLEnumType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - List values = type.getValues(); - if (!isIntrospectionTypes(type)) { - checkEnum(type, values, errors); - } - checkDirectiveContainer(type, schema, context, errors); - for (GraphQLEnumValueDefinition value : values) { - checkDirectiveContainer(value, schema, context, errors); - } - } - - private void validateInputObjectType(GraphQLInputObjectType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - List fields = type.getFieldDefinitions(); - if (!isIntrospectionTypes(type)) { - checkInputObject(type, fields, errors); - } - checkDirectiveContainer(type, schema, context, errors); - checkOneOfInhabited(type, errors); - for (GraphQLInputObjectField field : fields) { - validateInputObjectField(type, field, schema, context, errors); - } - } - - private void validateFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition, Set checkedCycleRoots, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - checkNoUnbrokenInputCycles(fieldDefinition, checkedCycleRoots, errors); - checkDirectiveContainer(fieldDefinition, schema, context, errors); - checkFieldTypesUsedAppropriately(container, fieldDefinition, errors); - for (GraphQLArgument argument : fieldDefinition.getArguments()) { - validateArgument(argument, fieldDefinition, schema, context, errors); - } - } - - private void validateInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField field, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - if (field.hasSetDefaultValue()) { - checkDefaultValue(field.getInputFieldDefaultValue(), field.getType(), schema, context, errors); - } - checkDirectiveContainer(field, schema, context, errors); - checkInputFieldTypeUsedAppropriately(type, field, errors); - checkOneOfField(type, field, errors); - checkDeprecatedInputField(type, field, errors); - } - - private void validateArgument(GraphQLArgument argument, GraphQLSchemaElement fieldOrDirective, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - if (argument.hasSetDefaultValue()) { - checkDefaultValue(argument.getArgumentDefaultValue(), argument.getType(), schema, context, errors); - } - checkDirectiveContainer(argument, schema, context, errors); - checkDeprecatedArgument(argument, fieldOrDirective, errors); - } - - private void validateDirectiveDefinition(GraphQLDirective directive, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - checkDirectiveContainer(directive, schema, context, errors); - for (GraphQLArgument argument : directive.getArguments()) { - validateArgument(argument, directive, schema, context, errors); - } - } - - private void checkDirectiveContainer(GraphQLDirectiveContainer container, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - checkAppliedDirectives(container, schema, errors); - for (GraphQLDirective directive : container.getDirectives()) { - for (GraphQLArgument argument : directive.getArguments()) { - checkAppliedDirectiveArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType(), schema, context, errors); - } - } - for (GraphQLAppliedDirective directive : container.getAppliedDirectives()) { - for (GraphQLAppliedDirectiveArgument argument : directive.getArguments()) { - checkAppliedDirectiveArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType(), schema, context, errors); - } - } - } - - private void addError(SchemaValidationErrorCollector errors, SchemaValidationErrorType errorType, String message) { - errors.addError(new SchemaValidationError(errorType, message)); - } - - private void checkNoUnbrokenInputCycles(GraphQLFieldDefinition fieldDefinition, Set checkedCycleRoots, SchemaValidationErrorCollector errors) { - for (GraphQLArgument argument : fieldDefinition.getArguments()) { - GraphQLInputType argumentType = argument.getType(); - if (argumentType instanceof GraphQLInputObjectType && checkedCycleRoots.add((GraphQLInputObjectType) argumentType)) { - checkUnbrokenInputCycle((GraphQLInputObjectType) argumentType, newIdentitySet(), new ArrayList<>(), errors); - } - } - } - - // path entries deliberately accumulate across sibling fields, which existing error messages rely on - private void checkUnbrokenInputCycle(GraphQLInputObjectType type, Set pathTypes, List path, SchemaValidationErrorCollector errors) { - if (!pathTypes.add(type)) { - addError(errors, SchemaValidationErrorType.UnbrokenInputCycle, "[" + String.join(".", path) + "] forms an unsatisfiable cycle"); - return; - } - int pathSizeOnEntry = path.size(); - for (GraphQLInputObjectField field : type.getFieldDefinitions()) { - GraphQLInputObjectType next = nonNullInputObjectType(field.getType()); - if (next != null) { - path.add(field.getName() + "!"); - checkUnbrokenInputCycle(next, pathTypes, path, errors); - } - } - path.subList(pathSizeOnEntry, path.size()).clear(); - pathTypes.remove(type); - } - - private @Nullable GraphQLInputObjectType nonNullInputObjectType(GraphQLInputType type) { - if (!(type instanceof GraphQLNonNull)) { - return null; - } - GraphQLType wrappedType = ((GraphQLNonNull) type).getWrappedType(); - if (isList(wrappedType)) { - return null; - } - GraphQLType unwrapped = unwrapAll(wrappedType); - return unwrapped instanceof GraphQLInputObjectType ? (GraphQLInputObjectType) unwrapped : null; - } - private void checkDefaultValueCycles(List types, SchemaValidationErrorCollector errors) { - // coordinates already explored, so each cycle is reported only once - Set exploredDefaults = new LinkedHashSet<>(); + NoDefaultValueCircularRefs noDefaultValueCircularRefs = new NoDefaultValueCircularRefs(errors); for (GraphQLNamedType type : types) { if (type instanceof GraphQLInputObjectType) { - checkNoDefaultValueCircularRefs((GraphQLInputObjectType) type, exploredDefaults, errors); - } - } - } - - private void checkNoDefaultValueCircularRefs(GraphQLInputObjectType type, Set exploredDefaults, SchemaValidationErrorCollector errors) { - @Nullable LinkedHashSet visitedFields = null; - // equivalent to InputObjectDefaultValueHasCycle(type, {}) without building the empty map - for (GraphQLInputObjectField field : type.getFieldDefinitions()) { - if (field.getInputFieldDefaultValue().isNotSet()) { - continue; - } - GraphQLType namedFieldType = unwrapAll(field.getType()); - if (namedFieldType instanceof GraphQLInputObjectType) { - visitedFields = visitedFields == null ? new LinkedHashSet<>() : visitedFields; - inputFieldDefaultValueHasCycle(field, (GraphQLInputObjectType) namedFieldType, type.getName(), exploredDefaults, visitedFields, errors); - } - } - } - - private void literalDefaultValueHasCycle(GraphQLInputObjectType inputObject, @Nullable Value defaultValue, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { - if (defaultValue instanceof ArrayValue) { - for (Value itemValue : ((ArrayValue) defaultValue).getValues()) { - literalDefaultValueHasCycle(inputObject, itemValue, exploredDefaults, visitedFields, errors); - } - return; - } - if (!(defaultValue instanceof ObjectValue)) { - return; - } - Map> defaultValueMap = new LinkedHashMap<>(); - for (ObjectField field : ((ObjectValue) defaultValue).getObjectFields()) { - defaultValueMap.put(field.getName(), field.getValue()); - } - for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { - boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); - GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); - if (fieldInputObject == null) { - continue; - } - if (hasDefaultValue) { - literalDefaultValueHasCycle(fieldInputObject, defaultValueMap.get(field.getName()), exploredDefaults, visitedFields, errors); - } else { - inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), exploredDefaults, visitedFields, errors); - } - } - } - - private void externalDefaultValueHasCycle(GraphQLInputObjectType inputObject, Object defaultValue, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { - if (defaultValue instanceof Iterable) { - externalListDefaultValueHasCycle(inputObject, (Iterable) defaultValue, exploredDefaults, visitedFields, errors); - return; - } - if (!(defaultValue instanceof Map)) { - return; - } - Map defaultValueMap = (Map) defaultValue; - for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { - boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); - GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); - if (fieldInputObject == null) { - continue; - } - if (!hasDefaultValue) { - inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), exploredDefaults, visitedFields, errors); - continue; - } - Object fieldDefaultValue = defaultValueMap.get(field.getName()); - if (fieldDefaultValue != null) { - externalDefaultValueHasCycle(fieldInputObject, fieldDefaultValue, exploredDefaults, visitedFields, errors); - } - } - } - - private void externalListDefaultValueHasCycle(GraphQLInputObjectType inputObject, Iterable defaultValues, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { - for (Object itemValue : defaultValues) { - if (itemValue != null) { - externalDefaultValueHasCycle(inputObject, itemValue, exploredDefaults, visitedFields, errors); - } - } - } - - private @Nullable GraphQLInputObjectType inputObjectTypeWithDefault(GraphQLInputObjectField field, boolean hasDefaultInParent) { - if (!hasDefaultInParent && field.getInputFieldDefaultValue().isNotSet()) { - return null; - } - GraphQLType namedFieldType = unwrapAll(field.getType()); - return namedFieldType instanceof GraphQLInputObjectType ? (GraphQLInputObjectType) namedFieldType : null; - } - - private void inputFieldDefaultValueHasCycle(GraphQLInputObjectField field, GraphQLInputObjectType namedFieldType, String parentTypeName, Set exploredDefaults, LinkedHashSet visitedFields, SchemaValidationErrorCollector errors) { - InputValueWithState fieldDefaultValue = field.getInputFieldDefaultValue(); - String coordinate = parentTypeName + "." + field.getName(); - if (visitedFields.contains(coordinate)) { - addError(errors, SchemaValidationErrorType.DefaultValueCircularRef, defaultValueCycleMessage(coordinate, visitedFields)); - return; - } - if (!exploredDefaults.add(coordinate)) { - return; - } - visitedFields.add(coordinate); - if (fieldDefaultValue.isLiteral() && fieldDefaultValue.getValue() instanceof Value) { - literalDefaultValueHasCycle(namedFieldType, (Value) fieldDefaultValue.getValue(), exploredDefaults, visitedFields, errors); - } else if (fieldDefaultValue.isExternal() && fieldDefaultValue.getValue() != null) { - externalDefaultValueHasCycle(namedFieldType, fieldDefaultValue.getValue(), exploredDefaults, visitedFields, errors); - } - visitedFields.remove(coordinate); - } - - private String defaultValueCycleMessage(String coordinate, LinkedHashSet visitedFields) { - List intermediaries = new ArrayList<>(); - boolean found = false; - for (String entry : visitedFields) { - if (found) { - intermediaries.add(entry); - } - if (entry.equals(coordinate)) { - found = true; - } - } - if (intermediaries.isEmpty()) { - return "Invalid circular reference. The default value of Input Object field " - + coordinate + " references itself."; - } - return "Invalid circular reference. The default value of Input Object field " - + coordinate + " references itself via the default values of: " - + String.join(", ", intermediaries) + "."; - } - - private void checkImplementsInterfaces(GraphQLImplementingType implementingType, SchemaValidationErrorCollector errors) { - List interfaces = implementingType.getInterfaces(); - for (GraphQLNamedOutputType interfaceType : interfaces) { - checkObjectImplementsInterface(implementingType, (GraphQLInterfaceType) interfaceType, errors); - } - } - - private void checkObjectImplementsInterface(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector errors) { - for (GraphQLFieldDefinition interfaceFieldDef : interfaceType.getFieldDefinitions()) { - GraphQLFieldDefinition objectFieldDef = implementingType.getFieldDefinition(interfaceFieldDef.getName()); - if (objectFieldDef == null) { - addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' is missing", - typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName())); - } else { - checkFieldTypeCompatibility(implementingType, interfaceType, interfaceFieldDef, objectFieldDef, errors); - } - } - checkTransitiveImplementations(implementingType, interfaceType, errors); - } - - private void checkTransitiveImplementations(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector errors) { - List implementedInterfaces = implementingType.getInterfaces(); - for (GraphQLNamedOutputType transitiveInterface : interfaceType.getInterfaces()) { - if (transitiveInterface.equals(implementingType)) { - addInterfaceError(errors, format("%s type '%s' cannot implement '%s' because that would result on a circular reference", - typeOf(implementingType), implementingType.getName(), interfaceType.getName())); - } else if (!implementedInterfaces.contains(transitiveInterface)) { - addInterfaceError(errors, format("%s type '%s' must implement '%s' because it is implemented by '%s'", - typeOf(implementingType), implementingType.getName(), transitiveInterface.getName(), interfaceType.getName())); - } - } - } - - private void checkFieldTypeCompatibility(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef, SchemaValidationErrorCollector errors) { - if (isCompatible(interfaceFieldDef.getType(), objectFieldDef.getType())) { - checkFieldArgumentEquivalence(implementingType, interfaceType, interfaceFieldDef, objectFieldDef, errors); - return; - } - addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' is defined as '%s' type and not as '%s' type", - typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), - simplePrint(objectFieldDef.getType()), simplePrint(interfaceFieldDef.getType()))); - } - - private void checkFieldArgumentEquivalence(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef, SchemaValidationErrorCollector errors) { - List interfaceArgs = interfaceFieldDef.getArguments(); - for (GraphQLArgument interfaceArg : interfaceArgs) { - if (objectFieldDef.getArgument(interfaceArg.getName()) == null) { - addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' is missing argument(s): '%s'", - typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), - missingArgumentNames(interfaceArgs, objectFieldDef))); - return; - } - } - for (GraphQLArgument objectArg : objectFieldDef.getArguments()) { - GraphQLArgument interfaceArg = interfaceFieldDef.getArgument(objectArg.getName()); - if (interfaceArg == null) { - checkAdditionalArgumentIsOptional(implementingType, interfaceType, objectFieldDef, objectArg, errors); - } else if (!isSameType(objectArg.getType(), interfaceArg.getType())) { - addInterfaceError(errors, format("%s type '%s' does not implement interface '%s' because field '%s' argument '%s' is defined differently", - typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), objectArg.getName())); + noDefaultValueCircularRefs.checkInputObjectType((GraphQLInputObjectType) type); } } } - private void checkAdditionalArgumentIsOptional(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition objectFieldDef, GraphQLArgument objectArg, SchemaValidationErrorCollector errors) { - if (objectArg.getType() instanceof GraphQLNonNull) { - addInterfaceError(errors, format("%s type '%s' field '%s' defines an additional non-optional argument '%s' which is not allowed because field is also defined in interface '%s'", - typeOf(implementingType), implementingType.getName(), objectFieldDef.getName(), objectArg.getName(), interfaceType.getName())); - } - } - - private String missingArgumentNames(List interfaceArgs, GraphQLFieldDefinition objectFieldDef) { - Set missing = new LinkedHashSet<>(); - for (GraphQLArgument interfaceArg : interfaceArgs) { - if (objectFieldDef.getArgument(interfaceArg.getName()) == null) { - missing.add(interfaceArg.getName()); - } - } - return String.join(", ", missing); - } - - private void addInterfaceError(SchemaValidationErrorCollector errors, String message) { - addError(errors, ObjectDoesNotImplementItsInterfaces, message); - } - - private String typeOf(GraphQLImplementingType implementingType) { - return implementingType instanceof GraphQLObjectType ? "object" : "interface"; - } - - private boolean isCompatible(GraphQLOutputType constraintType, GraphQLOutputType objectType) { - if (isSameType(constraintType, objectType)) { - return true; - } else if (constraintType instanceof GraphQLUnionType) { - return ((GraphQLUnionType) constraintType).getTypes().contains(objectType); - } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLObjectType) { - return ((GraphQLObjectType) objectType).getInterfaces().contains(constraintType); - } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLInterfaceType) { - return ((GraphQLInterfaceType) objectType).getInterfaces().contains(constraintType); - } else if (isList(constraintType) && isList(objectType)) { - return isCompatible((GraphQLOutputType) unwrapOne(constraintType), (GraphQLOutputType) unwrapOne(objectType)); - } else if (isNonNull(objectType)) { - GraphQLOutputType nullableConstraint = isNonNull(constraintType) ? (GraphQLOutputType) unwrapOne(constraintType) : constraintType; - return isCompatible(nullableConstraint, (GraphQLOutputType) unwrapOne(objectType)); - } - return false; - } - - // equivalent to comparing GraphQLTypeUtil.simplePrint() of both types - private boolean isSameType(GraphQLType first, GraphQLType second) { - GraphQLType left = first; - GraphQLType right = second; - while (true) { - boolean leftNonNull = isNonNull(left); - boolean leftList = isList(left); - if (leftNonNull != isNonNull(right) || leftList != isList(right)) { - return false; - } - if (!leftNonNull && !leftList) { - return ((GraphQLNamedType) left).getName().equals(((GraphQLNamedType) right).getName()); - } - left = unwrapOne(left); - right = unwrapOne(right); - } - } - - private void checkFieldsContainer(GraphQLFieldsContainer type, List fieldDefinitions, SchemaValidationErrorCollector errors) { - if (fieldDefinitions.isEmpty()) { - addError(errors, SchemaValidationErrorType.ImplementingTypeLackOfFieldError, format("\"%s\" must define one or more fields.", type.getName())); - return; - } - for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { - checkFieldName(type.getName(), fieldDefinition.getName(), errors); - for (GraphQLArgument argument : fieldDefinition.getArguments()) { - checkArgumentName(type.getName(), fieldDefinition.getName(), argument.getName(), errors); - } - } - } - - private void checkInputObject(GraphQLInputObjectType type, List fields, SchemaValidationErrorCollector errors) { - if (fields.isEmpty()) { - addError(errors, SchemaValidationErrorType.InputObjectTypeLackOfFieldError, format("\"%s\" must define one or more fields.", type.getName())); - return; - } - for (GraphQLInputObjectField field : fields) { - checkFieldName(type.getName(), field.getName(), errors); - } + private SchemaValidationRule[] createRules(GraphQLSchema schema, SchemaValidationErrorCollector errors) { + InputValueValidator inputValueValidator = new InputValueValidator(schema, errors); + return new SchemaValidationRule[]{ + new NoUnbrokenInputCycles(errors), + new TypesImplementInterfaces(errors), + new TypeAndFieldRule(errors), + new DefaultValuesAreValid(inputValueValidator, errors), + new AppliedDirectivesAreValid(schema, errors), + new AppliedDirectiveArgumentsAreValid(inputValueValidator, errors), + new InputAndOutputTypesUsedAppropriately(errors), + new OneOfInputObjectRules(errors), + new DeprecatedInputObjectAndArgumentsAreValid(errors), + }; } - private void checkUnion(GraphQLUnionType type, SchemaValidationErrorCollector errors) { - List memberTypes = type.getTypes(); - if (memberTypes.isEmpty()) { - addError(errors, SchemaValidationErrorType.UnionTypeLackOfTypeError, format("Union type \"%s\" must include one or more unique member types.", type.getName())); - } - Set typeNames = new LinkedHashSet<>(); - for (GraphQLNamedOutputType memberType : memberTypes) { - if (!(memberType instanceof GraphQLObjectType)) { - addError(errors, SchemaValidationErrorType.InvalidUnionMemberTypeError, - format("The member types of a Union type must all be Object base types. member type \"%s\" in Union \"%s\" is invalid.", memberType.getName(), type.getName())); - } - if (!typeNames.add(memberType.getName())) { - addError(errors, SchemaValidationErrorType.RepetitiveElementError, - format("The member types of a Union type must be unique. member type \"%s\" in Union \"%s\" is not unique.", memberType.getName(), type.getName())); - } + private void validateType(GraphQLNamedType type, SchemaValidationRule[] rules) { + if (type instanceof GraphQLObjectType) { + validateObjectType((GraphQLObjectType) type, rules); + } else if (type instanceof GraphQLInterfaceType) { + validateInterfaceType((GraphQLInterfaceType) type, rules); + } else if (type instanceof GraphQLInputObjectType) { + validateInputObjectType((GraphQLInputObjectType) type, rules); + } else if (type instanceof GraphQLEnumType) { + validateEnumType((GraphQLEnumType) type, rules); + } else if (type instanceof GraphQLUnionType) { + validateUnionType((GraphQLUnionType) type, rules); + } else if (type instanceof GraphQLScalarType) { + checkDirectiveContainer((GraphQLScalarType) type, rules); } } - private void checkEnum(GraphQLEnumType type, List values, SchemaValidationErrorCollector errors) { - if (values.isEmpty()) { - addError(errors, SchemaValidationErrorType.EnumLackOfValueError, format("Enum type \"%s\" must define one or more enum values.", type.getName())); - return; - } - for (GraphQLEnumValueDefinition value : values) { - if (isReservedName(value.getName())) { - addError(errors, SchemaValidationErrorType.InvalidCustomizedNameError, - format("EnumValueDefinition \"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", value.getName(), type.getName())); - } + private void validateObjectType(GraphQLObjectType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkObjectType(type); } + checkDirectiveContainer(type, rules); + validateFieldDefinitions(type, rules); } - private void checkFieldName(String typeName, String fieldName, SchemaValidationErrorCollector errors) { - if (isReservedName(fieldName) && !INTROSPECTION_SYSTEM_FIELDS.contains(fieldName)) { - addError(errors, SchemaValidationErrorType.InvalidCustomizedNameError, - format("\"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", fieldName, typeName)); + private void validateInterfaceType(GraphQLInterfaceType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkInterfaceType(type); } + checkDirectiveContainer(type, rules); + validateFieldDefinitions(type, rules); } - private void checkArgumentName(String typeName, String fieldName, String argumentName, SchemaValidationErrorCollector errors) { - if (isReservedName(argumentName)) { - addError(errors, SchemaValidationErrorType.InvalidCustomizedNameError, - format("Argument name \"%s\" in \"%s-%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", argumentName, typeName, fieldName)); + private void validateUnionType(GraphQLUnionType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkUnionType(type); } + checkDirectiveContainer(type, rules); } - private boolean isReservedName(String name) { - return name.startsWith("__"); - } - - private void checkDefaultValue(InputValueWithState defaultValue, GraphQLInputType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - if (isValidValue(defaultValue, type, schema, context, errors)) { - return; + private void validateEnumType(GraphQLEnumType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkEnumType(type); } - addError(errors, SchemaValidationErrorType.InvalidDefaultValue, - format("Invalid default value %s for type %s", defaultValue.getValue(), simplePrint(type))); - } - - private void checkAppliedDirectiveArgument(String directiveName, String argumentName, InputValueWithState argumentValue, GraphQLInputType argumentType, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - boolean invalid = !isValidValue(argumentValue, argumentType, schema, context, errors) - || (argumentValue.isNotSet() && isNonNull(argumentType)); - if (invalid) { - addError(errors, SchemaValidationErrorType.InvalidAppliedDirectiveArgument, - format("Invalid argument '%s' for applied directive of name '%s'", argumentName, directiveName)); + checkDirectiveContainer(type, rules); + for (GraphQLEnumValueDefinition value : type.getValues()) { + checkDirectiveContainer(value, rules); } } - private boolean isValidValue(InputValueWithState value, GraphQLInputType type, GraphQLSchema schema, GraphQLContext context, SchemaValidationErrorCollector errors) { - if (value.isLiteral()) { - return validationUtil.isValidLiteralValue((Value) value.getValue(), type, schema, context, Locale.getDefault()); + private void validateInputObjectType(GraphQLInputObjectType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkInputObjectType(type); } - // coercing external values expands input field defaults, which never terminates once defaults form a cycle - if (!value.isExternal() || errors.containsValidationError(SchemaValidationErrorType.DefaultValueCircularRef)) { - return true; + checkDirectiveContainer(type, rules); + for (GraphQLInputObjectField field : type.getFieldDefinitions()) { + validateInputObjectField(type, field, rules); } - return isValidExternalValue(value.getValue(), type, schema, context); } - private boolean isValidExternalValue(@Nullable Object externalValue, GraphQLInputType type, GraphQLSchema schema, GraphQLContext context) { - try { - ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type, context, Locale.getDefault()); - return true; - } catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) { - return false; + private void validateFieldDefinitions(GraphQLFieldsContainer container, SchemaValidationRule[] rules) { + for (GraphQLFieldDefinition fieldDefinition : container.getFieldDefinitions()) { + validateFieldDefinition(container, fieldDefinition, rules); } } - private void checkAppliedDirectives(GraphQLDirectiveContainer container, GraphQLSchema schema, SchemaValidationErrorCollector errors) { - Map> directivesByName = container.getAllDirectivesByName(); - if (directivesByName.isEmpty()) { - return; - } - for (Map.Entry> entry : directivesByName.entrySet()) { - GraphQLDirective directiveDef = schema.getDirective(entry.getKey()); - if (directiveDef == null) { - addError(errors, SchemaValidationErrorType.InvalidAppliedDirective, format("A definition for directive '%s' could not be found", entry.getKey())); - } else if (directiveDef.isNonRepeatable() && entry.getValue().size() > 1) { - addError(errors, SchemaValidationErrorType.InvalidAppliedDirective, - format("The directive '%s' on the '%s' called '%s' is a non repeatable directive but has been applied %d times", - directiveDef.getName(), container.getClass().getSimpleName(), container.getName(), entry.getValue().size())); - } + private void validateFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkFieldDefinition(container, fieldDefinition); } - } - - private void checkFieldTypesUsedAppropriately(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition, SchemaValidationErrorCollector errors) { + checkDirectiveContainer(fieldDefinition, rules); for (GraphQLArgument argument : fieldDefinition.getArguments()) { - if (hasMisusedType(argument.getType(), true)) { - String path = container.getName() + "." + fieldDefinition.getName() + "." + argument.getName(); - addTypeContextErrors(argument.getType(), true, path, errors); - } - } - if (hasMisusedType(fieldDefinition.getType(), false)) { - String path = container.getName() + "." + fieldDefinition.getName(); - addTypeContextErrors(fieldDefinition.getType(), false, path, errors); - } - } - - private void checkInputFieldTypeUsedAppropriately(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errors) { - if (hasMisusedType(inputObjectField.getType(), true)) { - String path = type.getName() + "." + inputObjectField.getName(); - addTypeContextErrors(inputObjectField.getType(), true, path, errors); - } - } - - private boolean hasMisusedType(GraphQLType type, boolean inputContext) { - GraphQLType current = type; - while (true) { - if (isMisused(current, inputContext)) { - return true; - } - if (!(current instanceof GraphQLModifiedType)) { - return false; - } - current = ((GraphQLModifiedType) current).getWrappedType(); + validateArgument(fieldDefinition, argument, rules); } } - private void addTypeContextErrors(GraphQLType type, boolean inputContext, String path, SchemaValidationErrorCollector errors) { - GraphQLType current = type; - while (true) { - if (isMisused(current, inputContext)) { - addTypeContextError(current, inputContext, path, errors); - } - if (!(current instanceof GraphQLModifiedType)) { - return; - } - current = ((GraphQLModifiedType) current).getWrappedType(); + private void validateInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField field, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkInputObjectField(type, field); } + checkDirectiveContainer(field, rules); } - private void addTypeContextError(GraphQLType misusedType, boolean inputContext, String path, SchemaValidationErrorCollector errors) { - if (inputContext) { - addError(errors, SchemaValidationErrorType.OutputTypeUsedInInputTypeContext, - format("The output type '%s' has been used in an input type context : '%s'", simplePrint(misusedType), path)); - } else { - addError(errors, SchemaValidationErrorType.InputTypeUsedInOutputTypeContext, - format("The input type '%s' has been used in a output type context : '%s'", simplePrint(misusedType), path)); + private void validateArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkArgument(fieldOrDirective, argument); } + checkDirectiveContainer(argument, rules); } - private boolean isMisused(GraphQLType type, boolean inputContext) { - return inputContext ? !(type instanceof GraphQLInputType) : !(type instanceof GraphQLOutputType); - } - - private void checkOneOfInhabited(GraphQLInputObjectType inputObjectType, SchemaValidationErrorCollector errors) { - if (!inputObjectType.isOneOf()) { - return; - } - if (!canBeProvidedAFiniteValue(inputObjectType, newIdentitySet())) { - addError(errors, SchemaValidationErrorType.OneOfNotInhabited, - format("OneOf Input Object %s must be inhabited but all fields recursively reference only other OneOf Input Objects forming an unresolvable cycle.", inputObjectType.getName())); - } - } - - private boolean canBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { - if (!visited.add(oneOfInputObject)) { - return false; - } - boolean result = anyFieldCanBeProvidedAFiniteValue(oneOfInputObject, visited); - visited.remove(oneOfInputObject); - return result; - } - - private boolean anyFieldCanBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { - for (GraphQLInputObjectField field : oneOfInputObject.getFieldDefinitions()) { - GraphQLType fieldType = field.getType(); - if (isList(fieldType)) { - return true; - } - GraphQLType namedFieldType = unwrapAll(fieldType); - if (!(namedFieldType instanceof GraphQLInputObjectType)) { - return true; - } - GraphQLInputObjectType inputFieldType = (GraphQLInputObjectType) namedFieldType; - if (!inputFieldType.isOneOf() || canBeProvidedAFiniteValue(inputFieldType, visited)) { - return true; - } - } - return false; - } - - private void checkOneOfField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errors) { - if (!inputObjectType.isOneOf()) { - return; - } - if (inputObjectField.hasSetDefaultValue()) { - addError(errors, SchemaValidationErrorType.OneOfDefaultValueOnField, - format("OneOf input field %s.%s cannot have a default value.", inputObjectType.getName(), inputObjectField.getName())); - } - if (isNonNull(inputObjectField.getType())) { - addError(errors, SchemaValidationErrorType.OneOfNonNullableField, - format("OneOf input field %s.%s must be nullable.", inputObjectType.getName(), inputObjectField.getName())); - } - } - - private void checkDeprecatedInputField(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField, SchemaValidationErrorCollector errors) { - if (!isNonNull(inputObjectField.getType()) || inputObjectField.hasSetDefaultValue()) { - return; - } - if (inputObjectField.getAppliedDirective(DEPRECATED_DIRECTIVE_NAME) == null) { - return; + private void validateDirectiveDefinition(GraphQLDirective directive, SchemaValidationRule[] rules) { + checkDirectiveContainer(directive, rules); + for (GraphQLArgument argument : directive.getArguments()) { + validateArgument(directive, argument, rules); } - addError(errors, SchemaValidationErrorType.RequiredInputFieldCannotBeDeprecated, - format("Required input field '%s.%s' cannot be deprecated.", type.getName(), inputObjectField.getName())); } - private void checkDeprecatedArgument(GraphQLArgument argument, GraphQLSchemaElement fieldOrDirective, SchemaValidationErrorCollector errors) { - if (!argument.isDeprecated() || !isNonNull(argument.getType()) || argument.hasSetDefaultValue()) { - return; - } - if (fieldOrDirective instanceof GraphQLFieldDefinition) { - addError(errors, SchemaValidationErrorType.RequiredFieldArgumentCannotBeDeprecated, - format("Required argument '%s' on field '%s' cannot be deprecated.", argument.getName(), ((GraphQLFieldDefinition) fieldOrDirective).getName())); - } else if (fieldOrDirective instanceof GraphQLDirective) { - addError(errors, SchemaValidationErrorType.RequiredDirectiveArgumentCannotBeDeprecated, - format("Required argument '%s' on directive '%s' cannot be deprecated.", argument.getName(), ((GraphQLDirective) fieldOrDirective).getName())); + private void checkDirectiveContainer(GraphQLDirectiveContainer container, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkDirectiveContainer(container); } } } diff --git a/src/main/java/graphql/schema/validation/TypeAndFieldRule.java b/src/main/java/graphql/schema/validation/TypeAndFieldRule.java new file mode 100644 index 0000000000..504385f987 --- /dev/null +++ b/src/main/java/graphql/schema/validation/TypeAndFieldRule.java @@ -0,0 +1,155 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLEnumType; +import graphql.schema.GraphQLEnumValueDefinition; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInterfaceType; +import graphql.schema.GraphQLNamedOutputType; +import graphql.schema.GraphQLObjectType; +import graphql.schema.GraphQLUnionType; +import org.jspecify.annotations.NullMarked; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import static graphql.introspection.Introspection.INTROSPECTION_SYSTEM_FIELDS; +import static graphql.introspection.Introspection.isIntrospectionTypes; +import static java.lang.String.format; + +/** + * The validation about GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType and GraphQLInputObjectType: + *

    + *
  • Types must define one or more fields;
  • + *
  • Enum type must define one or more enum values;
  • + *
  • Union type must include one or more unique member types;
  • + *
  • The member types of a Union type must all be Object base types;
  • + *
  • Names must not begin with "__" (two underscores).
  • + *
+ *

+ * details in https://spec.graphql.org/June2018/#sec-Type-System + */ +@Internal +@NullMarked +public class TypeAndFieldRule implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + + public TypeAndFieldRule(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkObjectType(GraphQLObjectType objectType) { + if (!isIntrospectionTypes(objectType)) { + checkFieldsContainer(objectType, objectType.getFieldDefinitions()); + } + } + + @Override + public void checkInterfaceType(GraphQLInterfaceType interfaceType) { + checkFieldsContainer(interfaceType, interfaceType.getFieldDefinitions()); + } + + @Override + public void checkUnionType(GraphQLUnionType unionType) { + if (!isIntrospectionTypes(unionType)) { + checkUnion(unionType); + } + } + + @Override + public void checkEnumType(GraphQLEnumType enumType) { + if (!isIntrospectionTypes(enumType)) { + checkEnum(enumType, enumType.getValues()); + } + } + + @Override + public void checkInputObjectType(GraphQLInputObjectType inputObjectType) { + if (!isIntrospectionTypes(inputObjectType)) { + checkInputObject(inputObjectType, inputObjectType.getFieldDefinitions()); + } + } + + private void checkFieldsContainer(GraphQLFieldsContainer type, List fieldDefinitions) { + if (fieldDefinitions.isEmpty()) { + addError(SchemaValidationErrorType.ImplementingTypeLackOfFieldError, format("\"%s\" must define one or more fields.", type.getName())); + return; + } + for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) { + checkFieldName(type.getName(), fieldDefinition.getName()); + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + checkArgumentName(type.getName(), fieldDefinition.getName(), argument.getName()); + } + } + } + + private void checkInputObject(GraphQLInputObjectType type, List fields) { + if (fields.isEmpty()) { + addError(SchemaValidationErrorType.InputObjectTypeLackOfFieldError, format("\"%s\" must define one or more fields.", type.getName())); + return; + } + for (GraphQLInputObjectField field : fields) { + checkFieldName(type.getName(), field.getName()); + } + } + + private void checkUnion(GraphQLUnionType type) { + List memberTypes = type.getTypes(); + if (memberTypes.isEmpty()) { + addError(SchemaValidationErrorType.UnionTypeLackOfTypeError, format("Union type \"%s\" must include one or more unique member types.", type.getName())); + } + Set typeNames = new LinkedHashSet<>(); + for (GraphQLNamedOutputType memberType : memberTypes) { + if (!(memberType instanceof GraphQLObjectType)) { + addError(SchemaValidationErrorType.InvalidUnionMemberTypeError, + format("The member types of a Union type must all be Object base types. member type \"%s\" in Union \"%s\" is invalid.", memberType.getName(), type.getName())); + } + if (!typeNames.add(memberType.getName())) { + addError(SchemaValidationErrorType.RepetitiveElementError, + format("The member types of a Union type must be unique. member type \"%s\" in Union \"%s\" is not unique.", memberType.getName(), type.getName())); + } + } + } + + private void checkEnum(GraphQLEnumType type, List values) { + if (values.isEmpty()) { + addError(SchemaValidationErrorType.EnumLackOfValueError, format("Enum type \"%s\" must define one or more enum values.", type.getName())); + return; + } + for (GraphQLEnumValueDefinition value : values) { + if (isReservedName(value.getName())) { + addError(SchemaValidationErrorType.InvalidCustomizedNameError, + format("EnumValueDefinition \"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", value.getName(), type.getName())); + } + } + } + + private void checkFieldName(String typeName, String fieldName) { + if (isReservedName(fieldName) && !INTROSPECTION_SYSTEM_FIELDS.contains(fieldName)) { + addError(SchemaValidationErrorType.InvalidCustomizedNameError, + format("\"%s\" in \"%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", fieldName, typeName)); + } + } + + private void checkArgumentName(String typeName, String fieldName, String argumentName) { + if (isReservedName(argumentName)) { + addError(SchemaValidationErrorType.InvalidCustomizedNameError, + format("Argument name \"%s\" in \"%s-%s\" must not begin with \"__\", which is reserved by GraphQL introspection.", argumentName, typeName, fieldName)); + } + } + + private boolean isReservedName(String name) { + return name.startsWith("__"); + } + + private void addError(SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); + } +} diff --git a/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java b/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java new file mode 100644 index 0000000000..9fba3e2fad --- /dev/null +++ b/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java @@ -0,0 +1,175 @@ +package graphql.schema.validation; + +import graphql.Internal; +import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLImplementingType; +import graphql.schema.GraphQLInterfaceType; +import graphql.schema.GraphQLNamedOutputType; +import graphql.schema.GraphQLNamedType; +import graphql.schema.GraphQLNonNull; +import graphql.schema.GraphQLObjectType; +import graphql.schema.GraphQLOutputType; +import graphql.schema.GraphQLType; +import graphql.schema.GraphQLUnionType; +import org.jspecify.annotations.NullMarked; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import static graphql.schema.GraphQLTypeUtil.isList; +import static graphql.schema.GraphQLTypeUtil.isNonNull; +import static graphql.schema.GraphQLTypeUtil.simplePrint; +import static graphql.schema.GraphQLTypeUtil.unwrapOne; +import static java.lang.String.format; + +/** + * Schema validation rule ensuring object and interface types have all the fields that they need to + * implement the interfaces they say they implement. + */ +@Internal +@NullMarked +public class TypesImplementInterfaces implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + + public TypesImplementInterfaces(SchemaValidationErrorCollector errors) { + this.errors = errors; + } + + @Override + public void checkObjectType(GraphQLObjectType objectType) { + checkImplementsInterfaces(objectType); + } + + @Override + public void checkInterfaceType(GraphQLInterfaceType interfaceType) { + checkImplementsInterfaces(interfaceType); + } + + private void checkImplementsInterfaces(GraphQLImplementingType implementingType) { + List interfaces = implementingType.getInterfaces(); + for (GraphQLNamedOutputType interfaceType : interfaces) { + checkObjectImplementsInterface(implementingType, (GraphQLInterfaceType) interfaceType); + } + } + + private void checkObjectImplementsInterface(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType) { + for (GraphQLFieldDefinition interfaceFieldDef : interfaceType.getFieldDefinitions()) { + GraphQLFieldDefinition objectFieldDef = implementingType.getFieldDefinition(interfaceFieldDef.getName()); + if (objectFieldDef == null) { + addInterfaceError(format("%s type '%s' does not implement interface '%s' because field '%s' is missing", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName())); + } else { + checkFieldTypeCompatibility(implementingType, interfaceType, interfaceFieldDef, objectFieldDef); + } + } + checkTransitiveImplementations(implementingType, interfaceType); + } + + private void checkTransitiveImplementations(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType) { + List implementedInterfaces = implementingType.getInterfaces(); + for (GraphQLNamedOutputType transitiveInterface : interfaceType.getInterfaces()) { + if (transitiveInterface.equals(implementingType)) { + addInterfaceError(format("%s type '%s' cannot implement '%s' because that would result on a circular reference", + typeOf(implementingType), implementingType.getName(), interfaceType.getName())); + } else if (!implementedInterfaces.contains(transitiveInterface)) { + addInterfaceError(format("%s type '%s' must implement '%s' because it is implemented by '%s'", + typeOf(implementingType), implementingType.getName(), transitiveInterface.getName(), interfaceType.getName())); + } + } + } + + private void checkFieldTypeCompatibility(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef) { + if (isCompatible(interfaceFieldDef.getType(), objectFieldDef.getType())) { + checkFieldArgumentEquivalence(implementingType, interfaceType, interfaceFieldDef, objectFieldDef); + return; + } + addInterfaceError(format("%s type '%s' does not implement interface '%s' because field '%s' is defined as '%s' type and not as '%s' type", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), + simplePrint(objectFieldDef.getType()), simplePrint(interfaceFieldDef.getType()))); + } + + private void checkFieldArgumentEquivalence(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef) { + List interfaceArgs = interfaceFieldDef.getArguments(); + for (GraphQLArgument interfaceArg : interfaceArgs) { + if (objectFieldDef.getArgument(interfaceArg.getName()) == null) { + addInterfaceError(format("%s type '%s' does not implement interface '%s' because field '%s' is missing argument(s): '%s'", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), + missingArgumentNames(interfaceArgs, objectFieldDef))); + return; + } + } + for (GraphQLArgument objectArg : objectFieldDef.getArguments()) { + GraphQLArgument interfaceArg = interfaceFieldDef.getArgument(objectArg.getName()); + if (interfaceArg == null) { + checkAdditionalArgumentIsOptional(implementingType, interfaceType, objectFieldDef, objectArg); + } else if (!isSameType(objectArg.getType(), interfaceArg.getType())) { + addInterfaceError(format("%s type '%s' does not implement interface '%s' because field '%s' argument '%s' is defined differently", + typeOf(implementingType), implementingType.getName(), interfaceType.getName(), interfaceFieldDef.getName(), objectArg.getName())); + } + } + } + + private void checkAdditionalArgumentIsOptional(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, GraphQLFieldDefinition objectFieldDef, GraphQLArgument objectArg) { + if (objectArg.getType() instanceof GraphQLNonNull) { + addInterfaceError(format("%s type '%s' field '%s' defines an additional non-optional argument '%s' which is not allowed because field is also defined in interface '%s'", + typeOf(implementingType), implementingType.getName(), objectFieldDef.getName(), objectArg.getName(), interfaceType.getName())); + } + } + + private String missingArgumentNames(List interfaceArgs, GraphQLFieldDefinition objectFieldDef) { + Set missing = new LinkedHashSet<>(); + for (GraphQLArgument interfaceArg : interfaceArgs) { + if (objectFieldDef.getArgument(interfaceArg.getName()) == null) { + missing.add(interfaceArg.getName()); + } + } + return String.join(", ", missing); + } + + private void addInterfaceError(String message) { + errors.addError(new SchemaValidationError(SchemaValidationErrorType.ObjectDoesNotImplementItsInterfaces, message)); + } + + private String typeOf(GraphQLImplementingType implementingType) { + return implementingType instanceof GraphQLObjectType ? "object" : "interface"; + } + + private boolean isCompatible(GraphQLOutputType constraintType, GraphQLOutputType objectType) { + if (isSameType(constraintType, objectType)) { + return true; + } else if (constraintType instanceof GraphQLUnionType) { + return ((GraphQLUnionType) constraintType).getTypes().contains(objectType); + } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLObjectType) { + return ((GraphQLObjectType) objectType).getInterfaces().contains(constraintType); + } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLInterfaceType) { + return ((GraphQLInterfaceType) objectType).getInterfaces().contains(constraintType); + } else if (isList(constraintType) && isList(objectType)) { + return isCompatible((GraphQLOutputType) unwrapOne(constraintType), (GraphQLOutputType) unwrapOne(objectType)); + } else if (isNonNull(objectType)) { + GraphQLOutputType nullableConstraint = isNonNull(constraintType) ? (GraphQLOutputType) unwrapOne(constraintType) : constraintType; + return isCompatible(nullableConstraint, (GraphQLOutputType) unwrapOne(objectType)); + } + return false; + } + + // equivalent to comparing GraphQLTypeUtil.simplePrint() of both types + private boolean isSameType(GraphQLType first, GraphQLType second) { + GraphQLType left = first; + GraphQLType right = second; + while (true) { + boolean leftNonNull = isNonNull(left); + boolean leftList = isList(left); + if (leftNonNull != isNonNull(right) || leftList != isList(right)) { + return false; + } + if (!leftNonNull && !leftList) { + return ((GraphQLNamedType) left).getName().equals(((GraphQLNamedType) right).getName()); + } + left = unwrapOne(left); + right = unwrapOne(right); + } + } +} diff --git a/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy b/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy index 00000bfe96..c7f7d20dcf 100644 --- a/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy +++ b/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy @@ -3,9 +3,11 @@ package graphql.schema.validation import graphql.Directives import graphql.TestUtil import graphql.collect.ImmutableKit +import graphql.execution.InputValueLimits import graphql.schema.GraphQLCodeRegistry import graphql.schema.GraphQLInputObjectField import graphql.schema.GraphQLSchema +import graphql.schema.GraphQLTypeReference import graphql.schema.idl.FastSchemaGenerator import graphql.schema.idl.RuntimeWiring import graphql.schema.idl.SchemaGenerator @@ -138,6 +140,39 @@ class SchemaValidatorTest extends Specification { } == ['"__bad" in "Query" must not begin with "__", which is reserved by GraphQL introspection.'] as Set } + def "default values nested beyond the input depth limit stop validation early"() { + given: + Map tooDeep = [:] + (InputValueLimits.DEFAULT_MAX_DEPTH + 1).times { tooDeep = [next: tooDeep] } + def recursive = newInputObject().name("Recursive") + .field(newInputObjectField().name("next").type(GraphQLTypeReference.typeRef("Recursive"))) + .build() + def query = newObject().name("Query") + .field(newFieldDefinition().name("echo").type(GraphQLString) + .argument(newArgument().name("arg").type(recursive).defaultValueProgrammatic(tooDeep))) + .field(newFieldDefinition().name("__bad").type(GraphQLString)) + .build() + + when: + def errors = errors { newSchema().query(query).build() } + + then: + errors.size() == 1 + errors.every { it.contains("exceeds the maximum depth of " + InputValueLimits.DEFAULT_MAX_DEPTH) } + } + + def "named types other than the schema type kinds are skipped"() { + given: + def query = newObject().name("Query").field(newFieldDefinition().name("hello").type(GraphQLString)).build() + def schema = new GraphQLSchema.FastBuilder(GraphQLCodeRegistry.newCodeRegistry(), query, null, null) + .addType(GraphQLTypeReference.typeRef("Dangling")) + .build() + + expect: + schema.getType("Dangling") instanceof GraphQLTypeReference + new SchemaValidator().validateSchema(schema).isEmpty() + } + def "applied directives without a definition are rejected"() { given: def query = newObject() diff --git a/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy b/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy index 2b13f33cd1..90fab3e55f 100644 --- a/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy +++ b/src/test/groovy/graphql/schema/validation/TypesImplementInterfacesTest.groovy @@ -190,6 +190,31 @@ class TypesImplementInterfacesTest extends Specification { newObject().name("Actor").field(newFieldDefinition().name("name").type(GraphQLString)).withInterface(person).build() } + def "list and non-list types are not interchangeable: #scenario"() { + given: + def interfaceType = newInterface() + .name("Interface") + .field(newFieldDefinition().name("field").type(interfaceFieldType)) + .field(newFieldDefinition().name("withArg").type(GraphQLString) + .argument(newArgument().name("arg").type(interfaceArgType))) + .build() + def objType = newObject() + .name("Object") + .withInterface(interfaceType) + .field(newFieldDefinition().name("field").type(objectFieldType)) + .field(newFieldDefinition().name("withArg").type(GraphQLString) + .argument(newArgument().name("arg").type(objectArgType))) + .build() + + expect: + errorsFor(objType) == expected as Set + + where: + scenario | interfaceFieldType | objectFieldType | interfaceArgType | objectArgType || expected + "field list vs scalar" | list(GraphQLString) | GraphQLString | GraphQLString | GraphQLString || ["object type 'Object' does not implement interface 'Interface' because field 'field' is defined as 'String' type and not as '[String]' type"] + "argument list vs scalar" | GraphQLString | GraphQLString | list(GraphQLString) | GraphQLString || ["object type 'Object' does not implement interface 'Interface' because field 'withArg' argument 'arg' is defined differently"] + } + def "field is a non null object"() { given: def memberInterface = newInterface()