/
validate_request.go
394 lines (355 loc) · 11.5 KB
/
validate_request.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package openapi3filter
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"sort"
"github.com/getkin/kin-openapi/openapi3"
)
// ErrAuthenticationServiceMissing is returned when no authentication service
// is defined for the request validator
var ErrAuthenticationServiceMissing = errors.New("missing AuthenticationFunc")
// ErrInvalidRequired is returned when a required value of a parameter or request body is not defined.
var ErrInvalidRequired = errors.New("value is required but missing")
// ErrInvalidEmptyValue is returned when a value of a parameter or request body is empty while it's not allowed.
var ErrInvalidEmptyValue = errors.New("empty value is not allowed")
// ValidateRequest is used to validate the given input according to previous
// loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a
// non-nil error will be returned.
//
// Note: One can tune the behavior of uniqueItems: true verification
// by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker
func ValidateRequest(ctx context.Context, input *RequestValidationInput) (err error) {
var me openapi3.MultiError
options := input.Options
if options == nil {
options = DefaultOptions
}
route := input.Route
operation := route.Operation
operationParameters := operation.Parameters
pathItemParameters := route.PathItem.Parameters
// Security
security := operation.Security
// If there aren't any security requirements for the operation
if security == nil {
// Use the global security requirements.
security = &route.Spec.Security
}
if security != nil {
if err = ValidateSecurityRequirements(ctx, input, *security); err != nil && !options.MultiError {
return
}
if err != nil {
me = append(me, err)
}
}
// For each parameter of the PathItem
for _, parameterRef := range pathItemParameters {
parameter := parameterRef.Value
if operationParameters != nil {
if override := operationParameters.GetByInAndName(parameter.In, parameter.Name); override != nil {
continue
}
}
if err = ValidateParameter(ctx, input, parameter); err != nil && !options.MultiError {
return
}
if err != nil {
me = append(me, err)
}
}
// For each parameter of the Operation
for _, parameter := range operationParameters {
if err = ValidateParameter(ctx, input, parameter.Value); err != nil && !options.MultiError {
return
}
if err != nil {
me = append(me, err)
}
}
// RequestBody
requestBody := operation.RequestBody
if requestBody != nil && !options.ExcludeRequestBody {
if err = ValidateRequestBody(ctx, input, requestBody.Value); err != nil && !options.MultiError {
return
}
if err != nil {
me = append(me, err)
}
}
if len(me) > 0 {
return me
}
return
}
// ValidateParameter validates a parameter's value by JSON schema.
// The function returns RequestError with a ParseError cause when unable to parse a value.
// The function returns RequestError with ErrInvalidRequired cause when a value of a required parameter is not defined.
// The function returns RequestError with ErrInvalidEmptyValue cause when a value of a required parameter is not defined.
// The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema.
func ValidateParameter(ctx context.Context, input *RequestValidationInput, parameter *openapi3.Parameter) error {
if parameter.Schema == nil && parameter.Content == nil {
// We have no schema for the parameter. Assume that everything passes
// a schema-less check, but this could also be an error. The OpenAPI
// validation allows this to happen.
return nil
}
options := input.Options
if options == nil {
options = DefaultOptions
}
var value interface{}
var err error
var found bool
var schema *openapi3.Schema
// Validation will ensure that we either have content or schema.
if parameter.Content != nil {
if value, schema, found, err = decodeContentParameter(parameter, input); err != nil {
return &RequestError{Input: input, Parameter: parameter, Err: err}
}
} else {
if value, found, err = decodeStyledParameter(parameter, input); err != nil {
return &RequestError{Input: input, Parameter: parameter, Err: err}
}
schema = parameter.Schema.Value
}
// Set default value if needed
if !options.SkipSettingDefaults && value == nil && schema != nil && schema.Default != nil {
value = schema.Default
req := input.Request
switch parameter.In {
case openapi3.ParameterInPath:
// Path parameters are required.
// Next check `parameter.Required && !found` will catch this.
case openapi3.ParameterInQuery:
q := req.URL.Query()
q.Add(parameter.Name, fmt.Sprintf("%v", value))
req.URL.RawQuery = q.Encode()
case openapi3.ParameterInHeader:
req.Header.Add(parameter.Name, fmt.Sprintf("%v", value))
case openapi3.ParameterInCookie:
req.AddCookie(&http.Cookie{
Name: parameter.Name,
Value: fmt.Sprintf("%v", value),
})
}
}
// Validate a parameter's value and presence.
if parameter.Required && !found {
return &RequestError{Input: input, Parameter: parameter, Reason: ErrInvalidRequired.Error(), Err: ErrInvalidRequired}
}
if isNilValue(value) {
if !parameter.AllowEmptyValue && found {
return &RequestError{Input: input, Parameter: parameter, Reason: ErrInvalidEmptyValue.Error(), Err: ErrInvalidEmptyValue}
}
return nil
}
if schema == nil {
// A parameter's schema is not defined so skip validation of a parameter's value.
return nil
}
var opts []openapi3.SchemaValidationOption
if options.MultiError {
opts = make([]openapi3.SchemaValidationOption, 0, 1)
opts = append(opts, openapi3.MultiErrors())
}
if options.customSchemaErrorFunc != nil {
opts = append(opts, openapi3.SetSchemaErrorMessageCustomizer(options.customSchemaErrorFunc))
}
if err = schema.VisitJSON(value, opts...); err != nil {
return &RequestError{Input: input, Parameter: parameter, Err: err}
}
return nil
}
const prefixInvalidCT = "header Content-Type has unexpected value"
// ValidateRequestBody validates data of a request's body.
//
// The function returns RequestError with ErrInvalidRequired cause when a value is required but not defined.
// The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema.
func ValidateRequestBody(ctx context.Context, input *RequestValidationInput, requestBody *openapi3.RequestBody) error {
var (
req = input.Request
data []byte
)
options := input.Options
if options == nil {
options = DefaultOptions
}
if req.Body != http.NoBody && req.Body != nil {
defer req.Body.Close()
var err error
if data, err = ioutil.ReadAll(req.Body); err != nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "reading failed",
Err: err,
}
}
// Put the data back into the input
req.Body = nil
if req.GetBody != nil {
if req.Body, err = req.GetBody(); err != nil {
req.Body = nil
}
}
if req.Body == nil {
req.ContentLength = int64(len(data))
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(data)), nil
}
req.Body, _ = req.GetBody() // no error return
}
}
if len(data) == 0 {
if requestBody.Required {
return &RequestError{Input: input, RequestBody: requestBody, Err: ErrInvalidRequired}
}
return nil
}
content := requestBody.Content
if len(content) == 0 {
// A request's body does not have declared content, so skip validation.
return nil
}
inputMIME := req.Header.Get(headerCT)
contentType := requestBody.Content.Get(inputMIME)
if contentType == nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: fmt.Sprintf("%s %q", prefixInvalidCT, inputMIME),
}
}
if contentType.Schema == nil {
// A JSON schema that describes the received data is not declared, so skip validation.
return nil
}
encFn := func(name string) *openapi3.Encoding { return contentType.Encoding[name] }
mediaType, value, err := decodeBody(bytes.NewReader(data), req.Header, contentType.Schema, encFn)
if err != nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "failed to decode request body",
Err: err,
}
}
defaultsSet := false
opts := make([]openapi3.SchemaValidationOption, 0, 3) // 3 potential opts here
opts = append(opts, openapi3.VisitAsRequest())
if !options.SkipSettingDefaults {
opts = append(opts, openapi3.DefaultsSet(func() { defaultsSet = true }))
}
if options.MultiError {
opts = append(opts, openapi3.MultiErrors())
}
if options.customSchemaErrorFunc != nil {
opts = append(opts, openapi3.SetSchemaErrorMessageCustomizer(options.customSchemaErrorFunc))
}
// Validate JSON with the schema
if err := contentType.Schema.Value.VisitJSON(value, opts...); err != nil {
schemaId := getSchemaIdentifier(contentType.Schema)
schemaId = prependSpaceIfNeeded(schemaId)
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: fmt.Sprintf("doesn't match schema%s", schemaId),
Err: err,
}
}
if defaultsSet {
var err error
if data, err = encodeBody(value, mediaType); err != nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "rewriting failed",
Err: err,
}
}
// Put the data back into the input
if req.Body != nil {
req.Body.Close()
}
req.ContentLength = int64(len(data))
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(data)), nil
}
req.Body, _ = req.GetBody() // no error return
}
return nil
}
// ValidateSecurityRequirements goes through multiple OpenAPI 3 security
// requirements in order and returns nil on the first valid requirement.
// If no requirement is met, errors are returned in order.
func ValidateSecurityRequirements(ctx context.Context, input *RequestValidationInput, srs openapi3.SecurityRequirements) error {
if len(srs) == 0 {
return nil
}
var errs []error
for _, sr := range srs {
if err := validateSecurityRequirement(ctx, input, sr); err != nil {
if len(errs) == 0 {
errs = make([]error, 0, len(srs))
}
errs = append(errs, err)
continue
}
return nil
}
return &SecurityRequirementsError{
SecurityRequirements: srs,
Errors: errs,
}
}
// validateSecurityRequirement validates a single OpenAPI 3 security requirement
func validateSecurityRequirement(ctx context.Context, input *RequestValidationInput, securityRequirement openapi3.SecurityRequirement) error {
doc := input.Route.Spec
securitySchemes := doc.Components.SecuritySchemes
// Ensure deterministic order
names := make([]string, 0, len(securityRequirement))
for name := range securityRequirement {
names = append(names, name)
}
sort.Strings(names)
// Get authentication function
options := input.Options
if options == nil {
options = DefaultOptions
}
f := options.AuthenticationFunc
if f == nil {
return ErrAuthenticationServiceMissing
}
// For each scheme for the requirement
for _, name := range names {
var securityScheme *openapi3.SecurityScheme
if securitySchemes != nil {
if ref := securitySchemes[name]; ref != nil {
securityScheme = ref.Value
}
}
if securityScheme == nil {
return &RequestError{
Input: input,
Err: fmt.Errorf("security scheme %q is not declared", name),
}
}
scopes := securityRequirement[name]
if err := f(ctx, &AuthenticationInput{
RequestValidationInput: input,
SecuritySchemeName: name,
SecurityScheme: securityScheme,
Scopes: scopes,
}); err != nil {
return err
}
}
return nil
}