-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathvalidate_parameter.go
More file actions
399 lines (360 loc) · 12.9 KB
/
validate_parameter.go
File metadata and controls
399 lines (360 loc) · 12.9 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
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
395
396
397
398
399
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package parameters
import (
"encoding/json"
"fmt"
"net/url"
"reflect"
"strings"
"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"
stdError "errors"
"github.com/pb33f/libopenapi-validator/cache"
"github.com/pb33f/libopenapi-validator/config"
"github.com/pb33f/libopenapi-validator/errors"
"github.com/pb33f/libopenapi-validator/helpers"
)
func ValidateSingleParameterSchema(
schema *base.Schema,
rawObject any,
entity string,
reasonEntity string,
name string,
validationType string,
subValType string,
o *config.ValidationOptions,
pathTemplate string,
operation string,
) (validationErrors []*errors.ValidationError) {
var jsch *jsonschema.Schema
var jsonSchema []byte
// Try cache lookup first - avoids expensive schema compilation on each request
if o != nil && o.SchemaCache != nil && schema != nil && schema.GoLow() != nil {
hash := schema.GoLow().Hash()
if cached, ok := o.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil {
jsch = cached.CompiledSchema
}
}
// Cache miss - compile the schema
if jsch == nil {
// Get the JSON Schema for the parameter definition.
var err error
jsonSchema, err = buildJsonRender(schema)
if err != nil {
return validationErrors
}
// Attempt to compile the JSON Schema
jsch, err = helpers.NewCompiledSchema(name, jsonSchema, o)
if err != nil {
return validationErrors
}
// Store in cache for future requests
if o != nil && o.SchemaCache != nil && schema != nil && schema.GoLow() != nil {
hash := schema.GoLow().Hash()
renderCtx := base.NewInlineRenderContextForValidation()
renderedInline, _ := schema.RenderInlineWithContext(renderCtx)
referenceSchema := string(renderedInline)
var renderedNode yaml.Node
_ = yaml.Unmarshal(renderedInline, &renderedNode)
o.SchemaCache.Store(hash, &cache.SchemaCacheEntry{
Schema: schema,
RenderedInline: renderedInline,
ReferenceSchema: referenceSchema,
RenderedJSON: jsonSchema,
CompiledSchema: jsch,
RenderedNode: &renderedNode,
})
}
}
// Validate the object and report any errors.
scErrs := jsch.Validate(rawObject)
var werras *jsonschema.ValidationError
if stdError.As(scErrs, &werras) {
validationErrors = formatJsonSchemaValidationError(schema, werras, entity, reasonEntity, name, validationType, subValType, pathTemplate, operation)
}
return validationErrors
}
// buildJsonRender build a JSON render of the schema.
func buildJsonRender(schema *base.Schema) ([]byte, error) {
if schema == nil {
// Sanity Check
return nil, stdError.New("buildJSONRender nil pointer")
}
renderedSchema, err := schema.Render()
if err != nil {
return nil, err
}
return utils.ConvertYAMLtoJSON(renderedSchema)
}
// GetRenderedSchema returns a YAML string representation of the schema for error messages.
// It first checks the schema cache for a pre-rendered version, falling back to fresh rendering.
// This avoids expensive re-rendering on each validation when the cache is available.
func GetRenderedSchema(schema *base.Schema, opts *config.ValidationOptions) string {
if schema == nil {
return ""
}
// Try cache lookup first
if opts != nil && opts.SchemaCache != nil && schema.GoLow() != nil {
hash := schema.GoLow().Hash()
if cached, ok := opts.SchemaCache.Load(hash); ok && cached != nil && len(cached.RenderedInline) > 0 {
return string(cached.RenderedInline)
}
}
// Cache miss - render fresh as YAML using validation mode
renderCtx := base.NewInlineRenderContextForValidation()
rendered, _ := schema.RenderInlineWithContext(renderCtx)
return string(rendered)
}
// ValidateParameterSchema will validate a parameter against a raw object, or a blob of json/yaml.
// It will return a list of validation errors, if any.
//
// schema: the schema to validate against
// rawObject: the object to validate (leave empty if using a blob)
// rawBlob: the blob to validate (leave empty if using an object)
// entity: the entity being validated
// reasonEntity: the entity that caused the validation to be called
// name: the name of the parameter
// validationType: the type of validation being performed
// subValType: the type of sub-validation being performed
func ValidateParameterSchema(
schema *base.Schema,
rawObject any,
rawBlob,
entity,
reasonEntity,
name,
validationType,
subValType string,
validationOptions *config.ValidationOptions,
) []*errors.ValidationError {
var validationErrors []*errors.ValidationError
var jsch *jsonschema.Schema
var jsonSchema []byte
// Try cache lookup first - avoids expensive schema compilation on each request
if validationOptions != nil && validationOptions.SchemaCache != nil && schema != nil && schema.GoLow() != nil {
hash := schema.GoLow().Hash()
if cached, ok := validationOptions.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil {
jsch = cached.CompiledSchema
}
}
// Cache miss - render and compile the schema
if jsch == nil {
// 1. build a JSON render of the schema.
renderCtx := base.NewInlineRenderContextForValidation()
renderedSchema, _ := schema.RenderInlineWithContext(renderCtx)
referenceSchema := string(renderedSchema)
jsonSchema, _ = utils.ConvertYAMLtoJSON(renderedSchema)
// 2. create a new json schema compiler and add the schema to it
var err error
jsch, err = helpers.NewCompiledSchema(name, jsonSchema, validationOptions)
if err != nil {
// schema compilation failed, return validation error instead of panicking
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: validationType,
ValidationSubType: subValType,
Message: fmt.Sprintf("%s '%s' failed schema compilation", entity, name),
Reason: fmt.Sprintf("%s '%s' schema compilation failed: %s",
reasonEntity, name, err.Error()),
SpecLine: 1,
SpecCol: 0,
ParameterName: name,
HowToFix: "check the parameter schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs",
Context: string(jsonSchema),
})
return validationErrors
}
// Store in cache for future requests
if validationOptions != nil && validationOptions.SchemaCache != nil && schema != nil && schema.GoLow() != nil {
hash := schema.GoLow().Hash()
var renderedNode yaml.Node
_ = yaml.Unmarshal(renderedSchema, &renderedNode)
validationOptions.SchemaCache.Store(hash, &cache.SchemaCacheEntry{
Schema: schema,
RenderedInline: renderedSchema,
ReferenceSchema: referenceSchema,
RenderedJSON: jsonSchema,
CompiledSchema: jsch,
RenderedNode: &renderedNode,
})
}
}
// 3. decode the object into a json blob.
var decodedObj interface{}
rawIsMap := false
validEncoding := false
if rawObject != nil {
// check what type of object it is
ot := reflect.TypeOf(rawObject)
var ok bool
switch ot.Kind() {
case reflect.Map:
if decodedObj, ok = rawObject.(map[string]interface{}); ok {
rawIsMap = true
validEncoding = true
} else {
rawIsMap = true
}
}
} else {
decodedString, _ := url.QueryUnescape(rawBlob)
err := json.Unmarshal([]byte(decodedString), &decodedObj)
if err != nil {
decodedObj = rawBlob
}
validEncoding = true
}
// 4. validate the object against the schema
var scErrs error
if validEncoding {
p := decodedObj
if rawIsMap {
if g, ko := rawObject.(map[string]interface{}); ko {
if len(g) == 0 || (g[""] != nil && g[""] == "") {
p = nil
}
}
}
if p != nil {
// check if any of the items have an empty key
skip := false
if rawIsMap {
for k := range p.(map[string]interface{}) {
if k == "" {
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: validationType,
ValidationSubType: subValType,
Message: fmt.Sprintf("%s '%s' failed to validate", entity, name),
Reason: fmt.Sprintf("%s '%s' is defined as an object, "+
"however it failed to pass a schema validation", reasonEntity, name),
SpecLine: schema.GoLow().Type.KeyNode.Line,
SpecCol: schema.GoLow().Type.KeyNode.Column,
SchemaValidationErrors: nil,
HowToFix: errors.HowToFixInvalidSchema,
})
skip = true
break
}
}
}
if !skip {
scErrs = jsch.Validate(p)
}
}
}
var werras *jsonschema.ValidationError
if stdError.As(scErrs, &werras) {
validationErrors = formatJsonSchemaValidationError(schema, werras, entity, reasonEntity, name, validationType, subValType, "", "")
}
// if there are no validationErrors, check that the supplied value is even JSON
if len(validationErrors) == 0 {
if rawIsMap {
if !validEncoding {
// add the error to the list
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: validationType,
ValidationSubType: subValType,
Message: fmt.Sprintf("%s '%s' cannot be decoded", entity, name),
Reason: fmt.Sprintf("%s '%s' is defined as an object, "+
"however it failed to be decoded as an object", reasonEntity, name),
SpecLine: schema.GoLow().RootNode.Line,
SpecCol: schema.GoLow().RootNode.Column,
HowToFix: errors.HowToFixDecodingError,
})
}
}
}
return validationErrors
}
func formatJsonSchemaValidationError(schema *base.Schema, scErrs *jsonschema.ValidationError, entity string, reasonEntity string, name string, validationType string, subValType string, pathTemplate string, operation string) (validationErrors []*errors.ValidationError) {
// flatten the validationErrors
schFlatErrs := scErrs.BasicOutput().Errors
var schemaValidationErrors []*errors.SchemaValidationFailure
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 not useful
}
// Construct full OpenAPI path for KeywordLocation if pathTemplate and operation are provided
keywordLocation := er.KeywordLocation
if pathTemplate != "" && operation != "" && validationType == helpers.ParameterValidation {
// er.KeywordLocation is relative to the schema (e.g., "/minLength" or "/enum")
keyword := strings.TrimPrefix(er.KeywordLocation, "/")
keywordLocation = helpers.ConstructParameterJSONPointer(pathTemplate, operation, name, keyword)
}
fail := &errors.SchemaValidationFailure{
Reason: errMsg,
FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation),
FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation),
InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation),
KeywordLocation: keywordLocation,
OriginalJsonSchemaError: scErrs,
}
if schema != nil {
renderCtx := base.NewInlineRenderContextForValidation()
rendered, err := schema.RenderInlineWithContext(renderCtx)
if err == nil && rendered != nil {
fail.ReferenceSchema = string(rendered)
}
}
schemaValidationErrors = append(schemaValidationErrors, fail)
}
schemaType := "undefined"
line := 0
col := 0
if len(schema.Type) > 0 {
schemaType = schema.Type[0]
line = schema.GoLow().Type.KeyNode.Line
col = schema.GoLow().Type.KeyNode.Column
} else {
var sTypes []string
seen := make(map[string]struct{})
extractTypes := func(s *base.SchemaProxy) {
pSch := s.Schema()
if pSch != nil {
for _, typ := range pSch.Type {
if _, ok := seen[typ]; !ok {
sTypes = append(sTypes, typ)
seen[typ] = struct{}{}
}
}
}
}
processPoly := func(schemas []*base.SchemaProxy) {
for _, s := range schemas {
extractTypes(s)
}
}
// check if there is polymorphism going on here.
if len(schema.AnyOf) > 0 || len(schema.AllOf) > 0 || len(schema.OneOf) > 0 {
processPoly(schema.AnyOf)
processPoly(schema.AllOf)
processPoly(schema.OneOf)
sep := "or"
if len(schema.AllOf) > 0 {
sep = "and a"
}
schemaType = strings.Join(sTypes, fmt.Sprintf(" %s ", sep))
}
line = schema.GoLow().RootNode.Line
col = schema.GoLow().RootNode.Column
}
validationErrors = append(validationErrors, &errors.ValidationError{
ValidationType: validationType,
ValidationSubType: subValType,
Message: fmt.Sprintf("%s '%s' failed to validate", entity, name),
Reason: fmt.Sprintf("%s '%s' is defined as an %s, "+
"however it failed to pass a schema validation", reasonEntity, name, schemaType),
SpecLine: line,
SpecCol: col,
ParameterName: name,
SchemaValidationErrors: schemaValidationErrors,
HowToFix: errors.HowToFixInvalidSchema,
})
return validationErrors
}