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