Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validation for input objects #244

Merged
merged 6 commits into from
Feb 28, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 65 additions & 3 deletions core/src/main/scala/caliban/validation/Validator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ object Validator {
def validateSchema(rootType: RootType): IO[ValidationError, Unit] =
IO.foreach(rootType.types.values) { t =>
t.kind match {
case __TypeKind.ENUM => validateEnum(t)
case __TypeKind.UNION => validateUnion(t)
case _ => IO.unit
case __TypeKind.ENUM => validateEnum(t)
case __TypeKind.UNION => validateUnion(t)
case __TypeKind.INPUT_OBJECT => validateInputObject(t)
case _ => IO.unit
}
}
.unit
Expand Down Expand Up @@ -591,6 +592,67 @@ object Validator {

}

private def validateInputObject(t: __Type): IO[ValidationError, Unit] = {
// https://spec.graphql.org/June2018/#IsInputType()
def isInputType(t: __Type): Either[__Type, Unit] = t.kind match {
case __TypeKind.LIST | __TypeKind.NON_NULL => t.ofType.fold[Either[__Type, Unit]](Left(t))(isInputType)
ghostdogpr marked this conversation as resolved.
Show resolved Hide resolved
case __TypeKind.SCALAR | __TypeKind.ENUM | __TypeKind.INPUT_OBJECT => Right(())
case _ => Left(t)
}

def failValidation(msg: String, explanatoryText: String): IO[ValidationError, Unit] =
ghostdogpr marked this conversation as resolved.
Show resolved Hide resolved
IO.fail(ValidationError(msg, explanatoryText))

def validateFields(fields: List[__InputValue]): IO[ValidationError, Unit] =
duplicateFieldName(fields).flatMap(_ =>
ghostdogpr marked this conversation as resolved.
Show resolved Hide resolved
IO.foreach(fields)(field =>
for {
_ <- doesNotStartWithUnderscore(field)
_ <- onlyInputFieldType(field)
} yield ()
)
.unit
)

def duplicateFieldName(fields: List[__InputValue]): IO[ValidationError, Unit] =
fields
.groupBy(_.name)
.collectFirst { case (_, f :: _ :: _) => f }
.fold[IO[ValidationError, Unit]](IO.unit)(duplicateField =>
failValidation(
s"InputObject has repeated fields: ${duplicateField.name}",
"The input field must have a unique name within that Input Object type; no two input fields may share the same name"
)
)

def doesNotStartWithUnderscore(field: __InputValue): IO[ValidationError, Unit] =
IO.when(field.name.startsWith("__"))(
failValidation(
s"InputObject can't start with '__': ${field.name}",
"""The input field must not have a name which begins with the
characters {"__"} (two underscores)"""
)
)

def onlyInputFieldType(field: __InputValue): IO[ValidationError, Unit] =
IO.whenCase(isInputType(field.`type`())) {
case Left(errorType) =>
failValidation(
s"${errorType.name.getOrElse("")} is of kind ${errorType.kind}, must be an InputType",
"""The input field must accept a type where IsInputType(inputFieldType) returns true, https://spec.graphql.org/June2018/#IsInputType()"""
)
}

t.inputFields match {
case None | Some(Nil) =>
failValidation(
s"InputObject ${t.name.getOrElse("")} does not have fields",
"An Input Object type must define one or more input fields"
)
case Some(fields) => validateFields(fields)
}
}

case class Context(
document: Document,
rootType: RootType,
Expand Down
24 changes: 24 additions & 0 deletions core/src/test/scala/caliban/TestUtils.scala
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,28 @@ object TestUtils {
SubscriptionIO(ZStream.empty)
)

object InvalidSchemas {
case class DoubleUnderscoreArg(__name: String)
case class DoubleUnderscoreInputObjectArg(wrong: DoubleUnderscoreArg)
case class WrongMutationUnderscore(w: DoubleUnderscoreInputObjectArg => UIO[Unit])

val resolverWrongMutationUnderscore = RootResolver(
resolverIO.queryResolver,
WrongMutationUnderscore(_ => UIO.unit)
)

sealed trait UnionInput
object UnionInput {
case class A(value: String) extends UnionInput
case class B(value: String) extends UnionInput
}
case class UnionArg(union: UnionInput)
case class UnionInputObjectArg(wrong: UnionArg)
case class WrongMutationUnion(w: UnionInputObjectArg => UIO[Unit])

val resolverWrongMutationUnion = RootResolver(
resolverIO.queryResolver,
WrongMutationUnion(_ => UIO.unit)
)
}
}
59 changes: 59 additions & 0 deletions core/src/test/scala/caliban/validation/ValidationSchemaSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package caliban.validation

import caliban.CalibanError.ValidationError
import caliban.GraphQL
import caliban.GraphQL.graphQL
import caliban.TestUtils.InvalidSchemas._
import caliban.introspection.adt.__TypeKind.{ INPUT_OBJECT, SCALAR }
import caliban.introspection.adt.{ __InputValue, __Type }
import caliban.schema.RootType
import zio.IO
import zio.test.Assertion._
import zio.test._

object ValidationSchemaSpec
extends DefaultRunnableSpec({
def check(gql: GraphQL[Any], expectedMessage: String): IO[ValidationError, TestResult] =
assertM(gql.interpreter.run, fails[ValidationError](hasField("msg", _.msg, equalTo(expectedMessage))))

suite("ValidationSchemaSpec")({
def checkInputObject(
__type: __Type,
expectedMessage: String
) = {
val validate = Validator.validateSchema(RootType(__Type(kind = SCALAR), Some(__type), None))
assertM(validate.run, fails[ValidationError](hasField("msg", _.msg, equalTo(expectedMessage))))
}

def inputValue(name: String, t: __Type): __InputValue =
__InputValue(name = name, `type` = () => t, description = None, defaultValue = None)

def inputObject(inputs: __InputValue*): __Type =
__Type(
name = Some("inputObject"),
kind = INPUT_OBJECT,
inputFields = Some(inputs.toList)
)

suite("InputObjects")(
testM("any input field must have a unique name within an Input Object") {
checkInputObject(
inputObject(inputValue("duplicate", __Type(SCALAR)), inputValue("duplicate", __Type(SCALAR))),
"InputObject has repeated fields: duplicate"
)
},
testM("name can't start with '__'") {
check(
graphQL(resolverWrongMutationUnderscore),
"InputObject can't start with '__': __name"
)
},
testM("should only contain types for which IsInputType(type) is true") {
check(
graphQL(resolverWrongMutationUnion),
"UnionInput is of kind UNION, must be an InputType"
)
}
)
})
})