schema.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. specItemsType = reflect.TypeOf(&spec.Items{})
  27. specHeaderType = reflect.TypeOf(&spec.Header{})
  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. }
  38. // AgainstSchema validates the specified data against the provided schema, using a registry of supported formats.
  39. //
  40. // When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example.
  41. func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry) error {
  42. res := NewSchemaValidator(schema, nil, "", formats).Validate(data)
  43. if res.HasErrors() {
  44. return errors.CompositeValidationError(res.Errors...)
  45. }
  46. return nil
  47. }
  48. // NewSchemaValidator creates a new schema validator.
  49. //
  50. // Panics if the provided schema is invalid.
  51. func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry) *SchemaValidator {
  52. if schema == nil {
  53. return nil
  54. }
  55. if rootSchema == nil {
  56. rootSchema = schema
  57. }
  58. if schema.ID != "" || schema.Ref.String() != "" || schema.Ref.IsRoot() {
  59. err := spec.ExpandSchema(schema, rootSchema, nil)
  60. if err != nil {
  61. msg := invalidSchemaProvidedMsg(err).Error()
  62. panic(msg)
  63. }
  64. }
  65. s := SchemaValidator{Path: root, in: "body", Schema: schema, Root: rootSchema, KnownFormats: formats}
  66. s.validators = []valueValidator{
  67. s.typeValidator(),
  68. s.schemaPropsValidator(),
  69. s.stringValidator(),
  70. s.formatValidator(),
  71. s.numberValidator(),
  72. s.sliceValidator(),
  73. s.commonValidator(),
  74. s.objectValidator(),
  75. }
  76. return &s
  77. }
  78. // SetPath sets the path for this schema valdiator
  79. func (s *SchemaValidator) SetPath(path string) {
  80. s.Path = path
  81. }
  82. // Applies returns true when this schema validator applies
  83. func (s *SchemaValidator) Applies(source interface{}, kind reflect.Kind) bool {
  84. _, ok := source.(*spec.Schema)
  85. return ok
  86. }
  87. // Validate validates the data against the schema
  88. func (s *SchemaValidator) Validate(data interface{}) *Result {
  89. result := &Result{data: data}
  90. if s == nil {
  91. return result
  92. }
  93. if s.Schema != nil {
  94. result.addRootObjectSchemata(s.Schema)
  95. }
  96. if data == nil {
  97. result.Merge(s.validators[0].Validate(data)) // type validator
  98. result.Merge(s.validators[6].Validate(data)) // common validator
  99. return result
  100. }
  101. tpe := reflect.TypeOf(data)
  102. kind := tpe.Kind()
  103. for kind == reflect.Ptr {
  104. tpe = tpe.Elem()
  105. kind = tpe.Kind()
  106. }
  107. d := data
  108. if kind == reflect.Struct {
  109. // NOTE: since reflect retrieves the true nature of types
  110. // this means that all strfmt types passed here (e.g. strfmt.Datetime, etc..)
  111. // are converted here to strings, and structs are systematically converted
  112. // to map[string]interface{}.
  113. d = swag.ToDynamicJSON(data)
  114. }
  115. // TODO: this part should be handed over to type validator
  116. // Handle special case of json.Number data (number marshalled as string)
  117. isnumber := s.Schema.Type.Contains("number") || s.Schema.Type.Contains("integer")
  118. if num, ok := data.(json.Number); ok && isnumber {
  119. if s.Schema.Type.Contains("integer") { // avoid lossy conversion
  120. in, erri := num.Int64()
  121. if erri != nil {
  122. result.AddErrors(invalidTypeConversionMsg(s.Path, erri))
  123. result.Inc()
  124. return result
  125. }
  126. d = in
  127. } else {
  128. nf, errf := num.Float64()
  129. if errf != nil {
  130. result.AddErrors(invalidTypeConversionMsg(s.Path, errf))
  131. result.Inc()
  132. return result
  133. }
  134. d = nf
  135. }
  136. tpe = reflect.TypeOf(d)
  137. kind = tpe.Kind()
  138. }
  139. for _, v := range s.validators {
  140. if !v.Applies(s.Schema, kind) {
  141. debugLog("%T does not apply for %v", v, kind)
  142. continue
  143. }
  144. err := v.Validate(d)
  145. result.Merge(err)
  146. result.Inc()
  147. }
  148. result.Inc()
  149. return result
  150. }
  151. func (s *SchemaValidator) typeValidator() valueValidator {
  152. return &typeValidator{Type: s.Schema.Type, Format: s.Schema.Format, In: s.in, Path: s.Path}
  153. }
  154. func (s *SchemaValidator) commonValidator() valueValidator {
  155. return &basicCommonValidator{
  156. Path: s.Path,
  157. In: s.in,
  158. Enum: s.Schema.Enum,
  159. }
  160. }
  161. func (s *SchemaValidator) sliceValidator() valueValidator {
  162. return &schemaSliceValidator{
  163. Path: s.Path,
  164. In: s.in,
  165. MaxItems: s.Schema.MaxItems,
  166. MinItems: s.Schema.MinItems,
  167. UniqueItems: s.Schema.UniqueItems,
  168. AdditionalItems: s.Schema.AdditionalItems,
  169. Items: s.Schema.Items,
  170. Root: s.Root,
  171. KnownFormats: s.KnownFormats,
  172. }
  173. }
  174. func (s *SchemaValidator) numberValidator() valueValidator {
  175. return &numberValidator{
  176. Path: s.Path,
  177. In: s.in,
  178. Default: s.Schema.Default,
  179. MultipleOf: s.Schema.MultipleOf,
  180. Maximum: s.Schema.Maximum,
  181. ExclusiveMaximum: s.Schema.ExclusiveMaximum,
  182. Minimum: s.Schema.Minimum,
  183. ExclusiveMinimum: s.Schema.ExclusiveMinimum,
  184. }
  185. }
  186. func (s *SchemaValidator) stringValidator() valueValidator {
  187. return &stringValidator{
  188. Path: s.Path,
  189. In: s.in,
  190. MaxLength: s.Schema.MaxLength,
  191. MinLength: s.Schema.MinLength,
  192. Pattern: s.Schema.Pattern,
  193. }
  194. }
  195. func (s *SchemaValidator) formatValidator() valueValidator {
  196. return &formatValidator{
  197. Path: s.Path,
  198. In: s.in,
  199. Format: s.Schema.Format,
  200. KnownFormats: s.KnownFormats,
  201. }
  202. }
  203. func (s *SchemaValidator) schemaPropsValidator() valueValidator {
  204. sch := s.Schema
  205. return newSchemaPropsValidator(s.Path, s.in, sch.AllOf, sch.OneOf, sch.AnyOf, sch.Not, sch.Dependencies, s.Root, s.KnownFormats)
  206. }
  207. func (s *SchemaValidator) objectValidator() valueValidator {
  208. return &objectValidator{
  209. Path: s.Path,
  210. In: s.in,
  211. MaxProperties: s.Schema.MaxProperties,
  212. MinProperties: s.Schema.MinProperties,
  213. Required: s.Schema.Required,
  214. Properties: s.Schema.Properties,
  215. AdditionalProperties: s.Schema.AdditionalProperties,
  216. PatternProperties: s.Schema.PatternProperties,
  217. Root: s.Root,
  218. KnownFormats: s.KnownFormats,
  219. }
  220. }