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 index 1eec8bff75..8d76e0f530 100644 --- a/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java +++ b/src/main/java/graphql/schema/validation/AppliedDirectiveArgumentsAreValid.java @@ -1,100 +1,53 @@ 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.GraphQLDirectiveContainer; 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 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 -public class AppliedDirectiveArgumentsAreValid extends GraphQLTypeVisitorStub { +@NullMarked +public class AppliedDirectiveArgumentsAreValid implements SchemaValidationRule { - private ValidationUtil validationUtil = new ValidationUtil(); + private final InputValueValidator inputValueValidator; + private final SchemaValidationErrorCollector errors; + public AppliedDirectiveArgumentsAreValid(InputValueValidator inputValueValidator, SchemaValidationErrorCollector errors) { + this.inputValueValidator = inputValueValidator; + this.errors = errors; + } @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 - ); + public void checkDirectiveContainer(GraphQLDirectiveContainer container) { + for (GraphQLDirective directive : container.getDirectives()) { + for (GraphQLArgument argument : directive.getArguments()) { + checkArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType()); } } - 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 - ); + for (GraphQLAppliedDirective directive : container.getAppliedDirectives()) { + for (GraphQLAppliedDirectiveArgument argument : directive.getArguments()) { + checkArgument(directive.getName(), argument.getName(), argument.getArgumentValue(), argument.getType()); } } - 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; - } + private void checkArgument(String directiveName, String argumentName, InputValueWithState argumentValue, GraphQLInputType argumentType) { + boolean invalid = !inputValueValidator.isValidValue(argumentValue, argumentType) + || (argumentValue.isNotSet() && isNonNull(argumentType)); 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; + 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 index cf2b3da5d4..9b880f7ede 100644 --- a/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java +++ b/src/main/java/graphql/schema/validation/AppliedDirectivesAreValid.java @@ -4,56 +4,48 @@ 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 org.jspecify.annotations.NullMarked; import java.util.List; import java.util.Map; -import static graphql.schema.validation.SchemaValidationErrorType.InvalidAppliedDirective; 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 -public class AppliedDirectivesAreValid extends GraphQLTypeVisitorStub { +@NullMarked +public class AppliedDirectivesAreValid implements SchemaValidationRule { - @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)); - } - } - } + private final GraphQLSchema schema; + private final SchemaValidationErrorCollector errors; - return TraversalControl.CONTINUE; + public AppliedDirectivesAreValid(GraphQLSchema schema, SchemaValidationErrorCollector errors) { + this.schema = schema; + this.errors = errors; } - private void checkNonRepeatable(SchemaValidationErrorCollector collector, GraphQLDirectiveContainer directiveContainer, GraphQLDirective directiveDef, List directives) { - if (directiveDef.isNonRepeatable() && directives.size() > 1) { - addNonRepeatableError(collector, directiveContainer, directiveDef.getName(), directives.size()); + @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 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)); + 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 index 4527973461..caa14f5324 100644 --- a/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java +++ b/src/main/java/graphql/schema/validation/DefaultValuesAreValid.java @@ -1,91 +1,51 @@ 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.Internal; 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 org.jspecify.annotations.NullMarked; import static graphql.schema.GraphQLTypeUtil.simplePrint; import static java.lang.String.format; -public class DefaultValuesAreValid extends GraphQLTypeVisitorStub { - - private ValidationUtil validationUtil = new ValidationUtil(); +/** + * Schema validation rule ensuring argument and input field default values are valid for their types. + */ +@Internal +@NullMarked +public class DefaultValuesAreValid implements SchemaValidationRule { - private final GraphQLContext graphQLContext = GraphQLContext.getDefault(); + private final InputValueValidator inputValueValidator; + private final SchemaValidationErrorCollector errors; - - @Override - public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType node, TraverserContext context) { - return super.visitGraphQLInputObjectType(node, context); + public DefaultValuesAreValid(InputValueValidator inputValueValidator, SchemaValidationErrorCollector errors) { + this.inputValueValidator = inputValueValidator; + this.errors = errors; } @Override - public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField inputObjectField, TraverserContext context) { - if (!inputObjectField.hasSetDefaultValue()) { - return TraversalControl.CONTINUE; + public void checkInputObjectField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField) { + if (inputObjectField.hasSetDefaultValue()) { + checkDefaultValue(inputObjectField.getInputFieldDefaultValue(), inputObjectField.getType()); } - 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)); + public void checkArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument) { + if (argument.hasSetDefaultValue()) { + checkDefaultValue(argument.getArgumentDefaultValue(), argument.getType()); } - 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; + 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 index f7c1c1c776..33ca884c8a 100644 --- a/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java +++ b/src/main/java/graphql/schema/validation/DeprecatedInputObjectAndArgumentsAreValid.java @@ -2,62 +2,60 @@ 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 org.jspecify.annotations.NullMarked; +import static graphql.schema.GraphQLTypeUtil.isNonNull; 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. +/** + * 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 { +@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 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)); + public void checkInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField inputObjectField) { + if (!isNonNull(inputObjectField.getType()) || inputObjectField.hasSetDefaultValue()) { + return; } - return TraversalControl.CONTINUE; + if (inputObjectField.getAppliedDirective(DEPRECATED_DIRECTIVE_NAME) == null) { + return; + } + addError(SchemaValidationErrorType.RequiredInputFieldCannotBeDeprecated, + format("Required input field '%s.%s' cannot be deprecated.", type.getName(), inputObjectField.getName())); } - // 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)); - } + 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())); } - return TraversalControl.CONTINUE; } + 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 index 6ee43aef18..531a8524c5 100644 --- a/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java +++ b/src/main/java/graphql/schema/validation/InputAndOutputTypesUsedAppropriately.java @@ -3,88 +3,94 @@ 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.GraphQLSchemaElement; import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeUtil; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; +import org.jspecify.annotations.NullMarked; -import java.util.function.BiFunction; -import java.util.function.Predicate; +import static graphql.schema.GraphQLTypeUtil.simplePrint; +import static java.lang.String.format; /** - * Schema validation rule ensuring no input type forms an unbroken non-nullable recursion, - * as such a type would be impossible to satisfy + * Schema validation rule ensuring output types are only used in output positions and input types only in input positions. */ @Internal -public class InputAndOutputTypesUsedAppropriately extends GraphQLTypeVisitorStub { +@NullMarked +public class InputAndOutputTypesUsedAppropriately implements SchemaValidationRule { - @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; + private final SchemaValidationErrorCollector errors; + + public InputAndOutputTypesUsedAppropriately(SchemaValidationErrorCollector errors) { + this.errors = errors; } @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; + 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); + } } - 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))); + @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 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 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 checkTypeContext(GraphQLType type, - SchemaValidationErrorCollector validationErrorCollector, - String path, - Predicate typePredicate, - BiFunction errorMaker) { + private void addTypeContextErrors(GraphQLType type, boolean inputContext, String path) { + GraphQLType current = type; while (true) { - String typeName = getTypeName(type); - boolean isOk = typePredicate.test(type); - if (!isOk) { - validationErrorCollector.addError(errorMaker.apply(typeName, path)); + if (isMisused(current, inputContext)) { + addTypeContextError(current, inputContext, path); } - if (type instanceof GraphQLModifiedType) { - type = ((GraphQLModifiedType) type).getWrappedType(); - } else { + 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 String getTypeName(GraphQLType type) { - return GraphQLTypeUtil.simplePrint(type); + 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 index d33d4526a1..1079a58c53 100644 --- a/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java +++ b/src/main/java/graphql/schema/validation/NoDefaultValueCircularRefs.java @@ -7,12 +7,10 @@ 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 org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -40,200 +38,138 @@ * @see Input Objects Type Validation */ @Internal -public class NoDefaultValueCircularRefs extends GraphQLTypeVisitorStub { +@NullMarked +public class NoDefaultValueCircularRefs implements SchemaValidationRule { - // 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 SchemaValidationErrorCollector errors; + + // coordinates already explored, so each cycle is reported only once 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. + // the spec's "visitedFields" set, mutated and backtracked instead of copied at each step 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); + public NoDefaultValueCircularRefs(SchemaValidationErrorCollector errors) { + this.errors = errors; + } - return TraversalControl.CONTINUE; + @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()); + } + } } - /** - * 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..." + private void literalDefaultValueHasCycle(GraphQLInputObjectType inputObject, @Nullable Value defaultValue) { if (defaultValue instanceof ArrayValue) { for (Value itemValue : ((ArrayValue) defaultValue).getValues()) { - inputObjectDefaultValueHasCycle(inputObject, itemValue, errorCollector); + literalDefaultValueHasCycle(inputObject, itemValue); } 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()) { + for (ObjectField field : ((ObjectValue) defaultValue).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)) { + boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); + if (fieldInputObject == null) { 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); + literalDefaultValueHasCycle(fieldInputObject, defaultValueMap.get(field.getName())); } else { - // "Otherwise: let fieldDefaultValue be the default value of field..." - inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName(), errorCollector); + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName()); } } } - /** - * 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..." + private void externalDefaultValueHasCycle(GraphQLInputObjectType inputObject, Object defaultValue) { if (defaultValue instanceof Iterable) { - for (Object itemValue : (Iterable) defaultValue) { - if (itemValue != null) { - inputObjectDefaultValueHasCycle(inputObject, itemValue, errorCollector); - } - } + externalListDefaultValueHasCycle(inputObject, (Iterable) defaultValue); 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(...)" + Map defaultValueMap = (Map) defaultValue; for (GraphQLInputObjectField field : inputObject.getFieldDefinitions()) { - String fieldName = field.getName(); - boolean hasDefaultValue = defaultValueMap.containsKey(fieldName); - if (!hasDefaultValue && field.getInputFieldDefaultValue().isNotSet()) { + boolean hasDefaultValue = defaultValueMap.containsKey(field.getName()); + GraphQLInputObjectType fieldInputObject = inputObjectTypeWithDefault(field, hasDefaultValue); + if (fieldInputObject == null) { continue; } - - GraphQLType namedFieldType = unwrapAll(field.getType()); - if (!(namedFieldType instanceof GraphQLInputObjectType)) { + if (!hasDefaultValue) { + inputFieldDefaultValueHasCycle(field, fieldInputObject, inputObject.getName()); continue; } + Object fieldDefaultValue = defaultValueMap.get(field.getName()); + if (fieldDefaultValue != null) { + externalDefaultValueHasCycle(fieldInputObject, fieldDefaultValue); + } + } + } - 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); + private void externalListDefaultValueHasCycle(GraphQLInputObjectType inputObject, Iterable defaultValues) { + for (Object itemValue : defaultValues) { + if (itemValue != null) { + externalDefaultValueHasCycle(inputObject, itemValue); } } } - /** - * 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; + 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 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)); + errors.addError(new SchemaValidationError(SchemaValidationErrorType.DefaultValueCircularRef, cycleMessage(coordinate))); return; } - - if (fullyExplored.contains(coordinate)) { + if (!fullyExplored.add(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); + literalDefaultValueHasCycle(namedFieldType, (Value) fieldDefaultValue.getValue()); } else if (fieldDefaultValue.isExternal() && fieldDefaultValue.getValue() != null) { - inputObjectDefaultValueHasCycle(namedFieldType, fieldDefaultValue.getValue(), errorCollector); + 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 index 9eb061d070..6382f4594f 100644 --- a/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java +++ b/src/main/java/graphql/schema/validation/NoUnbrokenInputCycles.java @@ -3,23 +3,22 @@ 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.GraphQLSchemaElement; import graphql.schema.GraphQLType; -import graphql.schema.GraphQLTypeVisitorStub; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; import java.util.ArrayList; -import java.util.LinkedHashSet; +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.isNonNull; import static graphql.schema.GraphQLTypeUtil.unwrapAll; /** @@ -27,58 +26,54 @@ * as such a type would be impossible to satisfy */ @Internal -public class NoUnbrokenInputCycles extends GraphQLTypeVisitorStub { +@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 TraversalControl visitGraphQLFieldDefinition(GraphQLFieldDefinition fieldDef, TraverserContext context) { - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - for (GraphQLArgument argument : fieldDef.getArguments()) { + public void checkFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition) { + for (GraphQLArgument argument : fieldDefinition.getArguments()) { GraphQLInputType argumentType = argument.getType(); - if (argumentType instanceof GraphQLInputObjectType) { - List path = new ArrayList<>(); - check((GraphQLInputObjectType) argumentType, new LinkedHashSet<>(), path, validationErrorCollector); + if (argumentType instanceof GraphQLInputObjectType && checkedArgumentTypes.add((GraphQLInputObjectType) argumentType)) { + check((GraphQLInputObjectType) argumentType, Collections.newSetFromMap(new IdentityHashMap<>()), new ArrayList<>()); } } - 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))); + // 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; } - seen.add(type); - + int pathSizeOnEntry = path.size(); 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); - } + 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 GraphQLType unwrapNonNull(GraphQLNonNull type) { - GraphQLType wrappedType = type.getWrappedType(); - if (isList(wrappedType)) { - return wrappedType; + private @Nullable GraphQLInputObjectType nonNullInputObjectType(GraphQLInputType type) { + if (!(type instanceof GraphQLNonNull)) { + return null; } - 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)); + GraphQLType wrappedType = ((GraphQLNonNull) type).getWrappedType(); + if (isList(wrappedType)) { + return null; } - message.append("] forms an unsatisfiable cycle"); - return message.toString(); + 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 index 72e1aba67c..8f6c20a783 100644 --- a/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java +++ b/src/main/java/graphql/schema/validation/OneOfInputObjectRules.java @@ -1,65 +1,66 @@ package graphql.schema.validation; -import graphql.ExperimentalApi; +import graphql.Internal; 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.Collections; +import java.util.IdentityHashMap; import java.util.Set; -import static graphql.Assert.assertNotNull; +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 the input field must be nullable. - * The input field must not have a default value. +/** + * 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 -@ExperimentalApi -public class OneOfInputObjectRules extends GraphQLTypeVisitorStub { +public class OneOfInputObjectRules implements SchemaValidationRule { + + private final SchemaValidationErrorCollector errors; + + public OneOfInputObjectRules(SchemaValidationErrorCollector errors) { + this.errors = errors; + } @Override - public TraversalControl visitGraphQLInputObjectType(GraphQLInputObjectType inputObjectType, TraverserContext context) { + public void checkInputObjectType(GraphQLInputObjectType inputObjectType) { if (!inputObjectType.isOneOf()) { - return TraversalControl.CONTINUE; + return; } - 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)); + 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())); } - return TraversalControl.CONTINUE; } private boolean canBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObject, Set visited) { - if (visited.contains(oneOfInputObject)) { + if (!visited.add(oneOfInputObject)) { return false; } - Set nextVisited = new LinkedHashSet<>(visited); - nextVisited.add(oneOfInputObject); + 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 (GraphQLTypeUtil.isList(fieldType)) { + if (isList(fieldType)) { return true; } - GraphQLUnmodifiedType namedFieldType = GraphQLTypeUtil.unwrapAll(fieldType); + GraphQLType namedFieldType = unwrapAll(fieldType); if (!(namedFieldType instanceof GraphQLInputObjectType)) { return true; } GraphQLInputObjectType inputFieldType = (GraphQLInputObjectType) namedFieldType; - if (!inputFieldType.isOneOf()) { - return true; - } - if (canBeProvidedAFiniteValue(inputFieldType, nextVisited)) { + if (!inputFieldType.isOneOf() || canBeProvidedAFiniteValue(inputFieldType, visited)) { return true; } } @@ -67,22 +68,21 @@ private boolean canBeProvidedAFiniteValue(GraphQLInputObjectType oneOfInputObjec } @Override - public TraversalControl visitGraphQLInputObjectField(GraphQLInputObjectField inputObjectField, TraverserContext context) { - GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) assertNotNull(context.getParentNode(), "Input field validation requires its containing input object"); + public void checkInputObjectField(GraphQLInputObjectType inputObjectType, GraphQLInputObjectField inputObjectField) { if (!inputObjectType.isOneOf()) { - return TraversalControl.CONTINUE; + return; } - 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)); + addError(SchemaValidationErrorType.OneOfDefaultValueOnField, + format("OneOf input field %s.%s cannot have a default value.", inputObjectType.getName(), inputObjectField.getName())); } - - 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)); + if (isNonNull(inputObjectField.getType())) { + addError(SchemaValidationErrorType.OneOfNonNullableField, + format("OneOf input field %s.%s must be nullable.", inputObjectType.getName(), inputObjectField.getName())); } - return TraversalControl.CONTINUE; + } + + 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 815cfd4403..828abc87f8 100644 --- a/src/main/java/graphql/schema/validation/SchemaValidator.java +++ b/src/main/java/graphql/schema/validation/SchemaValidator.java @@ -2,50 +2,179 @@ import graphql.Internal; import graphql.execution.InputValueLimits; +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.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLInterfaceType; +import graphql.schema.GraphQLNamedType; +import graphql.schema.GraphQLObjectType; +import graphql.schema.GraphQLScalarType; import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLTypeVisitor; -import graphql.schema.SchemaTraverser; +import graphql.schema.GraphQLSchemaElement; +import graphql.schema.GraphQLUnionType; +import org.jspecify.annotations.NullMarked; -import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Set; +/** + * 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 { + public Set validateSchema(GraphQLSchema schema) { + SchemaValidationErrorCollector errors = new SchemaValidationErrorCollector(); + new DefaultValueDepth(InputValueLimits.getDefaultLimits().getMaxDepth()).check(schema, errors); + if (!errors.getErrors().isEmpty()) { + return errors.getErrors(); + } + List types = schema.getAllTypesAsList(); - private final List rules = new ArrayList<>(); + // runs first because value validation must not coerce default values that form a cycle + checkDefaultValueCycles(types, errors); - 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()); + SchemaValidationRule[] rules = createRules(schema, errors); + for (GraphQLNamedType type : types) { + validateType(type, rules); + } + for (GraphQLDirective directive : schema.getDirectives()) { + validateDirectiveDefinition(directive, rules); + } + return errors.getErrors(); } - public List getRules() { - return rules; + private void checkDefaultValueCycles(List types, SchemaValidationErrorCollector errors) { + NoDefaultValueCircularRefs noDefaultValueCircularRefs = new NoDefaultValueCircularRefs(errors); + for (GraphQLNamedType type : types) { + if (type instanceof GraphQLInputObjectType) { + noDefaultValueCircularRefs.checkInputObjectType((GraphQLInputObjectType) type); + } + } } - 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 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 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 validateObjectType(GraphQLObjectType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkObjectType(type); } - Map, Object> rootVars = new LinkedHashMap<>(); - rootVars.put(GraphQLSchema.class, schema); - rootVars.put(SchemaValidationErrorCollector.class, validationErrorCollector); - new SchemaTraverser().depthFirstFullSchema(rules, schema, rootVars); - return validationErrorCollector.getErrors(); + checkDirectiveContainer(type, rules); + validateFieldDefinitions(type, rules); } + private void validateInterfaceType(GraphQLInterfaceType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkInterfaceType(type); + } + checkDirectiveContainer(type, rules); + validateFieldDefinitions(type, rules); + } + + private void validateUnionType(GraphQLUnionType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkUnionType(type); + } + checkDirectiveContainer(type, rules); + } + + private void validateEnumType(GraphQLEnumType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkEnumType(type); + } + checkDirectiveContainer(type, rules); + for (GraphQLEnumValueDefinition value : type.getValues()) { + checkDirectiveContainer(value, rules); + } + } + + private void validateInputObjectType(GraphQLInputObjectType type, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkInputObjectType(type); + } + checkDirectiveContainer(type, rules); + for (GraphQLInputObjectField field : type.getFieldDefinitions()) { + validateInputObjectField(type, field, rules); + } + } + + private void validateFieldDefinitions(GraphQLFieldsContainer container, SchemaValidationRule[] rules) { + for (GraphQLFieldDefinition fieldDefinition : container.getFieldDefinitions()) { + validateFieldDefinition(container, fieldDefinition, rules); + } + } + + private void validateFieldDefinition(GraphQLFieldsContainer container, GraphQLFieldDefinition fieldDefinition, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkFieldDefinition(container, fieldDefinition); + } + checkDirectiveContainer(fieldDefinition, rules); + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + validateArgument(fieldDefinition, argument, rules); + } + } + + private void validateInputObjectField(GraphQLInputObjectType type, GraphQLInputObjectField field, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkInputObjectField(type, field); + } + checkDirectiveContainer(field, rules); + } + + private void validateArgument(GraphQLSchemaElement fieldOrDirective, GraphQLArgument argument, SchemaValidationRule[] rules) { + for (SchemaValidationRule rule : rules) { + rule.checkArgument(fieldOrDirective, argument); + } + checkDirectiveContainer(argument, rules); + } + + private void validateDirectiveDefinition(GraphQLDirective directive, SchemaValidationRule[] rules) { + checkDirectiveContainer(directive, rules); + for (GraphQLArgument argument : directive.getArguments()) { + validateArgument(directive, argument, rules); + } + } + + 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 index 84a768479d..504385f987 100644 --- a/src/main/java/graphql/schema/validation/TypeAndFieldRule.java +++ b/src/main/java/graphql/schema/validation/TypeAndFieldRule.java @@ -1,6 +1,6 @@ package graphql.schema.validation; -import graphql.collect.ImmutableKit; +import graphql.Internal; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLEnumType; import graphql.schema.GraphQLEnumValueDefinition; @@ -10,224 +10,146 @@ 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 org.jspecify.annotations.NullMarked; -import java.util.HashSet; +import java.util.LinkedHashSet; 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; +import static java.lang.String.format; /** - * 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).
  • - *
+ * 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 */ -public class TypeAndFieldRule extends GraphQLTypeVisitorStub { +@Internal +@NullMarked +public class TypeAndFieldRule implements SchemaValidationRule { - @Override - public TraversalControl visitGraphQLInterfaceType(GraphQLInterfaceType type, TraverserContext context) { - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateContainsField((GraphQLFieldsContainer) type, errorCollector); - return super.visitGraphQLInterfaceType(type, context); + private final SchemaValidationErrorCollector errors; + + public TypeAndFieldRule(SchemaValidationErrorCollector errors) { + this.errors = errors; } @Override - public TraversalControl visitGraphQLObjectType(GraphQLObjectType type, TraverserContext context) { - if (isIntrospectionTypes(type)) { - return TraversalControl.CONTINUE; + public void checkObjectType(GraphQLObjectType objectType) { + if (!isIntrospectionTypes(objectType)) { + checkFieldsContainer(objectType, objectType.getFieldDefinitions()); } - 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; + public void checkInterfaceType(GraphQLInterfaceType interfaceType) { + checkFieldsContainer(interfaceType, interfaceType.getFieldDefinitions()); } @Override - public TraversalControl visitGraphQLEnumType(GraphQLEnumType type, TraverserContext context) { - if (isIntrospectionTypes(type)) { - return TraversalControl.CONTINUE; + public void checkUnionType(GraphQLUnionType unionType) { + if (!isIntrospectionTypes(unionType)) { + checkUnion(unionType); } - 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; + public void checkEnumType(GraphQLEnumType enumType) { + if (!isIntrospectionTypes(enumType)) { + checkEnum(enumType, enumType.getValues()); } - SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - validateInputObject((GraphQLInputObjectType) type, errorCollector); - return TraversalControl.CONTINUE; } + @Override + public void checkInputObjectType(GraphQLInputObjectType inputObjectType) { + if (!isIntrospectionTypes(inputObjectType)) { + checkInputObject(inputObjectType, inputObjectType.getFieldDefinitions()); + } + } - 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); + 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) { - validateFieldDefinition(type.getName(), fieldDefinition, errorCollector); + checkFieldName(type.getName(), fieldDefinition.getName()); + for (GraphQLArgument argument : fieldDefinition.getArguments()) { + checkArgumentName(type.getName(), fieldDefinition.getName(), argument.getName()); + } } } - 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); + 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 inputObjectField : inputObjectFields) { - validateInputFieldDefinition(type.getName(), inputObjectField, errorCollector); + for (GraphQLInputObjectField field : fields) { + checkFieldName(type.getName(), field.getName()); } } - private void validateUnion(GraphQLUnionType type, SchemaValidationErrorCollector errorCollector) { + private void checkUnion(GraphQLUnionType type) { 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); + if (memberTypes.isEmpty()) { + addError(SchemaValidationErrorType.UnionTypeLackOfTypeError, format("Union type \"%s\" must include one or more unique member types.", type.getName())); } - - Set typeNames = new HashSet<>(); - for (GraphQLNamedOutputType memberType : type.getTypes()) { - String typeName = memberType.getName(); -// GraphQLNamedType graphQLNamedType = schemaTypeHolder.get(typeName); + Set typeNames = new LinkedHashSet<>(); + for (GraphQLNamedOutputType memberType : memberTypes) { 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); + 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.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); + 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 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 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; } - } - - 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); + 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 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 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 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 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 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 boolean isReservedName(String name) { + return name.startsWith("__"); } - - 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); - } + private void addError(SchemaValidationErrorType errorType, String message) { + errors.addError(new SchemaValidationError(errorType, message)); } -} \ 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 index ef1ef84b48..9fba3e2fad 100644 --- a/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java +++ b/src/main/java/graphql/schema/validation/TypesImplementInterfaces.java @@ -6,27 +6,22 @@ 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.GraphQLSchemaElement; -import graphql.schema.GraphQLTypeVisitorStub; +import graphql.schema.GraphQLType; import graphql.schema.GraphQLUnionType; -import graphql.util.FpKit; -import graphql.util.TraversalControl; -import graphql.util.TraverserContext; +import org.jspecify.annotations.NullMarked; -import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; +import java.util.Set; -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; /** @@ -34,178 +29,147 @@ * implement the interfaces they say they implement. */ @Internal -public class TypesImplementInterfaces extends GraphQLTypeVisitorStub { - private static final Map, String> TYPE_OF_MAP = new HashMap<>(); +@NullMarked +public class TypesImplementInterfaces implements SchemaValidationRule { - static { - TYPE_OF_MAP.put(GraphQLObjectType.class, "object"); - TYPE_OF_MAP.put(GraphQLInterfaceType.class, "interface"); + private final SchemaValidationErrorCollector errors; + + public TypesImplementInterfaces(SchemaValidationErrorCollector errors) { + this.errors = errors; } @Override - public TraversalControl visitGraphQLObjectType(GraphQLObjectType type, TraverserContext context) { - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - check((GraphQLImplementingType) type, validationErrorCollector); - return TraversalControl.CONTINUE; + public void checkObjectType(GraphQLObjectType objectType) { + checkImplementsInterfaces(objectType); } @Override - public TraversalControl visitGraphQLInterfaceType(GraphQLInterfaceType type, TraverserContext context) { - SchemaValidationErrorCollector validationErrorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); - check((GraphQLImplementingType) type, validationErrorCollector); - return TraversalControl.CONTINUE; + public void checkInterfaceType(GraphQLInterfaceType interfaceType) { + checkImplementsInterfaces(interfaceType); } - - private void check(GraphQLImplementingType implementingType, SchemaValidationErrorCollector validationErrorCollector) { + private void checkImplementsInterfaces(GraphQLImplementingType implementingType) { 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); - }); - + for (GraphQLNamedOutputType interfaceType : interfaces) { + checkObjectImplementsInterface(implementingType, (GraphQLInterfaceType) interfaceType); + } } - // 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) { + private void checkObjectImplementsInterface(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType) { + for (GraphQLFieldDefinition interfaceFieldDef : interfaceType.getFieldDefinitions()) { 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()))); + 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, validationErrorCollector, interfaceFieldDef, objectFieldDef); + checkFieldTypeCompatibility(implementingType, interfaceType, interfaceFieldDef, objectFieldDef); } } - - checkTransitiveImplementations(implementingType, interfaceType, validationErrorCollector); + checkTransitiveImplementations(implementingType, interfaceType); } - private void checkTransitiveImplementations(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, SchemaValidationErrorCollector validationErrorCollector) { + private void checkTransitiveImplementations(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType) { List implementedInterfaces = implementingType.getInterfaces(); - interfaceType.getInterfaces().forEach(transitiveInterface -> { + for (GraphQLNamedOutputType transitiveInterface : interfaceType.getInterfaces()) { 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())) - ); + 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)) { - 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()))); + 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, 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 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, SchemaValidationErrorCollector validationErrorCollector, GraphQLFieldDefinition interfaceFieldDef, GraphQLFieldDefinition objectFieldDef) { + private void checkFieldArgumentEquivalence(GraphQLImplementingType implementingType, GraphQLInterfaceType interfaceType, 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()))); - } - } - }); + 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 String makeArgStr(GraphQLArgument argument) { - return argument.getName() + - ":" + - simplePrint(argument.getType()); + 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 SchemaValidationError error(String msg) { - return new SchemaValidationError(ObjectDoesNotImplementItsInterfaces, msg); + private String typeOf(GraphQLImplementingType implementingType) { + return implementingType instanceof GraphQLObjectType ? "object" : "interface"; } - /** - * @return {@code true} if the specified implementingType satisfies the constraintType. - */ - boolean isCompatible(GraphQLOutputType constraintType, GraphQLOutputType objectType) { + private boolean isCompatible(GraphQLOutputType constraintType, GraphQLOutputType objectType) { if (isSameType(constraintType, objectType)) { return true; } else if (constraintType instanceof GraphQLUnionType) { - return objectIsMemberOfUnion((GraphQLUnionType) constraintType, objectType); + return ((GraphQLUnionType) constraintType).getTypes().contains(objectType); } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLObjectType) { - return objectImplementsInterface((GraphQLInterfaceType) constraintType, (GraphQLObjectType) objectType); + return ((GraphQLObjectType) objectType).getInterfaces().contains(constraintType); } else if (constraintType instanceof GraphQLInterfaceType && objectType instanceof GraphQLInterfaceType) { - return interfaceImplementsInterface((GraphQLInterfaceType) constraintType, (GraphQLInterfaceType) objectType); + return ((GraphQLInterfaceType) objectType).getInterfaces().contains(constraintType); } else if (isList(constraintType) && isList(objectType)) { - GraphQLOutputType wrappedConstraintType = (GraphQLOutputType) unwrapOne(constraintType); - GraphQLOutputType wrappedObjectType = (GraphQLOutputType) unwrapOne(objectType); - return isCompatible(wrappedConstraintType, wrappedObjectType); + return isCompatible((GraphQLOutputType) unwrapOne(constraintType), (GraphQLOutputType) unwrapOne(objectType)); } 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; + GraphQLOutputType nullableConstraint = isNonNull(constraintType) ? (GraphQLOutputType) unwrapOne(constraintType) : constraintType; + return isCompatible(nullableConstraint, (GraphQLOutputType) unwrapOne(objectType)); } + 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); + // 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/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..c7f7d20dcf 100644 --- a/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy +++ b/src/test/groovy/graphql/schema/validation/SchemaValidatorTest.groovy @@ -1,26 +1,254 @@ 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 +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 "check used rules"() { + 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 "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 "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() + .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..90fab3e55f 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,250 @@ 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)) - ) - - .build() - - when: - new TypesImplementInterfaces().check(objType, errorCollector) - - 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'")) - } - - def "field is object 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) + .argument(newArgument().name("arg1").type(GraphQLString))) .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) + def errors = errorsFor(objType) then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() + 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 list of objects 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(list(person)).build()) + .field(newFieldDefinition().name("field").type(interfaceFieldType)) .build() - - GraphQLObjectType goodImpl = newObject() + def goodImpl = newObject() .name("GoodImpl") - .field(newFieldDefinition().name("field").type(list(actor)).build()) + .field(newFieldDefinition().name("field").type(goodFieldType)) .withInterface(interfaceType) .build() - - GraphQLObjectType badImpl = newObject() + def badImpl = newObject() .name("BadImpl") - .field(newFieldDefinition().name("field").type(list(prop)).build()) + .field(newFieldDefinition().name("field").type(badFieldType)) .withInterface(interfaceType) .build() - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() + expect: + errorsFor(goodImpl).isEmpty() + !errorsFor(badImpl).isEmpty() - 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 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() + // 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 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() + static GraphQLObjectType actorImplementing(GraphQLInterfaceType person) { + newObject().name("Actor").field(newFieldDefinition().name("name").type(GraphQLString)).withInterface(person).build() } - def "field is non-null"() { + def "list and non-list types are not interchangeable: #scenario"() { 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) + def interfaceType = newInterface() + .name("Interface") + .field(newFieldDefinition().name("field").type(interfaceFieldType)) + .field(newFieldDefinition().name("withArg").type(GraphQLString) + .argument(newArgument().name("arg").type(interfaceArgType))) .build() - - GraphQLObjectType badImpl = newObject() - .name("BadImpl") - .field(newFieldDefinition().name("field").type(nonNull(GraphQLInt)).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() - SchemaValidationErrorCollector goodErrorCollector = new SchemaValidationErrorCollector() - SchemaValidationErrorCollector badErrorCollector = new SchemaValidationErrorCollector() - - when: - new TypesImplementInterfaces().check(goodImpl, goodErrorCollector) - new TypesImplementInterfaces().check(badImpl, badErrorCollector) + expect: + errorsFor(objType) == expected as Set - then: - goodErrorCollector.getErrors().isEmpty() - !badErrorCollector.getErrors().isEmpty() + 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: - 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() } }