podman

Форк
0
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

15
package validate
16

17
import (
18
	"fmt"
19

20
	"github.com/go-openapi/spec"
21
)
22

23
// ExampleValidator validates example values defined in a spec
24
type exampleValidator struct {
25
	SpecValidator  *SpecValidator
26
	visitedSchemas map[string]bool
27
}
28

29
// resetVisited resets the internal state of visited schemas
30
func (ex *exampleValidator) resetVisited() {
31
	ex.visitedSchemas = map[string]bool{}
32
}
33

34
// beingVisited asserts a schema is being visited
35
func (ex *exampleValidator) beingVisited(path string) {
36
	ex.visitedSchemas[path] = true
37
}
38

39
// isVisited tells if a path has already been visited
40
func (ex *exampleValidator) isVisited(path string) bool {
41
	return 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
//
52
func (ex *exampleValidator) Validate() (errs *Result) {
53
	errs = new(Result)
54
	if ex == nil || ex.SpecValidator == nil {
55
		return errs
56
	}
57
	ex.resetVisited()
58
	errs.Merge(ex.validateExampleValueValidAgainstSchema()) // error -
59

60
	return errs
61
}
62

63
func (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

68
	res := new(Result)
69
	s := ex.SpecValidator
70

71
	for method, pathItem := range s.expandedAnalyzer().Operations() {
72
		for path, op := range pathItem {
73
			// parameters
74
			for _, 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
80
				ex.resetVisited()
81

82
				// Check simple parameters first
83
				// default values provided must validate against their inline definition (no explicit schema)
84
				if param.Example != nil && param.Schema == nil {
85
					// check param default value is valid
86
					red := NewParamValidator(&param, s.KnownFormats).Validate(param.Example) //#nosec
87
					if red.HasErrorsOrWarnings() {
88
						res.AddWarnings(exampleValueDoesNotValidateMsg(param.Name, param.In))
89
						res.MergeAsWarnings(red)
90
					}
91
				}
92

93
				// Recursively follows Items and Schemas
94
				if param.Items != nil {
95
					red := ex.validateExampleValueItemsAgainstSchema(param.Name, param.In, &param, param.Items) //#nosec
96
					if red.HasErrorsOrWarnings() {
97
						res.AddWarnings(exampleValueItemsDoesNotValidateMsg(param.Name, param.In))
98
						res.Merge(red)
99
					}
100
				}
101

102
				if param.Schema != nil {
103
					// Validate example value against schema
104
					red := ex.validateExampleValueSchemaAgainstSchema(param.Name, param.In, param.Schema)
105
					if red.HasErrorsOrWarnings() {
106
						res.AddWarnings(exampleValueDoesNotValidateMsg(param.Name, param.In))
107
						res.Merge(red)
108
					}
109
				}
110
			}
111

112
			if op.Responses != nil {
113
				if op.Responses.Default != nil {
114
					// Same constraint on default Response
115
					res.Merge(ex.validateExampleInResponse(op.Responses.Default, jsonDefault, path, 0, op.ID))
116
				}
117
				// Same constraint on regular Responses
118
				if op.Responses.StatusCodeResponses != nil { // Safeguard
119
					for code, r := range op.Responses.StatusCodeResponses {
120
						res.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
125
				res.AddErrors(noValidResponseMsg(op.ID))
126
			}
127
		}
128
	}
129
	if s.spec.Spec().Definitions != nil { // Safeguard
130
		// reset explored schemas to get depth-first recursive-proof exploration
131
		ex.resetVisited()
132
		for nm, sch := range s.spec.Spec().Definitions {
133
			res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("definitions.%s", nm), "body", &sch)) //#nosec
134
		}
135
	}
136
	return res
137
}
138

