| 1 |
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
package schema_validation |
| 4 |
|
| 5 |
import ( |
| 6 |
"encoding/json" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"log/slog" |
| 10 |
"math" |
| 11 |
"os" |
| 12 |
"reflect" |
| 13 |
"regexp" |
| 14 |
"strconv" |
| 15 |
"sync" |
| 16 |
|
| 17 |
"github.com/pb33f/libopenapi-validator/cache" |
| 18 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 19 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 20 |
"go.yaml.in/yaml/v4" |
| 21 |
"golang.org/x/text/language" |
| 22 |
"golang.org/x/text/message" |
| 23 |
|
| 24 |
_ "embed" |
| 25 |
|
| 26 |
"github.com/pb33f/libopenapi-validator/config" |
| 27 |
liberrors "github.com/pb33f/libopenapi-validator/errors" |
| 28 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 29 |
) |
| 30 |
|
| 31 |
// SchemaValidator is an interface that defines the methods for validating a *base.Schema (V3+ Only) object. |
| 32 |
// There are 6 methods for validating a schema: |
| 33 |
// |
| 34 |
// ValidateSchemaString accepts a schema object to validate against, and a JSON/YAML blob that is defined as a string. |
| 35 |
// ValidateSchemaObject accepts a schema object to validate against, and an object, created from unmarshalled JSON/YAML. |
| 36 |
// ValidateSchemaBytes accepts a schema object to validate against, and a JSON/YAML blob that is defined as a byte array. |
| 37 |
// ValidateSchemaStringWithVersion - version-aware validation that allows OpenAPI 3.0 keywords when version is specified. |
| 38 |
// ValidateSchemaObjectWithVersion - version-aware validation that allows OpenAPI 3.0 keywords when version is specified. |
| 39 |
// ValidateSchemaBytesWithVersion - version-aware validation that allows OpenAPI 3.0 keywords when version is specified. |
| 40 |
type SchemaValidator interface { |
| 41 |
// ValidateSchemaString accepts a schema object to validate against, and a JSON/YAML blob that is defined as a string. |
| 42 |
// Uses OpenAPI 3.1+ validation by default (strict JSON Schema compliance). |
| 43 |
ValidateSchemaString(schema *base.Schema, payload string) (bool, []*liberrors.ValidationError) |
| 44 |
|
| 45 |
// ValidateSchemaObject accepts a schema object to validate against, and an object, created from unmarshalled JSON/YAML. |
| 46 |
// This is a pre-decoded object that will skip the need to unmarshal a string of JSON/YAML. |
| 47 |
// Uses OpenAPI 3.1+ validation by default (strict JSON Schema compliance). |
| 48 |
ValidateSchemaObject(schema *base.Schema, payload interface{}) (bool, []*liberrors.ValidationError) |
| 49 |
|
| 50 |
// ValidateSchemaBytes accepts a schema object to validate against, and a byte slice containing a schema to |
| 51 |
// validate against. Uses OpenAPI 3.1+ validation by default (strict JSON Schema compliance). |
| 52 |
ValidateSchemaBytes(schema *base.Schema, payload []byte) (bool, []*liberrors.ValidationError) |
| 53 |
|
| 54 |
// ValidateSchemaStringWithVersion accepts a schema object to validate against, a JSON/YAML blob, and an OpenAPI version. |
| 55 |
// When version is 3.0, OpenAPI 3.0-specific keywords like 'nullable' are allowed and processed. |
| 56 |
// When version is 3.1+, OpenAPI 3.0-specific keywords like 'nullable' will cause validation to fail. |
| 57 |
ValidateSchemaStringWithVersion(schema *base.Schema, payload string, version float32) (bool, []*liberrors.ValidationError) |
| 58 |
|
| 59 |
// ValidateSchemaObjectWithVersion accepts a schema object to validate against, an object, and an OpenAPI version. |
| 60 |
// When version is 3.0, OpenAPI 3.0-specific keywords like 'nullable' are allowed and processed. |
| 61 |
// When version is 3.1+, OpenAPI 3.0-specific keywords like 'nullable' will cause validation to fail. |
| 62 |
ValidateSchemaObjectWithVersion(schema *base.Schema, payload interface{}, version float32) (bool, []*liberrors.ValidationError) |
| 63 |
|
| 64 |
// ValidateSchemaBytesWithVersion accepts a schema object to validate against, a byte slice, and an OpenAPI version. |
| 65 |
// When version is 3.0, OpenAPI 3.0-specific keywords like 'nullable' are allowed and processed. |
| 66 |
// When version is 3.1+, OpenAPI 3.0-specific keywords like 'nullable' will cause validation to fail. |
| 67 |
ValidateSchemaBytesWithVersion(schema *base.Schema, payload []byte, version float32) (bool, []*liberrors.ValidationError) |
| 68 |
} |
| 69 |
|
| 70 |
var instanceLocationRegex = regexp.MustCompile(`^/(\d+)`) |
| 71 |
|
| 72 |
type schemaValidator struct { |
| 73 |
options *config.ValidationOptions |
| 74 |
logger *slog.Logger |
| 75 |
lock sync.Mutex |
| 76 |
} |
| 77 |
|
| 78 |
// NewSchemaValidatorWithLogger will create a new SchemaValidator instance, ready to accept schemas and payloads to validate. |
| 79 |
func NewSchemaValidatorWithLogger(logger *slog.Logger, opts ...config.Option) SchemaValidator { |
| 80 |
options := config.NewValidationOptions(opts...) |
| 81 |
|
| 82 |
return &schemaValidator{options: options, logger: logger, lock: sync.Mutex{}} |
| 83 |
} |
| 84 |
|
| 85 |
// NewSchemaValidator will create a new SchemaValidator instance, ready to accept schemas and payloads to validate. |
| 86 |
func NewSchemaValidator(opts ...config.Option) SchemaValidator { |
| 87 |
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ |
| 88 |
Level: slog.LevelError, |
| 89 |
})) |
| 90 |
return NewSchemaValidatorWithLogger(logger, opts...) |
| 91 |
} |
| 92 |
|
| 93 |
func (s *schemaValidator) ValidateSchemaString(schema *base.Schema, payload string) (bool, []*liberrors.ValidationError) { |
| 94 |
return s.validateSchemaWithVersion(schema, []byte(payload), nil, s.logger, 3.1) |
| 95 |
} |
| 96 |
|
| 97 |
func (s *schemaValidator) ValidateSchemaObject(schema *base.Schema, payload interface{}) (bool, []*liberrors.ValidationError) { |
| 98 |
return s.validateSchemaWithVersion(schema, nil, payload, s.logger, 3.1) |
| 99 |
} |
| 100 |
|
| 101 |
func (s *schemaValidator) ValidateSchemaBytes(schema *base.Schema, payload []byte) (bool, []*liberrors.ValidationError) { |
| 102 |
return s.validateSchemaWithVersion(schema, payload, nil, s.logger, 3.1) |
| 103 |
} |
| 104 |
|
| 105 |
func (s *schemaValidator) ValidateSchemaStringWithVersion(schema *base.Schema, payload string, version float32) (bool, []*liberrors.ValidationError) { |
| 106 |
return s.validateSchemaWithVersion(schema, []byte(payload), nil, s.logger, version) |
| 107 |
} |
| 108 |
|
| 109 |
func (s *schemaValidator) ValidateSchemaObjectWithVersion(schema *base.Schema, payload interface{}, version float32) (bool, []*liberrors.ValidationError) { |
| 110 |
return s.validateSchemaWithVersion(schema, nil, payload, s.logger, version) |
| 111 |
} |
| 112 |
|
| 113 |
func (s *schemaValidator) ValidateSchemaBytesWithVersion(schema *base.Schema, payload []byte, version float32) (bool, []*liberrors.ValidationError) { |
| 114 |
return s.validateSchemaWithVersion(schema, payload, nil, s.logger, version) |
| 115 |
} |
| 116 |
|
| 117 |
func (s *schemaValidator) validateSchemaWithVersion(schema *base.Schema, payload []byte, decodedObject interface{}, log *slog.Logger, version float32) (bool, []*liberrors.ValidationError) { |
| 118 |
var validationErrors []*liberrors.ValidationError |
| 119 |
|
| 120 |
if schema == nil { |
| 121 |
log.Info("schema is empty and cannot be validated. This generally means the schema is missing from the spec, or could not be read.") |
| 122 |
return false, validationErrors |
| 123 |
} |
| 124 |
|
| 125 |
var renderedSchema []byte |
| 126 |
var renderedNode *yaml.Node |
| 127 |
var compiledSchema *jsonschema.Schema |
| 128 |
|
| 129 |
// Check cache first — reuses existing SchemaCache (populated by NewValidationOptions). |
| 130 |
var cacheKey uint64 |
| 131 |
canCache := s.options.SchemaCache != nil && schema.GoLow() != nil |
| 132 |
if canCache { |
| 133 |
// Include version in key so 3.0 (nullable) and 3.1 compile differently. |
| 134 |
cacheKey = schema.GoLow().Hash() ^ uint64(math.Float32bits(version)) |
| 135 |
if cached, ok := s.options.SchemaCache.Load(cacheKey); ok && |
| 136 |
cached != nil && cached.CompiledSchema != nil { |
| 137 |
renderedSchema = cached.RenderedInline |
| 138 |
renderedNode = cached.RenderedNode |
| 139 |
compiledSchema = cached.CompiledSchema |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
// Cache miss — render, convert to JSON, and compile. |
| 144 |
if compiledSchema == nil { |
| 145 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 146 |
s.lock.Lock() |
| 147 |
nodeIface, renderErr := schema.MarshalYAMLInlineWithContext(renderCtx) |
| 148 |
s.lock.Unlock() |
| 149 |
|
| 150 |
if renderErr != nil { |
| 151 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 152 |
ValidationType: helpers.RequestBodyValidation, |
| 153 |
ValidationSubType: helpers.Schema, |
| 154 |
Message: "schema does not pass validation", |
| 155 |
Reason: fmt.Sprintf("The schema cannot be decoded: %s", renderErr.Error()), |
| 156 |
SpecLine: schema.GoLow().GetRootNode().Line, |
| 157 |
SpecCol: schema.GoLow().GetRootNode().Column, |
| 158 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 159 |
Context: string(renderedSchema), |
| 160 |
}) |
| 161 |
return false, validationErrors |
| 162 |
} |
| 163 |
|
| 164 |
// MarshalYAMLInlineWithContext returns *yaml.Node (from NodeBuilder.Render) |
| 165 |
renderedNode, _ = nodeIface.(*yaml.Node) |
| 166 |
|
| 167 |
// yaml.Node → map → JSON bytes (skips yaml.Marshal + yaml.Unmarshal round-trip) |
| 168 |
var jsonMap map[string]interface{} |
| 169 |
if renderedNode != nil { |
| 170 |
_ = renderedNode.Decode(&jsonMap) |
| 171 |
} |
| 172 |
jsonSchema, _ := json.Marshal(jsonMap) |
| 173 |
|
| 174 |
// YAML bytes generated once for error messages / context strings |
| 175 |
renderedSchema, _ = yaml.Marshal(renderedNode) |
| 176 |
|
| 177 |
path := "" |
| 178 |
if schema.GoLow().GetIndex() != nil { |
| 179 |
path = schema.GoLow().GetIndex().GetSpecAbsolutePath() |
| 180 |
} |
| 181 |
|
| 182 |
var compileErr error |
| 183 |
compiledSchema, compileErr = helpers.NewCompiledSchemaWithVersion(path, jsonSchema, s.options, version) |
| 184 |
if compileErr != nil { |
| 185 |
line := 1 |
| 186 |
col := 0 |
| 187 |
if schema.GoLow().Type.KeyNode != nil { |
| 188 |
line = schema.GoLow().Type.KeyNode.Line |
| 189 |
col = schema.GoLow().Type.KeyNode.Column |
| 190 |
} |
| 191 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 192 |
ValidationType: helpers.Schema, |
| 193 |
ValidationSubType: helpers.Schema, |
| 194 |
Message: "schema compilation failed", |
| 195 |
Reason: fmt.Sprintf("Schema compilation failed: %s", compileErr.Error()), |
| 196 |
SpecLine: line, |
| 197 |
SpecCol: col, |
| 198 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 199 |
Context: string(renderedSchema), |
| 200 |
}) |
| 201 |
return false, validationErrors |
| 202 |
} |
| 203 |
|
| 204 |
// Store in cache for subsequent validations of the same schema. |
| 205 |
if canCache && compiledSchema != nil { |
| 206 |
s.options.SchemaCache.Store(cacheKey, &cache.SchemaCacheEntry{ |
| 207 |
Schema: schema, |
| 208 |
RenderedInline: renderedSchema, |
| 209 |
ReferenceSchema: string(renderedSchema), |
| 210 |
RenderedJSON: jsonSchema, |
| 211 |
CompiledSchema: compiledSchema, |
| 212 |
RenderedNode: renderedNode, |
| 213 |
}) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
if decodedObject == nil && len(payload) > 0 { |
| 218 |
err := json.Unmarshal(payload, &decodedObject) |
| 219 |
if err != nil { |
| 220 |
// cannot decode the request body, so it's not valid |
| 221 |
line := 1 |
| 222 |
col := 0 |
| 223 |
if schema.GoLow().Type.KeyNode != nil { |
| 224 |
line = schema.GoLow().Type.KeyNode.Line |
| 225 |
col = schema.GoLow().Type.KeyNode.Column |
| 226 |
} |
| 227 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 228 |
ValidationType: helpers.RequestBodyValidation, |
| 229 |
ValidationSubType: helpers.Schema, |
| 230 |
Message: "schema does not pass validation", |
| 231 |
Reason: fmt.Sprintf("The schema cannot be decoded: %s", err.Error()), |
| 232 |
SpecLine: line, |
| 233 |
SpecCol: col, |
| 234 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 235 |
Context: string(renderedSchema), |
| 236 |
}) |
| 237 |
return false, validationErrors |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
var schemaValidationErrors []*liberrors.SchemaValidationFailure |
| 242 |
|
| 243 |
if compiledSchema != nil && decodedObject != nil { |
| 244 |
scErrs := compiledSchema.Validate(decodedObject) |
| 245 |
if scErrs != nil { |
| 246 |
|
| 247 |
var jk *jsonschema.ValidationError |
| 248 |
if errors.As(scErrs, &jk) { |
| 249 |
|
| 250 |
// flatten the validationErrors |
| 251 |
schFlatErr := jk.BasicOutput().Errors |
| 252 |
schemaValidationErrors = extractBasicErrors(schFlatErr, renderedSchema, |
| 253 |
renderedNode, decodedObject, payload, jk, schemaValidationErrors) |
| 254 |
} |
| 255 |
line := 1 |
| 256 |
col := 0 |
| 257 |
if schema.GoLow().Type.KeyNode != nil { |
| 258 |
line = schema.GoLow().Type.KeyNode.Line |
| 259 |
col = schema.GoLow().Type.KeyNode.Column |
| 260 |
} |
| 261 |
|
| 262 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 263 |
ValidationType: helpers.Schema, |
| 264 |
Message: "schema does not pass validation", |
| 265 |
Reason: "Schema failed to validate against the contract requirements", |
| 266 |
SpecLine: line, |
| 267 |
SpecCol: col, |
| 268 |
SchemaValidationErrors: schemaValidationErrors, |
| 269 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 270 |
Context: string(renderedSchema), |
| 271 |
}) |
| 272 |
} |
| 273 |
} |
| 274 |
if len(validationErrors) > 0 { |
| 275 |
return false, validationErrors |
| 276 |
} |
| 277 |
return true, nil |
| 278 |
} |
| 279 |
|
| 280 |
func extractBasicErrors(schFlatErrs []jsonschema.OutputUnit, |
| 281 |
renderedSchema []byte, renderedNode *yaml.Node, |
| 282 |
decodedObject interface{}, |
| 283 |
payload []byte, jk *jsonschema.ValidationError, |
| 284 |
schemaValidationErrors []*liberrors.SchemaValidationFailure, |
| 285 |
) []*liberrors.SchemaValidationFailure { |
| 286 |
// Extract property name info once before processing errors (performance optimization) |
| 287 |
propertyInfo := extractPropertyNameFromError(jk) |
| 288 |
|
| 289 |
// Determine root content node ONCE (not per-error). |
| 290 |
// NodeBuilder.Render() returns MappingNode directly, no DocumentNode unwrapping needed. |
| 291 |
var rootNode *yaml.Node |
| 292 |
if renderedNode != nil { |
| 293 |
rootNode = renderedNode |
| 294 |
} else if len(renderedSchema) > 0 { |
| 295 |
// Fallback: parse bytes ONCE |
| 296 |
var docNode yaml.Node |
| 297 |
_ = yaml.Unmarshal(renderedSchema, &docNode) |
| 298 |
if len(docNode.Content) > 0 { |
| 299 |
rootNode = docNode.Content[0] |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
for q := range schFlatErrs { |
| 304 |
er := schFlatErrs[q] |
| 305 |
|
| 306 |
errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{})) |
| 307 |
if helpers.IgnoreRegex.MatchString(errMsg) { |
| 308 |
continue // ignore this error, it's useless tbh, utter noise. |
| 309 |
} |
| 310 |
if er.Error != nil { |
| 311 |
|
| 312 |
// locate the violated property in the schema |
| 313 |
var located *yaml.Node |
| 314 |
if rootNode != nil { |
| 315 |
located = LocateSchemaPropertyNodeByJSONPath(rootNode, er.KeywordLocation) |
| 316 |
} |
| 317 |
|
| 318 |
// extract the element specified by the instance |
| 319 |
val := instanceLocationRegex.FindStringSubmatch(er.InstanceLocation) |
| 320 |
var referenceObject string |
| 321 |
|
| 322 |
if len(val) > 0 { |
| 323 |
referenceIndex, _ := strconv.Atoi(val[1]) |
| 324 |
if reflect.ValueOf(decodedObject).Type().Kind() == reflect.Slice { |
| 325 |
found := decodedObject.([]any)[referenceIndex] |
| 326 |
recoded, _ := json.MarshalIndent(found, "", " ") |
| 327 |
referenceObject = string(recoded) |
| 328 |
} |
| 329 |
} |
| 330 |
if referenceObject == "" { |
| 331 |
referenceObject = string(payload) |
| 332 |
} |
| 333 |
|
| 334 |
violation := &liberrors.SchemaValidationFailure{ |
| 335 |
Reason: errMsg, |
| 336 |
FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation), |
| 337 |
FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation), |
| 338 |
InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation), |
| 339 |
KeywordLocation: er.KeywordLocation, |
| 340 |
ReferenceSchema: string(renderedSchema), |
| 341 |
ReferenceObject: referenceObject, |
| 342 |
OriginalJsonSchemaError: jk, |
| 343 |
} |
| 344 |
// if we have a location within the schema, add it to the error |
| 345 |
if located != nil { |
| 346 |
line := located.Line |
| 347 |
// if the located node is a map or an array, then the actual human interpretable |
| 348 |
// line on which the violation occurred is the line of the key, not the value. |
| 349 |
if located.Kind == yaml.MappingNode || located.Kind == yaml.SequenceNode { |
| 350 |
if line > 0 { |
| 351 |
line-- |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
// location of the violation within the rendered schema. |
| 356 |
violation.Line = line |
| 357 |
violation.Column = located.Column |
| 358 |
} else if rootNode != nil { |
| 359 |
// handles property name validation errors that don't provide useful InstanceLocation |
| 360 |
applyPropertyNameFallback(propertyInfo, rootNode, violation) |
| 361 |
} |
| 362 |
schemaValidationErrors = append(schemaValidationErrors, violation) |
| 363 |
} |
| 364 |
} |
| 365 |
return schemaValidationErrors |
| 366 |
} |