| 1 |
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package parameters |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding/json" |
| 8 |
"fmt" |
| 9 |
"net/url" |
| 10 |
"reflect" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 14 |
"github.com/pb33f/libopenapi/utils" |
| 15 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 16 |
"go.yaml.in/yaml/v4" |
| 17 |
"golang.org/x/text/language" |
| 18 |
"golang.org/x/text/message" |
| 19 |
|
| 20 |
stdError "errors" |
| 21 |
|
| 22 |
"github.com/pb33f/libopenapi-validator/cache" |
| 23 |
"github.com/pb33f/libopenapi-validator/config" |
| 24 |
"github.com/pb33f/libopenapi-validator/errors" |
| 25 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 26 |
) |
| 27 |
|
| 28 |
func ValidateSingleParameterSchema( |
| 29 |
schema *base.Schema, |
| 30 |
rawObject any, |
| 31 |
entity string, |
| 32 |
reasonEntity string, |
| 33 |
name string, |
| 34 |
validationType string, |
| 35 |
subValType string, |
| 36 |
o *config.ValidationOptions, |
| 37 |
pathTemplate string, |
| 38 |
operation string, |
| 39 |
) (validationErrors []*errors.ValidationError) { |
| 40 |
var jsch *jsonschema.Schema |
| 41 |
var jsonSchema []byte |
| 42 |
|
| 43 |
// Try cache lookup first - avoids expensive schema compilation on each request |
| 44 |
if o != nil && o.SchemaCache != nil && schema != nil && schema.GoLow() != nil { |
| 45 |
hash := schema.GoLow().Hash() |
| 46 |
if cached, ok := o.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil { |
| 47 |
jsch = cached.CompiledSchema |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
// Cache miss - compile the schema |
| 52 |
if jsch == nil { |
| 53 |
// Get the JSON Schema for the parameter definition. |
| 54 |
var err error |
| 55 |
jsonSchema, err = buildJsonRender(schema) |
| 56 |
if err != nil { |
| 57 |
return validationErrors |
| 58 |
} |
| 59 |
|
| 60 |
// Attempt to compile the JSON Schema |
| 61 |
jsch, err = helpers.NewCompiledSchema(name, jsonSchema, o) |
| 62 |
if err != nil { |
| 63 |
return validationErrors |
| 64 |
} |
| 65 |
|
| 66 |
// Store in cache for future requests |
| 67 |
if o != nil && o.SchemaCache != nil && schema != nil && schema.GoLow() != nil { |
| 68 |
hash := schema.GoLow().Hash() |
| 69 |
|
| 70 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 71 |
renderedInline, _ := schema.RenderInlineWithContext(renderCtx) |
| 72 |
referenceSchema := string(renderedInline) |
| 73 |
|
| 74 |
var renderedNode yaml.Node |
| 75 |
_ = yaml.Unmarshal(renderedInline, &renderedNode) |
| 76 |
|
| 77 |
o.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 78 |
Schema: schema, |
| 79 |
RenderedInline: renderedInline, |
| 80 |
ReferenceSchema: referenceSchema, |
| 81 |
RenderedJSON: jsonSchema, |
| 82 |
CompiledSchema: jsch, |
| 83 |
RenderedNode: &renderedNode, |
| 84 |
}) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
// Validate the object and report any errors. |
| 89 |
scErrs := jsch.Validate(rawObject) |
| 90 |
var werras *jsonschema.ValidationError |
| 91 |
if stdError.As(scErrs, &werras) { |
| 92 |
validationErrors = formatJsonSchemaValidationError(schema, werras, entity, reasonEntity, name, validationType, subValType, pathTemplate, operation) |
| 93 |
} |
| 94 |
return validationErrors |
| 95 |
} |
| 96 |
|
| 97 |
// buildJsonRender build a JSON render of the schema. |
| 98 |
func buildJsonRender(schema *base.Schema) ([]byte, error) { |
| 99 |
if schema == nil { |
| 100 |
// Sanity Check |
| 101 |
return nil, stdError.New("buildJSONRender nil pointer") |
| 102 |
} |
| 103 |
|
| 104 |
renderedSchema, err := schema.Render() |
| 105 |
if err != nil { |
| 106 |
return nil, err |
| 107 |
} |
| 108 |
|
| 109 |
return utils.ConvertYAMLtoJSON(renderedSchema) |
| 110 |
} |
| 111 |
|
| 112 |
// GetRenderedSchema returns a YAML string representation of the schema for error messages. |
| 113 |
// It first checks the schema cache for a pre-rendered version, falling back to fresh rendering. |
| 114 |
// This avoids expensive re-rendering on each validation when the cache is available. |
| 115 |
func GetRenderedSchema(schema *base.Schema, opts *config.ValidationOptions) string { |
| 116 |
if schema == nil { |
| 117 |
return "" |
| 118 |
} |
| 119 |
|
| 120 |
// Try cache lookup first |
| 121 |
if opts != nil && opts.SchemaCache != nil && schema.GoLow() != nil { |
| 122 |
hash := schema.GoLow().Hash() |
| 123 |
if cached, ok := opts.SchemaCache.Load(hash); ok && cached != nil && len(cached.RenderedInline) > 0 { |
| 124 |
return string(cached.RenderedInline) |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
// Cache miss - render fresh as YAML using validation mode |
| 129 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 130 |
rendered, _ := schema.RenderInlineWithContext(renderCtx) |
| 131 |
return string(rendered) |
| 132 |
} |
| 133 |
|
| 134 |
// ValidateParameterSchema will validate a parameter against a raw object, or a blob of json/yaml. |
| 135 |
// It will return a list of validation errors, if any. |
| 136 |
// |
| 137 |
// schema: the schema to validate against |
| 138 |
// rawObject: the object to validate (leave empty if using a blob) |
| 139 |
// rawBlob: the blob to validate (leave empty if using an object) |
| 140 |
// entity: the entity being validated |
| 141 |
// reasonEntity: the entity that caused the validation to be called |
| 142 |
// name: the name of the parameter |
| 143 |
// validationType: the type of validation being performed |
| 144 |
// subValType: the type of sub-validation being performed |
| 145 |
func ValidateParameterSchema( |
| 146 |
schema *base.Schema, |
| 147 |
rawObject any, |
| 148 |
rawBlob, |
| 149 |
entity, |
| 150 |
reasonEntity, |
| 151 |
name, |
| 152 |
validationType, |
| 153 |
subValType string, |
| 154 |
validationOptions *config.ValidationOptions, |
| 155 |
) []*errors.ValidationError { |
| 156 |
var validationErrors []*errors.ValidationError |
| 157 |
var jsch *jsonschema.Schema |
| 158 |
var jsonSchema []byte |
| 159 |
|
| 160 |
// Try cache lookup first - avoids expensive schema compilation on each request |
| 161 |
if validationOptions != nil && validationOptions.SchemaCache != nil && schema != nil && schema.GoLow() != nil { |
| 162 |
hash := schema.GoLow().Hash() |
| 163 |
if cached, ok := validationOptions.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil { |
| 164 |
jsch = cached.CompiledSchema |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
// Cache miss - render and compile the schema |
| 169 |
if jsch == nil { |
| 170 |
// 1. build a JSON render of the schema. |
| 171 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 172 |
renderedSchema, _ := schema.RenderInlineWithContext(renderCtx) |
| 173 |
referenceSchema := string(renderedSchema) |
| 174 |
jsonSchema, _ = utils.ConvertYAMLtoJSON(renderedSchema) |
| 175 |
|
| 176 |
// 2. create a new json schema compiler and add the schema to it |
| 177 |
var err error |
| 178 |
jsch, err = helpers.NewCompiledSchema(name, jsonSchema, validationOptions) |
| 179 |
if err != nil { |
| 180 |
// schema compilation failed, return validation error instead of panicking |
| 181 |
validationErrors = append(validationErrors, &errors.ValidationError{ |
| 182 |
ValidationType: validationType, |
| 183 |
ValidationSubType: subValType, |
| 184 |
Message: fmt.Sprintf("%s '%s' failed schema compilation", entity, name), |
| 185 |
Reason: fmt.Sprintf("%s '%s' schema compilation failed: %s", |
| 186 |
reasonEntity, name, err.Error()), |
| 187 |
SpecLine: 1, |
| 188 |
SpecCol: 0, |
| 189 |
ParameterName: name, |
| 190 |
HowToFix: "check the parameter schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs", |
| 191 |
Context: string(jsonSchema), |
| 192 |
}) |
| 193 |
return validationErrors |
| 194 |
} |
| 195 |
|
| 196 |
// Store in cache for future requests |
| 197 |
if validationOptions != nil && validationOptions.SchemaCache != nil && schema != nil && schema.GoLow() != nil { |
| 198 |
hash := schema.GoLow().Hash() |
| 199 |
|
| 200 |
var renderedNode yaml.Node |
| 201 |
_ = yaml.Unmarshal(renderedSchema, &renderedNode) |
| 202 |
|
| 203 |
validationOptions.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 204 |
Schema: schema, |
| 205 |
RenderedInline: renderedSchema, |
| 206 |
ReferenceSchema: referenceSchema, |
| 207 |
RenderedJSON: jsonSchema, |
| 208 |
CompiledSchema: jsch, |
| 209 |
RenderedNode: &renderedNode, |
| 210 |
}) |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
// 3. decode the object into a json blob. |
| 215 |
var decodedObj interface{} |
| 216 |
rawIsMap := false |
| 217 |
validEncoding := false |
| 218 |
if rawObject != nil { |
| 219 |
// check what type of object it is |
| 220 |
ot := reflect.TypeOf(rawObject) |
| 221 |
var ok bool |
| 222 |
switch ot.Kind() { |
| 223 |
case reflect.Map: |
| 224 |
if decodedObj, ok = rawObject.(map[string]interface{}); ok { |
| 225 |
rawIsMap = true |
| 226 |
validEncoding = true |
| 227 |
} else { |
| 228 |
rawIsMap = true |
| 229 |
} |
| 230 |
} |
| 231 |
} else { |
| 232 |
decodedString, _ := url.QueryUnescape(rawBlob) |
| 233 |
err := json.Unmarshal([]byte(decodedString), &decodedObj) |
| 234 |
if err != nil { |
| 235 |
decodedObj = rawBlob |
| 236 |
} |
| 237 |
validEncoding = true |
| 238 |
} |
| 239 |
|
| 240 |
// 4. validate the object against the schema |
| 241 |
var scErrs error |
| 242 |
if validEncoding { |
| 243 |
p := decodedObj |
| 244 |
if rawIsMap { |
| 245 |
if g, ko := rawObject.(map[string]interface{}); ko { |
| 246 |
if len(g) == 0 || (g[""] != nil && g[""] == "") { |
| 247 |
p = nil |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
if p != nil { |
| 252 |
|
| 253 |
// check if any of the items have an empty key |
| 254 |
skip := false |
| 255 |
if rawIsMap { |
| 256 |
for k := range p.(map[string]interface{}) { |
| 257 |
if k == "" { |
| 258 |
validationErrors = append(validationErrors, &errors.ValidationError{ |
| 259 |
ValidationType: validationType, |
| 260 |
ValidationSubType: subValType, |
| 261 |
Message: fmt.Sprintf("%s '%s' failed to validate", entity, name), |
| 262 |
Reason: fmt.Sprintf("%s '%s' is defined as an object, "+ |
| 263 |
"however it failed to pass a schema validation", reasonEntity, name), |
| 264 |
SpecLine: schema.GoLow().Type.KeyNode.Line, |
| 265 |
SpecCol: schema.GoLow().Type.KeyNode.Column, |
| 266 |
SchemaValidationErrors: nil, |
| 267 |
HowToFix: errors.HowToFixInvalidSchema, |
| 268 |
}) |
| 269 |
skip = true |
| 270 |
break |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
if !skip { |
| 275 |
scErrs = jsch.Validate(p) |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
var werras *jsonschema.ValidationError |
| 280 |
if stdError.As(scErrs, &werras) { |
| 281 |
validationErrors = formatJsonSchemaValidationError(schema, werras, entity, reasonEntity, name, validationType, subValType, "", "") |
| 282 |
} |
| 283 |
|
| 284 |
// if there are no validationErrors, check that the supplied value is even JSON |
| 285 |
if len(validationErrors) == 0 { |
| 286 |
if rawIsMap { |
| 287 |
if !validEncoding { |
| 288 |
// add the error to the list |
| 289 |
validationErrors = append(validationErrors, &errors.ValidationError{ |
| 290 |
ValidationType: validationType, |
| 291 |
ValidationSubType: subValType, |
| 292 |
Message: fmt.Sprintf("%s '%s' cannot be decoded", entity, name), |
| 293 |
Reason: fmt.Sprintf("%s '%s' is defined as an object, "+ |
| 294 |
"however it failed to be decoded as an object", reasonEntity, name), |
| 295 |
SpecLine: schema.GoLow().RootNode.Line, |
| 296 |
SpecCol: schema.GoLow().RootNode.Column, |
| 297 |
HowToFix: errors.HowToFixDecodingError, |
| 298 |
}) |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
return validationErrors |
| 303 |
} |
| 304 |
|
| 305 |
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) { |
| 306 |
// flatten the validationErrors |
| 307 |
schFlatErrs := scErrs.BasicOutput().Errors |
| 308 |
var schemaValidationErrors []*errors.SchemaValidationFailure |
| 309 |
for q := range schFlatErrs { |
| 310 |
er := schFlatErrs[q] |
| 311 |
|
| 312 |
errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{})) |
| 313 |
if er.KeywordLocation == "" || helpers.IgnoreRegex.MatchString(errMsg) { |
| 314 |
continue // ignore this error, it's not useful |
| 315 |
} |
| 316 |
|
| 317 |
// Construct full OpenAPI path for KeywordLocation if pathTemplate and operation are provided |
| 318 |
keywordLocation := er.KeywordLocation |
| 319 |
if pathTemplate != "" && operation != "" && validationType == helpers.ParameterValidation { |
| 320 |
// er.KeywordLocation is relative to the schema (e.g., "/minLength" or "/enum") |
| 321 |
keyword := strings.TrimPrefix(er.KeywordLocation, "/") |
| 322 |
keywordLocation = helpers.ConstructParameterJSONPointer(pathTemplate, operation, name, keyword) |
| 323 |
} |
| 324 |
|
| 325 |
fail := &errors.SchemaValidationFailure{ |
| 326 |
Reason: errMsg, |
| 327 |
FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation), |
| 328 |
FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation), |
| 329 |
InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation), |
| 330 |
KeywordLocation: keywordLocation, |
| 331 |
OriginalJsonSchemaError: scErrs, |
| 332 |
} |
| 333 |
if schema != nil { |
| 334 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 335 |
rendered, err := schema.RenderInlineWithContext(renderCtx) |
| 336 |
if err == nil && rendered != nil { |
| 337 |
fail.ReferenceSchema = string(rendered) |
| 338 |
} |
| 339 |
} |
| 340 |
schemaValidationErrors = append(schemaValidationErrors, fail) |
| 341 |
} |
| 342 |
schemaType := "undefined" |
| 343 |
line := 0 |
| 344 |
col := 0 |
| 345 |
if len(schema.Type) > 0 { |
| 346 |
schemaType = schema.Type[0] |
| 347 |
line = schema.GoLow().Type.KeyNode.Line |
| 348 |
col = schema.GoLow().Type.KeyNode.Column |
| 349 |
} else { |
| 350 |
var sTypes []string |
| 351 |
seen := make(map[string]struct{}) |
| 352 |
extractTypes := func(s *base.SchemaProxy) { |
| 353 |
pSch := s.Schema() |
| 354 |
if pSch != nil { |
| 355 |
for _, typ := range pSch.Type { |
| 356 |
if _, ok := seen[typ]; !ok { |
| 357 |
sTypes = append(sTypes, typ) |
| 358 |
seen[typ] = struct{}{} |
| 359 |
} |
| 360 |
} |
| 361 |
} |
| 362 |
} |
| 363 |
processPoly := func(schemas []*base.SchemaProxy) { |
| 364 |
for _, s := range schemas { |
| 365 |
extractTypes(s) |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
// check if there is polymorphism going on here. |
| 370 |
if len(schema.AnyOf) > 0 || len(schema.AllOf) > 0 || len(schema.OneOf) > 0 { |
| 371 |
processPoly(schema.AnyOf) |
| 372 |
processPoly(schema.AllOf) |
| 373 |
processPoly(schema.OneOf) |
| 374 |
|
| 375 |
sep := "or" |
| 376 |
if len(schema.AllOf) > 0 { |
| 377 |
sep = "and a" |
| 378 |
} |
| 379 |
schemaType = strings.Join(sTypes, fmt.Sprintf(" %s ", sep)) |
| 380 |
} |
| 381 |
|
| 382 |
line = schema.GoLow().RootNode.Line |
| 383 |
col = schema.GoLow().RootNode.Column |
| 384 |
} |
| 385 |
|
| 386 |
validationErrors = append(validationErrors, &errors.ValidationError{ |
| 387 |
ValidationType: validationType, |
| 388 |
ValidationSubType: subValType, |
| 389 |
Message: fmt.Sprintf("%s '%s' failed to validate", entity, name), |
| 390 |
Reason: fmt.Sprintf("%s '%s' is defined as an %s, "+ |
| 391 |
"however it failed to pass a schema validation", reasonEntity, name, schemaType), |
| 392 |
SpecLine: line, |
| 393 |
SpecCol: col, |
| 394 |
ParameterName: name, |
| 395 |
SchemaValidationErrors: schemaValidationErrors, |
| 396 |
HowToFix: errors.HowToFixInvalidSchema, |
| 397 |
}) |
| 398 |
return validationErrors |
| 399 |
} |