forked from pb33f/libopenapi-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_request.go
More file actions
365 lines (324 loc) · 12.2 KB
/
Copy pathvalidate_request.go
File metadata and controls
365 lines (324 loc) · 12.2 KB
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
// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
// SPDX-License-Identifier: MIT
package requests
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"regexp"
"strconv"
"github.com/pb33f/libopenapi/datamodel/high/base"
"github.com/pb33f/libopenapi/utils"
"github.com/santhosh-tekuri/jsonschema/v6"
"go.yaml.in/yaml/v4"
"golang.org/x/text/language"
"golang.org/x/text/message"
"github.com/pb33f/libopenapi-validator/cache"
"github.com/pb33f/libopenapi-validator/config"
"github.com/pb33f/libopenapi-validator/errors"
"github.com/pb33f/libopenapi-validator/helpers"
"github.com/pb33f/libopenapi-validator/schema_validation"
"github.com/pb33f/libopenapi-validator/strict"
)
var instanceLocationRegex = regexp.MustCompile(`^/(\d+)`)
// ValidateRequestSchemaInput contains parameters for request schema validation.
type ValidateRequestSchemaInput struct {
Request *http.Request // Required: The HTTP request to validate
Schema *base.Schema // Required: The OpenAPI schema to validate against
Version float32 // Required: OpenAPI version (3.0 or 3.1)
Options []config.Option // Optional: Functional options (defaults applied if empty/nil)
BodyRequired bool // Optional: Whether the request body is required (default false)
}
// ValidateRequestSchema will validate a http.Request pointer against a schema.
// If validation fails, it will return a list of validation errors as the second return value.
// The schema will be stored and reused from cache if available, otherwise it will be compiled on each call.
func ValidateRequestSchema(input *ValidateRequestSchemaInput) (bool, []*errors.ValidationError) {
validationOptions := config.NewValidationOptions(input.Options...)
var validationErrors []*errors.ValidationError
var renderedSchema, jsonSchema []byte
var referenceSchema string
var compiledSchema *jsonschema.Schema
var cachedNode *yaml.Node
if input.Schema == nil {
return false, []*errors.ValidationError{{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: "schema is nil",
Reason: "The schema to validate against is nil",
}}
} else if input.Schema.GoLow() == nil {
return false, []*errors.ValidationError{{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: "schema cannot be rendered",
Reason: "The schema does not have low-level information and cannot be rendered. Please ensure the schema is loaded from a document.",
}}
}
if validationOptions.SchemaCache != nil {
hash := input.Schema.GoLow().Hash()
if cached, ok := validationOptions.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil {
renderedSchema = cached.RenderedInline
referenceSchema = cached.ReferenceSchema
jsonSchema = cached.RenderedJSON
compiledSchema = cached.CompiledSchema
cachedNode = cached.RenderedNode
}
}
// Cache miss or no cache - render and compile
if compiledSchema == nil {
renderCtx := base.NewInlineRenderContextForValidation()
var renderErr error
renderedSchema, renderErr = input.Schema.RenderInlineWithContext(renderCtx)
referenceSchema = string(renderedSchema)
// If rendering failed (e.g., circular reference), return the render error
if renderErr != nil {
violation := &errors.SchemaValidationFailure{
Reason: renderErr.Error(),
ReferenceSchema: referenceSchema,
}
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: fmt.Sprintf("%s request body for '%s' failed schema rendering",
input.Request.Method, input.Request.URL.Path),
Reason: fmt.Sprintf("The request schema failed to render: %s",
renderErr.Error()),
SpecLine: 1,
SpecCol: 0,
SchemaValidationErrors: []*errors.SchemaValidationFailure{violation},
HowToFix: errors.HowToFixInvalidRenderedSchema,
Context: referenceSchema,
})
return false, validationErrors
}
jsonSchema, _ = utils.ConvertYAMLtoJSON(renderedSchema)
var err error
schemaName := fmt.Sprintf("%x", input.Schema.GoLow().Hash())
compiledSchema, err = helpers.NewCompiledSchemaWithVersion(
schemaName,
jsonSchema,
validationOptions,
input.Version,
)
if err != nil {
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: fmt.Sprintf("%s request body for '%s' failed schema compilation",
input.Request.Method, input.Request.URL.Path),
Reason: fmt.Sprintf("The request schema failed to compile: %s", err.Error()),
SpecLine: 1,
SpecCol: 0,
HowToFix: "check the request schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs",
Context: input.Schema,
})
return false, validationErrors
}
if validationOptions.SchemaCache != nil {
hash := input.Schema.GoLow().Hash()
validationOptions.SchemaCache.Store(hash, &cache.SchemaCacheEntry{
Schema: input.Schema,
RenderedInline: renderedSchema,
ReferenceSchema: referenceSchema,
RenderedJSON: jsonSchema,
CompiledSchema: compiledSchema,
})
}
}
request := input.Request
schema := input.Schema
var requestBody []byte
if request != nil && request.Body != nil {
requestBody, _ = io.ReadAll(request.Body)
// close the request body, so it can be re-read later by another player in the chain
_ = request.Body.Close()
request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
}
var decodedObj interface{}
if len(requestBody) > 0 {
err := json.Unmarshal(requestBody, &decodedObj)
if err != nil {
// cannot decode the request body, so it's not valid
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: fmt.Sprintf("%s request body for '%s' failed to validate schema",
request.Method, request.URL.Path),
Reason: fmt.Sprintf("The request body cannot be decoded: %s", err.Error()),
SpecLine: 1,
SpecCol: 0,
HowToFix: errors.HowToFixInvalidSchema,
Context: schema,
})
return false, validationErrors
}
}
// no request body? but we do have a schema?
if len(requestBody) == 0 && len(jsonSchema) > 0 {
if !input.BodyRequired {
return true, nil
}
line := 1
col := 0
if schema.ParentProxy != nil {
if keyNode := schema.ParentProxy.GetSchemaKeyNode(); keyNode != nil {
line = keyNode.Line
col = keyNode.Column
}
}
if schema.Type != nil {
if low := schema.GoLow(); low != nil && low.Type.KeyNode != nil {
line = low.Type.KeyNode.Line
col = low.Type.KeyNode.Column
}
}
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: fmt.Sprintf("%s request body is empty for '%s'",
request.Method, request.URL.Path),
Reason: "The request body is empty but there is a schema defined",
SpecLine: line,
SpecCol: col,
HowToFix: errors.HowToFixInvalidSchema,
Context: schema,
})
return false, validationErrors
}
// validate the object against the schema
scErrs := compiledSchema.Validate(decodedObj)
if scErrs != nil {
jk := scErrs.(*jsonschema.ValidationError)
// flatten the validationErrors
schFlatErrs := jk.BasicOutput().Errors
var schemaValidationErrors []*errors.SchemaValidationFailure
// Use cached node if available, otherwise parse
renderedNode := cachedNode
if renderedNode == nil {
renderedNode = new(yaml.Node)
_ = yaml.Unmarshal(renderedSchema, renderedNode)
}
for q := range schFlatErrs {
er := schFlatErrs[q]
errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{}))
if er.KeywordLocation == "" || helpers.IgnoreRegex.MatchString(errMsg) {
continue // ignore this error, it's useless tbh, utter noise.
}
if er.Error != nil {
// locate the violated property in the schema
var located *yaml.Node
if len(renderedNode.Content) > 0 {
located = schema_validation.LocateSchemaPropertyNodeByJSONPath(renderedNode.Content[0], er.KeywordLocation)
}
// extract the element specified by the instance
val := instanceLocationRegex.FindStringSubmatch(er.InstanceLocation)
var referenceObject string
if len(val) > 0 {
referenceIndex, _ := strconv.Atoi(val[1])
if reflect.ValueOf(decodedObj).Type().Kind() == reflect.Slice {
found := decodedObj.([]any)[referenceIndex]
recoded, _ := json.MarshalIndent(found, "", " ")
referenceObject = string(recoded)
}
}
if referenceObject == "" {
referenceObject = string(requestBody)
}
errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{}))
violation := &errors.SchemaValidationFailure{
Reason: errMsg,
FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation),
FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation),
InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation),
KeywordLocation: er.KeywordLocation,
ReferenceSchema: referenceSchema,
ReferenceObject: referenceObject,
OriginalJsonSchemaError: jk,
}
// if we have a location within the schema, add it to the error
if located != nil {
line := located.Line
// if the located node is a map or an array, then the actual human interpretable
// line on which the violation occurred is the line of the key, not the value.
if located.Kind == yaml.MappingNode || located.Kind == yaml.SequenceNode {
if line > 0 {
line--
}
}
// location of the violation within the rendered schema.
violation.Line = line
violation.Column = located.Column
}
schemaValidationErrors = append(schemaValidationErrors, violation)
}
}
line := 1
col := 0
if low := schema.GoLow(); low != nil && low.Type.KeyNode != nil {
line = low.Type.KeyNode.Line
col = low.Type.KeyNode.Column
}
// add the error to the list
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: helpers.RequestBodyValidation,
ValidationSubType: helpers.Schema,
Message: fmt.Sprintf("%s request body for '%s' failed to validate schema",
request.Method, request.URL.Path),
Reason: "The request body is defined as an object. " +
"However, it does not meet the schema requirements of the specification",
SpecLine: line,
SpecCol: col,
SchemaValidationErrors: schemaValidationErrors,
HowToFix: errors.HowToFixInvalidSchema,
Context: schema,
})
}
if len(validationErrors) > 0 {
return false, validationErrors
}
// strict mode: check for undeclared properties in request body
if validationOptions.StrictMode && decodedObj != nil {
strictValidator := strict.NewValidator(validationOptions, input.Version)
strictResult := strictValidator.Validate(strict.Input{
Schema: schema,
Data: decodedObj,
Direction: strict.DirectionRequest,
Options: validationOptions,
BasePath: "$.body",
Version: input.Version,
})
if !strictResult.Valid {
for _, undeclared := range strictResult.UndeclaredValues {
switch undeclared.Type {
case strict.TypeReadOnlyProperty:
validationErrors = append(validationErrors,
errors.ReadOnlyPropertyError(
undeclared.Path, undeclared.Name, undeclared.Value,
request.URL.Path, request.Method,
undeclared.SpecLine, undeclared.SpecCol,
))
default:
validationErrors = append(validationErrors,
errors.UndeclaredPropertyError(
undeclared.Path,
undeclared.Name,
undeclared.Value,
undeclared.DeclaredProperties,
undeclared.Direction.String(),
request.URL.Path,
request.Method,
undeclared.SpecLine,
undeclared.SpecCol,
))
}
}
}
}
if len(validationErrors) > 0 {
return false, validationErrors
}
return true, nil
}