本站源代码
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.

269 lines
8.8KB

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