object_validator.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. "reflect"
  17. "regexp"
  18. "strings"
  19. "github.com/go-openapi/errors"
  20. "github.com/go-openapi/spec"
  21. "github.com/go-openapi/strfmt"
  22. )
  23. type objectValidator struct {
  24. Path string
  25. In string
  26. MaxProperties *int64
  27. MinProperties *int64
  28. Required []string
  29. Properties map[string]spec.Schema
  30. AdditionalProperties *spec.SchemaOrBool
  31. PatternProperties map[string]spec.Schema
  32. Root interface{}
  33. KnownFormats strfmt.Registry
  34. }
  35. func (o *objectValidator) SetPath(path string) {
  36. o.Path = path
  37. }
  38. func (o *objectValidator) Applies(source interface{}, kind reflect.Kind) bool {
  39. // TODO: this should also work for structs
  40. // there is a problem in the type validator where it will be unhappy about null values
  41. // so that requires more testing
  42. r := reflect.TypeOf(source) == specSchemaType && (kind == reflect.Map || kind == reflect.Struct)
  43. debugLog("object validator for %q applies %t for %T (kind: %v)\n", o.Path, r, source, kind)
  44. return r
  45. }
  46. func (o *objectValidator) isPropertyName() bool {
  47. p := strings.Split(o.Path, ".")
  48. return p[len(p)-1] == "properties" && p[len(p)-2] != "properties"
  49. }
  50. func (o *objectValidator) checkArrayMustHaveItems(res *Result, val map[string]interface{}) {
  51. if t, typeFound := val["type"]; typeFound {
  52. if tpe, ok := t.(string); ok && tpe == "array" {
  53. if _, itemsKeyFound := val["items"]; !itemsKeyFound {
  54. res.AddErrors(errors.Required("items", o.Path))
  55. }
  56. }
  57. }
  58. }
  59. func (o *objectValidator) checkItemsMustBeTypeArray(res *Result, val map[string]interface{}) {
  60. if !o.isPropertyName() {
  61. if _, itemsKeyFound := val["items"]; itemsKeyFound {
  62. t, typeFound := val["type"]
  63. if typeFound {
  64. if tpe, ok := t.(string); !ok || tpe != "array" {
  65. res.AddErrors(errors.InvalidType(o.Path, o.In, "array", nil))
  66. }
  67. } else {
  68. // there is no type
  69. res.AddErrors(errors.Required("type", o.Path))
  70. }
  71. }
  72. }
  73. }
  74. func (o *objectValidator) precheck(res *Result, val map[string]interface{}) {
  75. o.checkArrayMustHaveItems(res, val)
  76. o.checkItemsMustBeTypeArray(res, val)
  77. }
  78. func (o *objectValidator) Validate(data interface{}) *Result {
  79. val := data.(map[string]interface{})
  80. // TODO: guard against nil data
  81. numKeys := int64(len(val))
  82. if o.MinProperties != nil && numKeys < *o.MinProperties {
  83. return errorHelp.sErr(errors.TooFewProperties(o.Path, o.In, *o.MinProperties))
  84. }
  85. if o.MaxProperties != nil && numKeys > *o.MaxProperties {
  86. return errorHelp.sErr(errors.TooManyProperties(o.Path, o.In, *o.MaxProperties))
  87. }
  88. res := new(Result)
  89. o.precheck(res, val)
  90. // check validity of field names
  91. if o.AdditionalProperties != nil && !o.AdditionalProperties.Allows {
  92. // Case: additionalProperties: false
  93. for k := range val {
  94. _, regularProperty := o.Properties[k]
  95. matched := false
  96. for pk := range o.PatternProperties {
  97. if matches, _ := regexp.MatchString(pk, k); matches {
  98. matched = true
  99. break
  100. }
  101. }
  102. if !regularProperty && k != "$schema" && k != "id" && !matched {
  103. // Special properties "$schema" and "id" are ignored
  104. res.AddErrors(errors.PropertyNotAllowed(o.Path, o.In, k))
  105. // BUG(fredbi): This section should move to a part dedicated to spec validation as
  106. // it will conflict with regular schemas where a property "headers" is defined.
  107. //
  108. // Croaks a more explicit message on top of the standard one
  109. // on some recognized cases.
  110. //
  111. // NOTE: edge cases with invalid type assertion are simply ignored here.
  112. // NOTE: prefix your messages here by "IMPORTANT!" so there are not filtered
  113. // by higher level callers (the IMPORTANT! tag will be eventually
  114. // removed).
  115. switch k {
  116. // $ref is forbidden in header
  117. case "headers":
  118. if val[k] != nil {
  119. if headers, mapOk := val[k].(map[string]interface{}); mapOk {
  120. for headerKey, headerBody := range headers {
  121. if headerBody != nil {
  122. if headerSchema, mapOfMapOk := headerBody.(map[string]interface{}); mapOfMapOk {
  123. if _, found := headerSchema["$ref"]; found {
  124. var msg string
  125. if refString, stringOk := headerSchema["$ref"].(string); stringOk {
  126. msg = strings.Join([]string{", one may not use $ref=\":", refString, "\""}, "")
  127. }
  128. res.AddErrors(refNotAllowedInHeaderMsg(o.Path, headerKey, msg))
  129. }
  130. }
  131. }
  132. }
  133. }
  134. }
  135. /*
  136. case "$ref":
  137. if val[k] != nil {
  138. // TODO: check context of that ref: warn about siblings, check against invalid context
  139. }
  140. */
  141. }
  142. }
  143. }
  144. } else {
  145. // Cases: no additionalProperties (implying: true), or additionalProperties: true, or additionalProperties: { <<schema>> }
  146. for key, value := range val {
  147. _, regularProperty := o.Properties[key]
  148. // Validates property against "patternProperties" if applicable
  149. // BUG(fredbi): succeededOnce is always false
  150. // NOTE: how about regular properties which do not match patternProperties?
  151. matched, succeededOnce, _ := o.validatePatternProperty(key, value, res)
  152. if !(regularProperty || matched || succeededOnce) {
  153. // Cases: properties which are not regular properties and have not been matched by the PatternProperties validator
  154. if o.AdditionalProperties != nil && o.AdditionalProperties.Schema != nil {
  155. // AdditionalProperties as Schema
  156. r := NewSchemaValidator(o.AdditionalProperties.Schema, o.Root, o.Path+"."+key, o.KnownFormats).Validate(value)
  157. res.mergeForField(data.(map[string]interface{}), key, r)
  158. } else if regularProperty && !(matched || succeededOnce) {
  159. // TODO: this is dead code since regularProperty=false here
  160. res.AddErrors(errors.FailedAllPatternProperties(o.Path, o.In, key))
  161. }
  162. }
  163. }
  164. // Valid cases: additionalProperties: true or undefined
  165. }
  166. createdFromDefaults := map[string]bool{}
  167. // Property types:
  168. // - regular Property
  169. for pName := range o.Properties {
  170. pSchema := o.Properties[pName] // one instance per iteration
  171. rName := pName
  172. if o.Path != "" {
  173. rName = o.Path + "." + pName
  174. }
  175. // Recursively validates each property against its schema
  176. if v, ok := val[pName]; ok {
  177. r := NewSchemaValidator(&pSchema, o.Root, rName, o.KnownFormats).Validate(v)
  178. res.mergeForField(data.(map[string]interface{}), pName, r)
  179. } else if pSchema.Default != nil {
  180. // If a default value is defined, creates the property from defaults
  181. // NOTE: JSON schema does not enforce default values to be valid against schema. Swagger does.
  182. createdFromDefaults[pName] = true
  183. res.addPropertySchemata(data.(map[string]interface{}), pName, &pSchema)
  184. }
  185. }
  186. // Check required properties
  187. if len(o.Required) > 0 {
  188. for _, k := range o.Required {
  189. if _, ok := val[k]; !ok && !createdFromDefaults[k] {
  190. res.AddErrors(errors.Required(o.Path+"."+k, o.In))
  191. continue
  192. }
  193. }
  194. }
  195. // Check patternProperties
  196. // TODO: it looks like we have done that twice in many cases
  197. for key, value := range val {
  198. _, regularProperty := o.Properties[key]
  199. matched, _ /*succeededOnce*/, patterns := o.validatePatternProperty(key, value, res)
  200. if !regularProperty && (matched /*|| succeededOnce*/) {
  201. for _, pName := range patterns {
  202. if v, ok := o.PatternProperties[pName]; ok {
  203. r := NewSchemaValidator(&v, o.Root, o.Path+"."+key, o.KnownFormats).Validate(value)
  204. res.mergeForField(data.(map[string]interface{}), key, r)
  205. }
  206. }
  207. }
  208. }
  209. return res
  210. }
  211. // TODO: succeededOnce is not used anywhere
  212. func (o *objectValidator) validatePatternProperty(key string, value interface{}, result *Result) (bool, bool, []string) {
  213. matched := false
  214. succeededOnce := false
  215. var patterns []string
  216. for k, schema := range o.PatternProperties {
  217. if match, _ := regexp.MatchString(k, key); match {
  218. patterns = append(patterns, k)
  219. matched = true
  220. validator := NewSchemaValidator(&schema, o.Root, o.Path+"."+key, o.KnownFormats)
  221. res := validator.Validate(value)
  222. result.Merge(res)
  223. }
  224. }
  225. // BUG(fredbi): can't get to here. Should remove dead code (commented out).
  226. //if succeededOnce {
  227. // result.Inc()
  228. //}
  229. return matched, succeededOnce, patterns
  230. }