139
func (ex *exampleValidator) validateExampleInResponse(resp *spec.Response, responseType, path string, responseCode int, operationID string) *Result {
140
	s := ex.SpecValidator
141

142
	response, res := responseHelp.expandResponseRef(resp, path, s)
143
	if !res.IsValid() { // Safeguard
144
		return res
145
	}
146

147
	responseName, responseCodeAsStr := responseHelp.responseMsgVariants(responseType, responseCode)
148

149
	// nolint: dupl
150
	if response.Headers != nil { // Safeguard
151
		for nm, h := range response.Headers {
152
			// reset explored schemas to get depth-first recursive-proof exploration
153
			ex.resetVisited()
154

155
			if h.Example != nil {
156
				red := NewHeaderValidator(nm, &h, s.KnownFormats).Validate(h.Example) //#nosec
157
				if red.HasErrorsOrWarnings() {
158
					res.AddWarnings(exampleValueHeaderDoesNotValidateMsg(operationID, nm, responseName))
159
					res.MergeAsWarnings(red)
160
				}
161
			}
162

163
			// Headers have inline definition, like params
164
			if h.Items != nil {
165
				red := ex.validateExampleValueItemsAgainstSchema(nm, "header", &h, h.Items) //#nosec
166
				if red.HasErrorsOrWarnings() {
167
					res.AddWarnings(exampleValueHeaderItemsDoesNotValidateMsg(operationID, nm, responseName))
168
					res.MergeAsWarnings(red)
169
				}
170
			}
171

172
			if _, err := compileRegexp(h.Pattern); err != nil {
173
				res.AddErrors(invalidPatternInHeaderMsg(operationID, nm, responseName, h.Pattern, err))
174
			}
175

176
			// Headers don't have schema
177
		}
178
	}
179
	if response.Schema != nil {
180
		// reset explored schemas to get depth-first recursive-proof exploration
181
		ex.resetVisited()
182

183
		red := ex.validateExampleValueSchemaAgainstSchema(responseCodeAsStr, "response", response.Schema)
184
		if red.HasErrorsOrWarnings() {
185
			// Additional message to make sure the context of the error is not lost
186
			res.AddWarnings(exampleValueInDoesNotValidateMsg(operationID, responseName))
187
			res.Merge(red)
188
		}
189
	}
190

191
	if response.Examples != nil {
192
		if response.Schema != nil {
193
			if example, ok := response.Examples["application/json"]; ok {
194
				res.MergeAsWarnings(NewSchemaValidator(response.Schema, s.spec.Spec(), path+".examples", s.KnownFormats, SwaggerSchema(true)).Validate(example))
195
			} else {
196
				// TODO: validate other media types too
197
				res.AddWarnings(examplesMimeNotSupportedMsg(operationID, responseName))
198
			}
199
		} else {
200
			res.AddWarnings(examplesWithoutSchemaMsg(operationID, responseName))
201
		}
202
	}
203
	return res
204
}
205

206
func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in string, schema *spec.Schema) *Result {
207
	if schema == nil || ex.isVisited(path) {
208
		// Avoids recursing if we are already done with that check
209
		return nil
210
	}
211
	ex.beingVisited(path)
212
	s := ex.SpecValidator
213
	res := new(Result)
214

215
	if schema.Example != nil {
216
		res.MergeAsWarnings(NewSchemaValidator(schema, s.spec.Spec(), path+".example", s.KnownFormats, SwaggerSchema(true)).Validate(schema.Example))
217
	}
218
	if schema.Items != nil {
219
		if schema.Items.Schema != nil {
220
			res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+".items.example", in, schema.Items.Schema))
221
		}
222
		// Multiple schemas in items
223
		if schema.Items.Schemas != nil { // Safeguard
224
			for i, sch := range schema.Items.Schemas {
225
				res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("%s.items[%d].example", path, i), in, &sch)) //#nosec
226
			}
227
		}
228
	}
229
	if _, err := compileRegexp(schema.Pattern); err != nil {
230
		res.AddErrors(invalidPatternInMsg(path, in, schema.Pattern))
231
	}
232
	if 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)
234
		res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalItems", path), in, schema.AdditionalItems.Schema))
235
	}
236
	for propName, prop := range schema.Properties {
237
		res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+"."+propName, in, &prop)) //#nosec
238
	}
239
	for propName, prop := range schema.PatternProperties {
240
		res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+"."+propName, in, &prop)) //#nosec
241
	}
242
	if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
243
		res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalProperties", path), in, schema.AdditionalProperties.Schema))
244
	}
245
	if schema.AllOf != nil {
246
		for i, aoSch := range schema.AllOf {
247
			res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("%s.allOf[%d]", path, i), in, &aoSch)) //#nosec
248
		}
249
	}
250
	return res
251
}
252

253
// TODO: Temporary duplicated code. Need to refactor with examples
254
// nolint: dupl
255
func (ex *exampleValidator) validateExampleValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result {
256
	res := new(Result)
257
	s := ex.SpecValidator
258
	if items != nil {
259
		if items.Example != nil {
260
			res.MergeAsWarnings(newItemsValidator(path, in, items, root, s.KnownFormats).Validate(0, items.Example))
261
		}
262
		if items.Items != nil {
263
			res.Merge(ex.validateExampleValueItemsAgainstSchema(path+"[0].example", in, root, items.Items))
264
		}
265
		if _, err := compileRegexp(items.Pattern); err != nil {
266
			res.AddErrors(invalidPatternInMsg(path, in, items.Pattern))
267
		}
268
	}
269
	return res
270
}
271

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.