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.

270 lines
9.4 KiB

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