default_validator.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. func isVisited(path string, visitedSchemas map[string]bool) bool {
  31. found := visitedSchemas[path]
  32. if !found {
  33. // search for overlapping paths
  34. frags := strings.Split(path, ".")
  35. if len(frags) < 2 {
  36. // shortcut exit on smaller paths
  37. return found
  38. }
  39. last := len(frags) - 1
  40. var currentFragStr, parent string
  41. for i := range frags {
  42. if i == 0 {
  43. currentFragStr = frags[last]
  44. } else {
  45. currentFragStr = strings.Join([]string{frags[last-i], currentFragStr}, ".")
  46. }
  47. if i < last {
  48. parent = strings.Join(frags[0:last-i], ".")
  49. } else {
  50. parent = ""
  51. }
  52. if strings.HasSuffix(parent, currentFragStr) {
  53. found = true
  54. break
  55. }
  56. }
  57. }
  58. return found
  59. }
  60. // beingVisited asserts a schema is being visited
  61. func (d *defaultValidator) beingVisited(path string) {
  62. d.visitedSchemas[path] = true
  63. }
  64. // isVisited tells if a path has already been visited
  65. func (d *defaultValidator) isVisited(path string) bool {
  66. return isVisited(path, d.visitedSchemas)
  67. }
  68. // Validate validates the default values declared in the swagger spec
  69. func (d *defaultValidator) Validate() (errs *Result) {
  70. errs = new(Result)
  71. if d == nil || d.SpecValidator == nil {
  72. return errs
  73. }
  74. d.resetVisited()
  75. errs.Merge(d.validateDefaultValueValidAgainstSchema()) // error -
  76. return errs
  77. }
  78. func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result {
  79. // every default value that is specified must validate against the schema for that property
  80. // headers, items, parameters, schema
  81. res := new(Result)
  82. s := d.SpecValidator
  83. for method, pathItem := range s.analyzer.Operations() {
  84. for path, op := range pathItem {
  85. // parameters
  86. for _, param := range paramHelp.safeExpandedParamsFor(path, method, op.ID, res, s) {
  87. if param.Default != nil && param.Required {
  88. res.AddWarnings(requiredHasDefaultMsg(param.Name, param.In))
  89. }
  90. // reset explored schemas to get depth-first recursive-proof exploration
  91. d.resetVisited()
  92. // Check simple parameters first
  93. // default values provided must validate against their inline definition (no explicit schema)
  94. if param.Default != nil && param.Schema == nil {
  95. // check param default value is valid
  96. red := NewParamValidator(&param, s.KnownFormats).Validate(param.Default)
  97. if red.HasErrorsOrWarnings() {
  98. res.AddErrors(defaultValueDoesNotValidateMsg(param.Name, param.In))
  99. res.Merge(red)
  100. }
  101. }
  102. // Recursively follows Items and Schemas
  103. if param.Items != nil {
  104. red := d.validateDefaultValueItemsAgainstSchema(param.Name, param.In, &param, param.Items)
  105. if red.HasErrorsOrWarnings() {
  106. res.AddErrors(defaultValueItemsDoesNotValidateMsg(param.Name, param.In))
  107. res.Merge(red)
  108. }
  109. }
  110. if param.Schema != nil {
  111. // Validate default value against schema
  112. red := d.validateDefaultValueSchemaAgainstSchema(param.Name, param.In, param.Schema)
  113. if red.HasErrorsOrWarnings() {
  114. res.AddErrors(defaultValueDoesNotValidateMsg(param.Name, param.In))
  115. res.Merge(red)
  116. }
  117. }
  118. }
  119. if op.Responses != nil {
  120. if op.Responses.Default != nil {
  121. // Same constraint on default Response
  122. res.Merge(d.validateDefaultInResponse(op.Responses.Default, jsonDefault, path, 0, op.ID))
  123. }
  124. // Same constraint on regular Responses
  125. if op.Responses.StatusCodeResponses != nil { // Safeguard
  126. for code, r := range op.Responses.StatusCodeResponses {
  127. res.Merge(d.validateDefaultInResponse(&r, "response", path, code, op.ID))
  128. }
  129. }
  130. } else if op.ID != "" {
  131. // Empty op.ID means there is no meaningful operation: no need to report a specific message
  132. res.AddErrors(noValidResponseMsg(op.ID))
  133. }
  134. }
  135. }
  136. if s.spec.Spec().Definitions != nil { // Safeguard
  137. // reset explored schemas to get depth-first recursive-proof exploration
  138. d.resetVisited()
  139. for nm, sch := range s.spec.Spec().Definitions {
  140. res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("definitions.%s", nm), "body", &sch))
  141. }
  142. }
  143. return res
  144. }
  145. func (d *defaultValidator) validateDefaultInResponse(resp *spec.Response, responseType, path string, responseCode int, operationID string) *Result {
  146. s := d.SpecValidator
  147. response, res := responseHelp.expandResponseRef(resp, path, s)
  148. if !res.IsValid() {
  149. return res
  150. }
  151. responseName, responseCodeAsStr := responseHelp.responseMsgVariants(responseType, responseCode)
  152. // nolint: dupl
  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, SwaggerSchema(true)).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. // TODO: Temporary duplicated code. Need to refactor with examples
  236. // nolint: dupl
  237. func (d *defaultValidator) validateDefaultValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result {
  238. res := new(Result)
  239. s := d.SpecValidator
  240. if items != nil {
  241. if items.Default != nil {
  242. res.Merge(newItemsValidator(path, in, items, root, s.KnownFormats).Validate(0, items.Default))
  243. }
  244. if items.Items != nil {
  245. res.Merge(d.validateDefaultValueItemsAgainstSchema(path+"[0].default", in, root, items.Items))
  246. }
  247. if _, err := compileRegexp(items.Pattern); err != nil {
  248. res.AddErrors(invalidPatternInMsg(path, in, items.Pattern))
  249. }
  250. }
  251. return res
  252. }