You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

schema.go 7.0KB

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