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

279 lines
9.2KB

  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. "fmt"
  17. "strings"
  18. "github.com/go-openapi/spec"
  19. )
  20. // defaultValidator validates default values in a spec.
  21. // According to Swagger spec, default values MUST validate their schema.
  22. type defaultValidator struct {
  23. SpecValidator *SpecValidator
  24. visitedSchemas map[string]bool
  25. }
  26. // resetVisited resets the internal state of visited schemas
  27. func (d *defaultValidator) resetVisited() {
  28. d.visitedSchemas = map[string]bool{}
  29. }
  30. // beingVisited asserts a schema is being visited
  31. func (d *defaultValidator) beingVisited(path string) {
  32. d.visitedSchemas[path] = true
  33. }
  34. // isVisited tells if a path has already been visited
  35. func (d *defaultValidator) isVisited(path string) bool {
  36. found := d.visitedSchemas[path]
  37. if !found {
  38. // search for overlapping paths
  39. frags := strings.Split(path, ".")
  40. if len(frags) < 2 {
  41. // shortcut exit on smaller paths
  42. return found
  43. }
  44. last := len(frags) - 1
  45. var currentFragStr, parent string
  46. for i := range frags {
  47. if i == 0 {
  48. currentFragStr = frags[last]
  49. } else {
  50. currentFragStr = strings.Join([]string{frags[last-i], currentFragStr}, ".")
  51. }
  52. if i < last {
  53. parent = strings.Join(frags[0:last-i], ".")
  54. } else {
  55. parent = ""
  56. }
  57. if strings.HasSuffix(parent, currentFragStr) {
  58. found = true
  59. break
  60. }
  61. }
  62. }
  63. return found
  64. }
  65. // Validate validates the default values declared in the swagger spec
  66. func (d *defaultValidator) Validate() (errs *Result) {
  67. errs = new(Result)
  68. if d == nil || d.SpecValidator == nil {
  69. return errs
  70. }
  71. d.resetVisited()
  72. errs.Merge(d.validateDefaultValueValidAgainstSchema()) // error -
  73. return errs
  74. }
  75. func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result {
  76. // every default value that is specified must validate against the schema for that property
  77. // headers, items, parameters, schema
  78. res := new(Result)
  79. s := d.SpecValidator
  80. for method, pathItem := range s.analyzer.Operations() {
  81. if pathItem != nil { // Safeguard
  82. for path, op := range pathItem {
  83. // parameters
  84. for _, param := range paramHelp.safeExpandedParamsFor(path, method, op.ID, res, s) {
  85. if param.Default != nil && param.Required {
  86. res.AddWarnings(requiredHasDefaultMsg(param.Name, param.In))
  87. }
  88. // reset explored schemas to get depth-first recursive-proof exploration
  89. d.resetVisited()
  90. // Check simple parameters first
  91. // default values provided must validate against their inline definition (no explicit schema)
  92. if param.Default != nil && param.Schema == nil {
  93. // check param default value is valid
  94. red := NewParamValidator(&param, s.KnownFormats).Validate(param.Default)
  95. if red.HasErrorsOrWarnings() {
  96. res.AddErrors(defaultValueDoesNotValidateMsg(param.Name, param.In))
  97. res.Merge(red)
  98. }
  99. }
  100. // Recursively follows Items and Schemas
  101. if param.Items != nil {
  102. red := d.validateDefaultValueItemsAgainstSchema(param.Name, param.In, &param, param.Items)
  103. if red.HasErrorsOrWarnings() {
  104. res.AddErrors(defaultValueItemsDoesNotValidateMsg(param.Name, param.In))
  105. res.Merge(red)
  106. }
  107. }
  108. if param.Schema != nil {
  109. // Validate default value against schema
  110. red := d.validateDefaultValueSchemaAgainstSchema(param.Name, param.In, param.Schema)
  111. if red.HasErrorsOrWarnings() {
  112. res.AddErrors(defaultValueDoesNotValidateMsg(param.Name, param.In))
  113. res.Merge(red)
  114. }
  115. }
  116. }
  117. if op.Responses != nil {
  118. if op.Responses.Default != nil {
  119. // Same constraint on default Response
  120. res.Merge(d.validateDefaultInResponse(op.Responses.Default, "default", path, 0, op.ID))
  121. }
  122. // Same constraint on regular Responses
  123. if op.Responses.StatusCodeResponses != nil { // Safeguard
  124. for code, r := range op.Responses.StatusCodeResponses {
  125. res.Merge(d.validateDefaultInResponse(&r, "response", path, code, op.ID))
  126. }
  127. }
  128. } else {
  129. // Empty op.ID means there is no meaningful operation: no need to report a specific message
  130. if op.ID != "" {
  131. res.AddErrors(noValidResponseMsg(op.ID))
  132. }
  133. }
  134. }
  135. }
  136. }
  137. if s.spec.Spec().Definitions != nil { // Safeguard
  138. // reset explored schemas to get depth-first recursive-proof exploration
  139. d.resetVisited()
  140. for nm, sch := range s.spec.Spec().Definitions {
  141. res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("definitions.%s", nm), "body", &sch))
  142. }
  143. }
  144. return res
  145. }
  146. func (d *defaultValidator) validateDefaultInResponse(resp *spec.Response, responseType, path string, responseCode int, operationID string) *Result {
  147. s := d.SpecValidator
  148. response, res := responseHelp.expandResponseRef(resp, path, s)
  149. if !res.IsValid() {
  150. return res
  151. }
  152. responseName, responseCodeAsStr := responseHelp.responseMsgVariants(responseType, responseCode)
  153. if response.Headers != nil { // Safeguard
  154. for nm, h := range response.Headers {
  155. // reset explored schemas to get depth-first recursive-proof exploration
  156. d.resetVisited()
  157. if h.Default != nil {
  158. red := NewHeaderValidator(nm, &h, s.KnownFormats).Validate(h.Default)
  159. if red.HasErrorsOrWarnings() {
  160. res.AddErrors(defaultValueHeaderDoesNotValidateMsg(operationID, nm, responseName))
  161. res.Merge(red)
  162. }
  163. }
  164. // Headers have inline definition, like params
  165. if h.Items != nil {
  166. red := d.validateDefaultValueItemsAgainstSchema(nm, "header", &h, h.Items)
  167. if red.HasErrorsOrWarnings() {
  168. res.AddErrors(defaultValueHeaderItemsDoesNotValidateMsg(operationID, nm, responseName))
  169. res.Merge(red)
  170. }
  171. }
  172. if _, err := compileRegexp(h.Pattern); err != nil {
  173. res.AddErrors(invalidPatternInHeaderMsg(operationID, nm, responseName, h.Pattern, err))
  174. }
  175. // Headers don't have schema
  176. }
  177. }
  178. if response.Schema != nil {
  179. // reset explored schemas to get depth-first recursive-proof exploration
  180. d.resetVisited()
  181. red := d.validateDefaultValueSchemaAgainstSchema(responseCodeAsStr, "response", response.Schema)
  182. if red.HasErrorsOrWarnings() {
  183. // Additional message to make sure the context of the error is not lost
  184. res.AddErrors(defaultValueInDoesNotValidateMsg(operationID, responseName))
  185. res.Merge(red)
  186. }
  187. }
  188. return res
  189. }
  190. func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in string, schema *spec.Schema) *Result {
  191. if schema == nil || d.isVisited(path) {
  192. // Avoids recursing if we are already done with that check
  193. return nil
  194. }
  195. d.beingVisited(path)
  196. res := new(Result)
  197. s := d.SpecValidator
  198. if schema.Default != nil {
  199. res.Merge(NewSchemaValidator(schema, s.spec.Spec(), path+".default", s.KnownFormats).Validate(schema.Default))
  200. }
  201. if schema.Items != nil {
  202. if schema.Items.Schema != nil {
  203. res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+".items.default", in, schema.Items.Schema))
  204. }
  205. // Multiple schemas in items
  206. if schema.Items.Schemas != nil { // Safeguard
  207. for i, sch := range schema.Items.Schemas {
  208. res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.items[%d].default", path, i), in, &sch))
  209. }
  210. }
  211. }
  212. if _, err := compileRegexp(schema.Pattern); err != nil {
  213. res.AddErrors(invalidPatternInMsg(path, in, schema.Pattern))
  214. }
  215. if schema.AdditionalItems != nil && schema.AdditionalItems.Schema != nil {
  216. // NOTE: we keep validating values, even though additionalItems is not supported by Swagger 2.0 (and 3.0 as well)
  217. res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalItems", path), in, schema.AdditionalItems.Schema))
  218. }
  219. for propName, prop := range schema.Properties {
  220. res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+"."+propName, in, &prop))
  221. }
  222. for propName, prop := range schema.PatternProperties {
  223. res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+"."+propName, in, &prop))
  224. }
  225. if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
  226. res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalProperties", path), in, schema.AdditionalProperties.Schema))
  227. }
  228. if schema.AllOf != nil {
  229. for i, aoSch := range schema.AllOf {
  230. res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.allOf[%d]", path, i), in, &aoSch))
  231. }
  232. }
  233. return res
  234. }
  235. func (d *defaultValidator) validateDefaultValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result {
  236. res := new(Result)
  237. s := d.SpecValidator
  238. if items != nil {
  239. if items.Default != nil {
  240. res.Merge(newItemsValidator(path, in, items, root, s.KnownFormats).Validate(0, items.Default))
  241. }
  242. if items.Items != nil {
  243. res.Merge(d.validateDefaultValueItemsAgainstSchema(path+"[0].default", in, root, items.Items))
  244. }
  245. if _, err := compileRegexp(items.Pattern); err != nil {
  246. res.AddErrors(invalidPatternInMsg(path, in, items.Pattern))
  247. }
  248. }
  249. return res
  250. }
上海开阖软件有限公司 沪ICP备12045867号-1