From e436ca77d4c7b96051db9694c34c6544d88da035 Mon Sep 17 00:00:00 2001 From: Marc-Andre Giroux Date: Fri, 6 Nov 2026 11:12:42 -0500 Subject: [PATCH] Validate oneOf input objects once per level during variable coercion --- .../OneOfVariableCoercionBenchmark.java | 124 ++++++++++++++++ .../execution/ValuesResolverConversion.java | 35 ++++- .../ValuesResolverOneOfValidation.java | 2 +- .../execution/ValuesResolverTest.groovy | 133 ++++++++++++++++++ 4 files changed, 289 insertions(+), 5 deletions(-) create mode 100644 src/jmh/java/benchmark/OneOfVariableCoercionBenchmark.java diff --git a/src/jmh/java/benchmark/OneOfVariableCoercionBenchmark.java b/src/jmh/java/benchmark/OneOfVariableCoercionBenchmark.java new file mode 100644 index 0000000000..13e613cfc2 --- /dev/null +++ b/src/jmh/java/benchmark/OneOfVariableCoercionBenchmark.java @@ -0,0 +1,124 @@ +package benchmark; + +import graphql.GraphQLContext; +import graphql.execution.CoercedVariables; +import graphql.execution.RawVariables; +import graphql.execution.ValuesResolver; +import graphql.language.OperationDefinition; +import graphql.language.VariableDefinition; +import graphql.parser.Parser; +import graphql.schema.GraphQLSchema; +import graphql.schema.idl.SchemaGenerator; +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 java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Coerces a variable made of nested input objects, `depth` levels deep, each level having + * {@link #FIELDS_PER_LEVEL} optional scalar fields of which only a few are provided. The innermost + * level holds a `Leaf` input object which is either a plain input object or a `@oneOf` one. + */ +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 3, time = 2) +@Measurement(iterations = 5, time = 2) +@Fork(2) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +public class OneOfVariableCoercionBenchmark { + + private static final int FIELDS_PER_LEVEL = 8; + private static final int PROVIDED_FIELDS_PER_LEVEL = 3; + private static final int LIST_SIZE = 20; + + @Param({"1", "8"}) + public int depth; + + @Param({"false", "true"}) + public boolean oneOfLeaf; + + private GraphQLSchema schema; + private List variableDefinitions; + private RawVariables singleObjectVariables; + private RawVariables listOfObjectsVariables; + private final GraphQLContext graphQLContext = GraphQLContext.getDefault(); + + @Setup + public void setup() { + schema = SchemaGenerator.createdMockedSchema(sdl()); + String query = "query ($input: Level0, $inputs: [Level0!]) { single(input: $input) list(inputs: $inputs) }"; + variableDefinitions = Parser.parse(query) + .getFirstDefinitionOfType(OperationDefinition.class).orElseThrow() + .getVariableDefinitions(); + + Map input = inputValue(); + List inputs = new ArrayList<>(); + for (int i = 0; i < LIST_SIZE; i++) { + inputs.add(inputValue()); + } + singleObjectVariables = RawVariables.of(Map.of("input", input)); + listOfObjectsVariables = RawVariables.of(Map.of("inputs", inputs)); + + // make sure the variables are valid + singleObject(); + listOfObjects(); + } + + @Benchmark + public CoercedVariables singleObject() { + return ValuesResolver.coerceVariableValues(schema, variableDefinitions, singleObjectVariables, graphQLContext, Locale.ENGLISH); + } + + @Benchmark + public CoercedVariables listOfObjects() { + return ValuesResolver.coerceVariableValues(schema, variableDefinitions, listOfObjectsVariables, graphQLContext, Locale.ENGLISH); + } + + private String sdl() { + StringBuilder sdl = new StringBuilder(); + sdl.append("input Leaf ").append(oneOfLeaf ? "@oneOf " : "").append("{ a: Int, b: String }\n"); + for (int level = 0; level < depth; level++) { + sdl.append("input Level").append(level).append(" {\n"); + for (int f = 0; f < FIELDS_PER_LEVEL; f++) { + sdl.append(" f").append(f).append(": String\n"); + } + if (level == depth - 1) { + sdl.append(" leaf: Leaf\n"); + } else { + sdl.append(" next: Level").append(level + 1).append("\n"); + } + sdl.append("}\n"); + } + sdl.append("type Query { single(input: Level0): Boolean list(inputs: [Level0!]): Boolean }\n"); + return sdl.toString(); + } + + private Map inputValue() { + Map value = Map.of("a", 1); + String childFieldName = "leaf"; + for (int level = depth - 1; level >= 0; level--) { + Map levelValue = new LinkedHashMap<>(); + for (int f = 0; f < PROVIDED_FIELDS_PER_LEVEL; f++) { + levelValue.put("f" + f, "value" + f); + } + levelValue.put(childFieldName, value); + value = levelValue; + childFieldName = "next"; + } + return value; + } +} diff --git a/src/main/java/graphql/execution/ValuesResolverConversion.java b/src/main/java/graphql/execution/ValuesResolverConversion.java index ca804c1cc9..bdad7c7781 100644 --- a/src/main/java/graphql/execution/ValuesResolverConversion.java +++ b/src/main/java/graphql/execution/ValuesResolverConversion.java @@ -481,16 +481,14 @@ static Object externalValueToInternalValueImpl( if (value instanceof Map) { GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) graphQLType; //noinspection unchecked - Map coercedMap = externalValueToInternalValueForObject( + return externalValueToInternalValueForObject( + variableName, inputInterceptor, fieldVisibility, inputObjectType, (Map) value, graphqlContext, locale); - - ValuesResolverOneOfValidation.validateOneOfInputTypes(inputObjectType, coercedMap, null, variableName, locale); - return coercedMap; } else { throw CoercingParseValueException.newCoercingParseValueException() .message("Expected type 'Map' but was '" + value.getClass().getSimpleName() + @@ -506,6 +504,7 @@ static Object externalValueToInternalValueImpl( * performs validation */ private static Map externalValueToInternalValueForObject( + String variableName, InputInterceptor inputInterceptor, GraphqlFieldVisibility fieldVisibility, GraphQLInputObjectType inputObjectType, @@ -522,6 +521,10 @@ private static Map externalValueToInternalValueForObject( } Map coercedValues = new LinkedHashMap<>(); + // Fields filled from a literal or internal default. Unlike provided values and external defaults, + // these don't go through externalValueToInternalValueImpl, so nothing has oneOf-validated their + // nested input objects yet. Tracked so they can get a full recursive walk below. + List nonExternalDefaultFields = null; for (GraphQLInputObjectField inputFieldDefinition : fieldDefinitions) { GraphQLInputType fieldType = inputFieldDefinition.getType(); @@ -538,6 +541,12 @@ private static Map externalValueToInternalValueForObject( graphqlContext, locale); coercedValues.put(fieldName, coercedDefaultValue); + if (!defaultValue.isExternal()) { + if (nonExternalDefaultFields == null) { + nonExternalDefaultFields = new ArrayList<>(1); + } + nonExternalDefaultFields.add(inputFieldDefinition); + } } else if (isNonNull(fieldType) && (!hasValue || value == null)) { throw new NonNullableValueCoercedAsNullException(fieldName, emptyList(), fieldType); } else if (hasValue) { @@ -555,6 +564,24 @@ private static Map externalValueToInternalValueForObject( } } } + + // OneOf validation happens here, once per input object, as each object finishes conversion. + // + // This object: only its own oneOf rule is checked (no recursion). Every nested input object that came + // from a provided value or an external default was converted by externalValueToInternalValueImpl, + // which ends up back in this method for that object and checks it there. Re-walking the subtree from + // every ancestor would re-check the same objects at each level (O(depth x size)). + // + // Literal and internal defaults: these never reached this method for their nested objects, so they get + // the full recursive walk. It runs after this object's own check to keep the same error order. + if (inputObjectType.isOneOf()) { + ValuesResolverOneOfValidation.validateOneOfInputTypesInternal(inputObjectType, null, coercedValues, locale); + } + if (nonExternalDefaultFields != null) { + for (GraphQLInputObjectField defaultField : nonExternalDefaultFields) { + ValuesResolverOneOfValidation.validateOneOfInputTypes(defaultField.getType(), coercedValues.get(defaultField.getName()), null, variableName, locale); + } + } return coercedValues; } diff --git a/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java b/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java index 4c1daac1c8..c2d7c5cc9a 100644 --- a/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java +++ b/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java @@ -80,7 +80,7 @@ static void validateOneOfInputTypes(GraphQLType type, Object inputValue, Value argumentValue, Map objectMap, Locale locale) { + static void validateOneOfInputTypesInternal(GraphQLInputObjectType oneOfInputType, Value argumentValue, Map objectMap, Locale locale) { final String fieldName; if (argumentValue instanceof ObjectValue) { List objectFields = ((ObjectValue) argumentValue).getObjectFields(); diff --git a/src/test/groovy/graphql/execution/ValuesResolverTest.groovy b/src/test/groovy/graphql/execution/ValuesResolverTest.groovy index cc4d7e7a4b..a39902e1b9 100644 --- a/src/test/groovy/graphql/execution/ValuesResolverTest.groovy +++ b/src/test/groovy/graphql/execution/ValuesResolverTest.groovy @@ -180,6 +180,139 @@ class ValuesResolverTest extends Specification { } + def nestedOneOfSdl = ''' + input OneOf @oneOf { a: Int, b: Int, nested: OneOf } + input Level3 { leaf: OneOf, leaves: [OneOf] } + input Level2 { level3: Level3, level3s: [Level3] } + input Level1 { level2: Level2, other: Int } + type Query { f(arg: Level1, args: [Level1], oneOf: OneOf, oneOfs: [OneOf]): Boolean } + ''' + + @Unroll + def "getVariableValues: nested oneOf violations in variables are reported - #testCase"() { + given: + def schema = TestUtil.schema(nestedOneOfSdl) + VariableDefinition variableDefinition = new VariableDefinition("variable", variableType) + + when: + ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: inputValue]), graphQLContext, locale) + + then: + def e = thrown(expectedException) + e.message == expectedMessage + + where: + testCase | variableType | inputValue || expectedException | expectedMessage + "depth 3 too many keys" | new TypeName("Level1") | [level2: [level3: [leaf: [a: 1, b: 2]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "depth 3 null value" | new TypeName("Level1") | [level2: [level3: [leaf: [a: null]]]] || OneOfNullValueException | "OneOf type field 'OneOf.a' must be non-null." + "depth 3 empty" | new TypeName("Level1") | [level2: [level3: [leaf: [:]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "oneOf nested in oneOf" | new TypeName("Level1") | [level2: [level3: [leaf: [nested: [nested: [a: 1, b: 2]]]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "oneOf nested in oneOf null value" | new TypeName("OneOf") | [nested: [nested: [b: null]]] || OneOfNullValueException | "OneOf type field 'OneOf.b' must be non-null." + "list of oneOf inside non-oneOf parents" | new TypeName("Level1") | [level2: [level3: [leaves: [[a: 1], [a: 1, b: 2]]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "list of parents containing oneOf" | new TypeName("Level1") | [level2: [level3s: [[leaf: [a: 1]], [leaf: [b: null]]]]] || OneOfNullValueException | "OneOf type field 'OneOf.b' must be non-null." + "top level list of parents" | new ListType(new TypeName("Level1")) | [[level2: [level3: [leaf: [a: 1]]]], [level2: [level3: [leaf: [:]]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "single value coerced to list" | new ListType(new TypeName("OneOf")) | [a: 1, b: 2] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "single value coerced to nested list" | new TypeName("Level1") | [level2: [level3s: [leaves: [a: null]]]] || OneOfNullValueException | "OneOf type field 'OneOf.a' must be non-null." + } + + def "getVariableValues: valid nested oneOf variables are accepted"() { + given: + def schema = TestUtil.schema(nestedOneOfSdl) + VariableDefinition variableDefinition = new VariableDefinition("variable", new TypeName("Level1")) + def inputValue = [level2: [level3: [leaf: [nested: [a: 1]], leaves: [[a: 1], [b: 2]]], level3s: [[leaves: [b: 3]]]], other: 1] + + when: + def resolvedValues = ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: inputValue]), graphQLContext, locale) + + then: + resolvedValues.get('variable') == [level2: [level3: [leaf: [nested: [a: 1]], leaves: [[a: 1], [b: 2]]], level3s: [[leaves: [[b: 3]]]]], other: 1] + } + + @Unroll + def "getVariableValues: error precedence between nested oneOf violations and sibling coercion errors - #testCase"() { + given: + def sdl = ''' + input OneOf @oneOf { a: Int, b: Int } + input Parent { first: OneOf, second: Int, third: OneOf } + type Query { f(arg: Parent): Boolean } + ''' + def schema = TestUtil.schema(sdl) + VariableDefinition variableDefinition = new VariableDefinition("variable", new TypeName("Parent")) + + when: + ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: inputValue]), graphQLContext, locale) + + then: + def e = thrown(GraphQLException) + e.class == expectedException + + where: + testCase | inputValue || expectedException + "oneOf violation before bad sibling" | [first: [a: 1, b: 2], second: "notAnInt"] || OneOfTooManyKeysException + "bad sibling before oneOf violation" | [second: "notAnInt", third: [a: 1, b: 2]] || CoercingParseValueException + } + + @Unroll + def "getVariableValues: oneOf violations in nested non-external default values are reported - #testCase"() { + given: + def oneOfType = newInputObject() + .name("OneOf") + .withAppliedDirective(Directives.OneOfDirective.toAppliedDirective()) + .field(newInputObjectField().name("a").type(GraphQLInt)) + .field(newInputObjectField().name("b").type(GraphQLInt)) + .build() + def childField = newInputObjectField().name("child").type(oneOfType) + defaultSetter(childField) + def inner = newInputObject() + .name("Inner") + .field(childField) + .field(newInputObjectField().name("x").type(GraphQLInt)) + .build() + def outer = newInputObject() + .name("Outer") + .field(newInputObjectField().name("inner").type(inner)) + .build() + def schema = TestUtil.schemaWithInputType(outer) + VariableDefinition variableDefinition = new VariableDefinition("variable", new TypeName("Outer")) + + when: + ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: [inner: [x: 1]]]), graphQLContext, locale) + + then: + def e = thrown(expectedException) + e.message == expectedMessage + + where: + testCase | defaultSetter || expectedException | expectedMessage + "internal default" | { it.defaultValue([a: 1, b: 2]) } || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'." + "literal default" | { it.defaultValueLiteral(ObjectValue.newObjectValue().objectField(new ObjectField("a", NullValue.of())).build()) } || OneOfNullValueException | "OneOf type field 'OneOf.a' must be non-null." + } + + def "getVariableValues: oneOf violations in nested external default values are reported"() { + given: + def oneOfType = newInputObject() + .name("OneOf") + .withAppliedDirective(Directives.OneOfDirective.toAppliedDirective()) + .field(newInputObjectField().name("a").type(GraphQLInt)) + .field(newInputObjectField().name("b").type(GraphQLInt)) + .build() + def inner = newInputObject() + .name("Inner") + .field(newInputObjectField().name("child").type(oneOfType).defaultValueProgrammatic([a: 1, b: 2])) + .field(newInputObjectField().name("x").type(GraphQLInt)) + .build() + def outer = newInputObject() + .name("Outer") + .field(newInputObjectField().name("inner").type(inner)) + .build() + + when: "the schema is built" + TestUtil.schemaWithInputType(outer) + + then: "external defaults are coerced, and so oneOf validated, during schema validation" + thrown(OneOfTooManyKeysException) + } + class Person { def name = "" def id = 0