schema.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validate
  15. import (
  16. "encoding/json"
  17. "reflect"
  18. "github.com/go-openapi/errors"
  19. "github.com/go-openapi/spec"
  20. "github.com/go-openapi/strfmt"
  21. "github.com/go-openapi/swag"
  22. )
  23. var (
  24. specSchemaType = reflect.TypeOf(&spec.Schema{})
  25. specParameterType = reflect.TypeOf(&spec.Parameter{})
  26. specHeaderType = reflect.TypeOf(&spec.Header{})
  27. //specItemsType = reflect.TypeOf(&spec.Items{})
  28. )
  29. // SchemaValidator validates data against a JSON schema
  30. type SchemaValidator struct {
  31. Path string
  32. in string
  33. Schema *spec.Schema
  34. validators []valueValidator
  35. Root interface{}
  36. KnownFormats strfmt.Registry
  37. Options SchemaValidatorOptions
  38. }
  39. // AgainstSchema validates the specified data against the provided schema, using a registry of supported formats.
  40. //
  41. // When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example.
  42. func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry, options ...Option) error {
  43. res := NewSchemaValidator(schema, nil, "", formats, options...).Validate(data)
  44. if res.HasErrors() {
  45. return errors.CompositeValidationError(res.Errors...)
  46. }
  47. return nil
  48. }
  49. // NewSchemaValidator creates a new schema validator.
  50. //
  51. // Panics if the provided schema is invalid.
  52. func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, options ...Option) *SchemaValidator {
  53. if schema == nil {
  54. return nil
  55. }
  56. if rootSchema == nil {
  57. rootSchema = schema
  58. }
  59. if schema.ID != "" || schema.Ref.String() != "" || schema.Ref.IsRoot() {
  60. err := spec.ExpandSchema(schema, rootSchema, nil)
  61. if err != nil {
  62. msg := invalidSchemaProvidedMsg(err).Error()
  63. panic(msg)
  64. }
  65. }
  66. s := SchemaValidator{
  67. Path: root,
  68. in: "body",
  69. Schema: schema,
  70. Root: rootSchema,
  71. KnownFormats: formats,
  72. Options: SchemaValidatorOptions{}}
  73. for _, o := range options {
  74. o(&s.Options)
  75. }
  76. s.validators = []valueValidator{
  77. s.typeValidator(),
  78. s.schemaPropsValidator(),
  79. s.stringValidator(),
  80. s.formatValidator(),
  81. s.numberValidator(),
  82. s.sliceValidator(),
  83. s.commonValidator(),
  84. s.objectValidator(),
  85. }
  86. return &s
  87. }
  88. // SetPath sets the path for this schema valdiator
  89. func (s *SchemaValidator) SetPath(path string) {
  90. s.Path = path
  91. }
  92. // Applies returns true when this schema validator applies
  93. func (s *SchemaValidator) Applies(source interface{}, kind reflect.Kind) bool {
  94. _, ok := source.(*spec.Schema)
  95. return ok
  96. }
  97. // Validate validates the data against the schema
  98. func (s *SchemaValidator) Validate(data interface{}) *Result {
  99. result := &Result{data: data}
  100. if s == nil {
  101. return result
  102. }
  103. if s.Schema != nil {
  104. result.addRootObjectSchemata(s.Schema)
  105. }
  106. if data == nil {
  107. result.Merge(s.validators[0].Validate(data)) // type validator
  108. result.Merge(s.validators[6].Validate(data)) // common validator
  109. return result
  110. }
  111. tpe := reflect.TypeOf(data)
  112. kind := tpe.Kind()
  113. for kind == reflect.Ptr {
  114. tpe = tpe.Elem()
  115. kind = tpe.Kind()
  116. }
  117. d := data
  118. if kind == reflect.Struct {
  119. // NOTE: since reflect retrieves the true nature of types
  120. // this means that all strfmt types passed here (e.g. strfmt.Datetime, etc..)
  121. // are converted here to strings, and structs are systematically converted
  122. // to map[string]interface{}.
  123. d = swag.ToDynamicJSON(data)
  124. }
  125. // TODO: this part should be handed over to type validator
  126. // Handle special case of json.Number data (number marshalled as string)
  127. isnumber := s.Schema.Type.Contains(numberType) || s.Schema.Type.Contains(integerType)
  128. if num, ok := data.(json.Number); ok && isnumber {
  129. if s.Schema.Type.Contains(integerType) { // avoid lossy conversion
  130. in, erri := num.Int64()
  131. if erri != nil {
  132. result.AddErrors(invalidTypeConversionMsg(s.Path, erri))
  133. result.Inc()
  134. return result
  135. }
  136. d = in
  137. } else {
  138. nf, errf := num.Float64()
  139. if errf != nil {
  140. result.AddErrors(invalidTypeConversionMsg(s.Path, errf))
  141. result.Inc()
  142. return result
  143. }
  144. d = nf
  145. }
  146. tpe = reflect.TypeOf(d)
  147. kind = tpe.Kind()
  148. }
  149. for _, v := range s.validators {
  150. if !v.Applies(s.Schema, kind) {
  151. debugLog("%T does not apply for %v", v, kind)
  152. continue
  153. }
  154. err := v.Validate(d)
  155. result.Merge(err)
  156. result.Inc()
  157. }
  158. result.Inc()
  159. return result
  160. }
  161. func (s *SchemaValidator) typeValidator() valueValidator {
  162. return &typeValidator{Type: s.Schema.Type, Nullable: s.Schema.Nullable, Format: s.Schema.Format, In: s.in, Path: s.Path}
  163. }
  164. func (s *SchemaValidator) commonValidator() valueValidator {
  165. return &basicCommonValidator{
  166. Path: s.Path,
  167. In: s.in,
  168. Enum: s.Schema.Enum,
  169. }
  170. }
  171. func (s *SchemaValidator) sliceValidator() valueValidator {
  172. return &schemaSliceValidator{
  173. Path: s.Path,
  174. In: s.in,
  175. MaxItems: s.Schema.MaxItems,
  176. MinItems: s.Schema.MinItems,
  177. UniqueItems: s.Schema.UniqueItems,
  178. AdditionalItems: s.Schema.AdditionalItems,
  179. Items: s.Schema.Items,
  180. Root: s.Root,
  181. KnownFormats: s.KnownFormats,
  182. Options: s.Options,
  183. }
  184. }
  185. func (s *SchemaValidator) numberValidator() valueValidator {
  186. return &numberValidator{
  187. Path: s.Path,
  188. In: s.in,
  189. Default: s.Schema.Default,
  190. MultipleOf: s.Schema.MultipleOf,
  191. Maximum: s.Schema.Maximum,
  192. ExclusiveMaximum: s.Schema.ExclusiveMaximum,
  193. Minimum: s.Schema.Minimum,
  194. ExclusiveMinimum: s.Schema.ExclusiveMinimum,
  195. }
  196. }
  197. func (s *SchemaValidator) stringValidator() valueValidator {
  198. return &stringValidator{
  199. Path: s.Path,
  200. In: s.in,
  201. MaxLength: s.Schema.MaxLength,
  202. MinLength: s.Schema.MinLength,
  203. Pattern: s.Schema.Pattern,
  204. }
  205. }
  206. func (s *SchemaValidator) formatValidator() valueValidator {
  207. return &formatValidator{
  208. Path: s.Path,
  209. In: s.in,
  210. Format: s.Schema.Format,
  211. KnownFormats: s.KnownFormats,
  212. }
  213. }
  214. func (s *SchemaValidator) schemaPropsValidator() valueValidator {
  215. sch := s.Schema
  216. return newSchemaPropsValidator(s.Path, s.in, sch.AllOf, sch.OneOf, sch.AnyOf, sch.Not, sch.Dependencies, s.Root, s.KnownFormats, s.Options.Options()...)
  217. }
  218. func (s *SchemaValidator) objectValidator() valueValidator {
  219. return &objectValidator{
  220. Path: s.Path,
  221. In: s.in,
  222. MaxProperties: s.Schema.MaxProperties,
  223. MinProperties: s.Schema.MinProperties,
  224. Required: s.Schema.Required,
  225. Properties: s.Schema.Properties,
  226. AdditionalProperties: s.Schema.AdditionalProperties,
  227. PatternProperties: s.Schema.PatternProperties,
  228. Root: s.Root,
  229. KnownFormats: s.KnownFormats,
  230. Options: s.Options,
  231. }
  232. }