forked from pb33f/libopenapi-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
341 lines (282 loc) · 11.8 KB
/
validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package validator
import (
"net/http"
"sync"
"github.com/pb33f/libopenapi"
v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
"github.com/pb33f/libopenapi-validator/errors"
"github.com/pb33f/libopenapi-validator/parameters"
"github.com/pb33f/libopenapi-validator/paths"
"github.com/pb33f/libopenapi-validator/requests"
"github.com/pb33f/libopenapi-validator/responses"
"github.com/pb33f/libopenapi-validator/schema_validation"
)
// Validator provides a coarse grained interface for validating an OpenAPI 3+ documents.
// There are three primary use-cases for validation
//
// Validating *http.Request objects against and OpenAPI 3+ document
// Validating *http.Response objects against an OpenAPI 3+ document
// Validating an OpenAPI 3+ document against the OpenAPI 3+ specification
type Validator interface {
// ValidateHttpRequest will validate an *http.Request object against an OpenAPI 3+ document.
// The path, query, cookie and header parameters and request body are validated.
ValidateHttpRequest(request *http.Request) (bool, []*errors.ValidationError)
// ValidateHttpRequestSync will validate an *http.Request object against an OpenAPI 3+ document syncronously and without spawning any goroutines.
// The path, query, cookie and header parameters and request body are validated.
ValidateHttpRequestSync(request *http.Request) (bool, []*errors.ValidationError)
// ValidateHttpRequestWithPathItem will validate an *http.Request object against an OpenAPI 3+ document.
// The path, query, cookie and header parameters and request body are validated.
ValidateHttpRequestWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError)
// ValidateHttpRequestSyncWithPathItem will validate an *http.Request object against an OpenAPI 3+ document syncronously and without spawning any goroutines.
// The path, query, cookie and header parameters and request body are validated.
ValidateHttpRequestSyncWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError)
// ValidateHttpResponse will an *http.Response object against an OpenAPI 3+ document.
// The response body is validated. The request is only used to extract the correct reponse from the spec.
ValidateHttpResponse(request *http.Request, response *http.Response) (bool, []*errors.ValidationError)
// ValidateHttpRequestResponse will validate both the *http.Request and *http.Response objects against an OpenAPI 3+ document.
// The path, query, cookie and header parameters and request and response body are validated.
ValidateHttpRequestResponse(request *http.Request, response *http.Response) (bool, []*errors.ValidationError)
// ValidateDocument will validate an OpenAPI 3+ document against the 3.0 or 3.1 OpenAPI 3+ specification
ValidateDocument() (bool, []*errors.ValidationError)
// GetParameterValidator will return a parameters.ParameterValidator instance used to validate parameters
GetParameterValidator() parameters.ParameterValidator
// GetRequestBodyValidator will return a parameters.RequestBodyValidator instance used to validate request bodies
GetRequestBodyValidator() requests.RequestBodyValidator
// GetResponseBodyValidator will return a parameters.ResponseBodyValidator instance used to validate response bodies
GetResponseBodyValidator() responses.ResponseBodyValidator
}
// NewValidator will create a new Validator from an OpenAPI 3+ document
func NewValidator(document libopenapi.Document) (Validator, []error) {
m, errs := document.BuildV3Model()
if errs != nil {
return nil, errs
}
v := NewValidatorFromV3Model(&m.Model)
v.(*validator).document = document
return v, nil
}
// NewValidatorFromV3Model will create a new Validator from an OpenAPI Model
func NewValidatorFromV3Model(m *v3.Document) Validator {
// create a new parameter validator
paramValidator := parameters.NewParameterValidator(m)
// create a new request body validator
reqBodyValidator := requests.NewRequestBodyValidator(m)
// create a response body validator
respBodyValidator := responses.NewResponseBodyValidator(m)
return &validator{
v3Model: m,
requestValidator: reqBodyValidator,
responseValidator: respBodyValidator,
paramValidator: paramValidator,
}
}
func (v *validator) GetParameterValidator() parameters.ParameterValidator {
return v.paramValidator
}
func (v *validator) GetRequestBodyValidator() requests.RequestBodyValidator {
return v.requestValidator
}
func (v *validator) GetResponseBodyValidator() responses.ResponseBodyValidator {
return v.responseValidator
}
func (v *validator) ValidateDocument() (bool, []*errors.ValidationError) {
return schema_validation.ValidateOpenAPIDocument(v.document)
}
func (v *validator) ValidateHttpResponse(
request *http.Request,
response *http.Response,
) (bool, []*errors.ValidationError) {
var pathItem *v3.PathItem
var pathValue string
var errs []*errors.ValidationError
pathItem, errs, pathValue = paths.FindPath(request, v.v3Model)
if pathItem == nil || errs != nil {
return false, errs
}
responseBodyValidator := v.responseValidator
// validate response
_, responseErrors := responseBodyValidator.ValidateResponseBodyWithPathItem(request, response, pathItem, pathValue)
if len(responseErrors) > 0 {
return false, responseErrors
}
return true, nil
}
func (v *validator) ValidateHttpRequestResponse(
request *http.Request,
response *http.Response,
) (bool, []*errors.ValidationError) {
var pathItem *v3.PathItem
var pathValue string
var errs []*errors.ValidationError
pathItem, errs, pathValue = paths.FindPath(request, v.v3Model)
if pathItem == nil || errs != nil {
return false, errs
}
responseBodyValidator := v.responseValidator
// validate request and response
_, requestErrors := v.ValidateHttpRequestWithPathItem(request, pathItem, pathValue)
_, responseErrors := responseBodyValidator.ValidateResponseBodyWithPathItem(request, response, pathItem, pathValue)
if len(requestErrors) > 0 || len(responseErrors) > 0 {
return false, append(requestErrors, responseErrors...)
}
return true, nil
}
func (v *validator) ValidateHttpRequest(request *http.Request) (bool, []*errors.ValidationError) {
pathItem, errs, foundPath := paths.FindPath(request, v.v3Model)
if len(errs) > 0 {
return false, errs
}
return v.ValidateHttpRequestWithPathItem(request, pathItem, foundPath)
}
func (v *validator) ValidateHttpRequestWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) {
// create a new parameter validator
paramValidator := v.paramValidator
// create a new request body validator
reqBodyValidator := v.requestValidator
// create some channels to handle async validation
doneChan := make(chan struct{})
errChan := make(chan []*errors.ValidationError)
controlChan := make(chan struct{})
// async param validation function.
parameterValidationFunc := func(control chan struct{}, errorChan chan []*errors.ValidationError) {
paramErrs := make(chan []*errors.ValidationError)
paramControlChan := make(chan struct{})
paramFunctionControlChan := make(chan struct{})
var paramValidationErrors []*errors.ValidationError
validations := []validationFunction{
paramValidator.ValidatePathParamsWithPathItem,
paramValidator.ValidateCookieParamsWithPathItem,
paramValidator.ValidateHeaderParamsWithPathItem,
paramValidator.ValidateQueryParamsWithPathItem,
paramValidator.ValidateSecurityWithPathItem,
}
// listen for validation errors on parameters. everything will run async.
paramListener := func(control chan struct{}, errorChan chan []*errors.ValidationError) {
completedValidations := 0
for {
select {
case vErrs := <-errorChan:
paramValidationErrors = append(paramValidationErrors, vErrs...)
case <-control:
completedValidations++
if completedValidations == len(validations) {
paramFunctionControlChan <- struct{}{}
return
}
}
}
}
validateParamFunction := func(
control chan struct{},
errorChan chan []*errors.ValidationError,
validatorFunc validationFunction,
) {
valid, pErrs := validatorFunc(request, pathItem, pathValue)
if !valid {
errorChan <- pErrs
}
control <- struct{}{}
}
go paramListener(paramControlChan, paramErrs)
for i := range validations {
go validateParamFunction(paramControlChan, paramErrs, validations[i])
}
// wait for all the validations to complete
<-paramFunctionControlChan
if len(paramValidationErrors) > 0 {
errorChan <- paramValidationErrors
}
// let runValidation know we are done with this part.
controlChan <- struct{}{}
}
requestBodyValidationFunc := func(control chan struct{}, errorChan chan []*errors.ValidationError) {
valid, pErrs := reqBodyValidator.ValidateRequestBodyWithPathItem(request, pathItem, pathValue)
if !valid {
errorChan <- pErrs
}
control <- struct{}{}
}
// build async functions
asyncFunctions := []validationFunctionAsync{
parameterValidationFunc,
requestBodyValidationFunc,
}
var validationErrors []*errors.ValidationError
// sit and wait for everything to report back.
go runValidation(controlChan, doneChan, errChan, &validationErrors, len(asyncFunctions))
// run async functions
for i := range asyncFunctions {
go asyncFunctions[i](controlChan, errChan)
}
// wait for all the validations to complete
<-doneChan
return !(len(validationErrors) > 0), validationErrors
}
func (v *validator) ValidateHttpRequestSync(request *http.Request) (bool, []*errors.ValidationError) {
pathItem, errs, foundPath := paths.FindPath(request, v.v3Model)
if len(errs) > 0 {
return false, errs
}
return v.ValidateHttpRequestSyncWithPathItem(request, pathItem, foundPath)
}
func (v *validator) ValidateHttpRequestSyncWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) {
// create a new parameter validator
paramValidator := v.paramValidator
// create a new request body validator
reqBodyValidator := v.requestValidator
validationErrors := make([]*errors.ValidationError, 0)
paramValidationErrors := make([]*errors.ValidationError, 0)
for _, validateFunc := range []validationFunction{
paramValidator.ValidatePathParamsWithPathItem,
paramValidator.ValidateCookieParamsWithPathItem,
paramValidator.ValidateHeaderParamsWithPathItem,
paramValidator.ValidateQueryParamsWithPathItem,
paramValidator.ValidateSecurityWithPathItem,
} {
valid, pErrs := validateFunc(request, pathItem, pathValue)
if !valid {
paramValidationErrors = append(paramValidationErrors, pErrs...)
}
}
valid, pErrs := reqBodyValidator.ValidateRequestBodyWithPathItem(request, pathItem, pathValue)
if !valid {
paramValidationErrors = append(paramValidationErrors, pErrs...)
}
validationErrors = append(validationErrors, paramValidationErrors...)
return !(len(validationErrors) > 0), validationErrors
}
type validator struct {
v3Model *v3.Document
document libopenapi.Document
paramValidator parameters.ParameterValidator
requestValidator requests.RequestBodyValidator
responseValidator responses.ResponseBodyValidator
}
func runValidation(control, doneChan chan struct{},
errorChan chan []*errors.ValidationError,
validationErrors *[]*errors.ValidationError,
total int,
) {
var validationLock sync.Mutex
completedValidations := 0
for {
select {
case vErrs := <-errorChan:
validationLock.Lock()
*validationErrors = append(*validationErrors, vErrs...)
validationLock.Unlock()
case <-control:
completedValidations++
if completedValidations == total {
doneChan <- struct{}{}
return
}
}
}
}
type (
validationFunction func(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError)
validationFunctionAsync func(control chan struct{}, errorChan chan []*errors.ValidationError)
)