Debian Codegraph @

validator.go

raw
1 // Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package validator
5
6 import (
7 "fmt"
8 "net/http"
9 "sort"
10 "sync"
11
12 "github.com/pb33f/libopenapi"
13 "github.com/pb33f/libopenapi/datamodel/high/base"
14 "github.com/pb33f/libopenapi/utils"
15 "go.yaml.in/yaml/v4"
16
17 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
18
19 "github.com/pb33f/libopenapi-validator/cache"
20 "github.com/pb33f/libopenapi-validator/config"
21 "github.com/pb33f/libopenapi-validator/errors"
22 "github.com/pb33f/libopenapi-validator/helpers"
23 "github.com/pb33f/libopenapi-validator/parameters"
24 "github.com/pb33f/libopenapi-validator/paths"
25 "github.com/pb33f/libopenapi-validator/radix"
26 "github.com/pb33f/libopenapi-validator/requests"
27 "github.com/pb33f/libopenapi-validator/responses"
28 "github.com/pb33f/libopenapi-validator/schema_validation"
29 )
30
31 // Validator provides a coarse grained interface for validating an OpenAPI 3+ documents.
32 // There are three primary use-cases for validation
33 //
34 // Validating *http.Request objects against and OpenAPI 3+ document
35 // Validating *http.Response objects against an OpenAPI 3+ document
36 // Validating an OpenAPI 3+ document against the OpenAPI 3+ specification
37 type Validator interface {
38 // ValidateHttpRequest will validate an *http.Request object against an OpenAPI 3+ document.
39 // The path, query, cookie and header parameters and request body are validated.
40 ValidateHttpRequest(request *http.Request) (bool, []*errors.ValidationError)
41 // ValidateHttpRequestSync will validate an *http.Request object against an OpenAPI 3+ document synchronously and without spawning any goroutines.
42 // The path, query, cookie and header parameters and request body are validated.
43 ValidateHttpRequestSync(request *http.Request) (bool, []*errors.ValidationError)
44
45 // ValidateHttpRequestWithPathItem will validate an *http.Request object against an OpenAPI 3+ document.
46 // The path, query, cookie and header parameters and request body are validated.
47 ValidateHttpRequestWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError)
48
49 // ValidateHttpRequestSyncWithPathItem will validate an *http.Request object against an OpenAPI 3+ document synchronously and without spawning any goroutines.
50 // The path, query, cookie and header parameters and request body are validated.
51 ValidateHttpRequestSyncWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError)
52
53 // ValidateHttpResponse will an *http.Response object against an OpenAPI 3+ document.
54 // The response body is validated. The request is only used to extract the correct response from the spec.
55 ValidateHttpResponse(request *http.Request, response *http.Response) (bool, []*errors.ValidationError)
56
57 // ValidateHttpRequestResponse will validate both the *http.Request and *http.Response objects against an OpenAPI 3+ document.
58 // The path, query, cookie and header parameters and request and response body are validated.
59 ValidateHttpRequestResponse(request *http.Request, response *http.Response) (bool, []*errors.ValidationError)
60
61 // ValidateDocument will validate an OpenAPI 3+ document against the 3.0 or 3.1 OpenAPI 3+ specification
62 ValidateDocument() (bool, []*errors.ValidationError)
63
64 // GetParameterValidator will return a parameters.ParameterValidator instance used to validate parameters
65 GetParameterValidator() parameters.ParameterValidator
66
67 // GetRequestBodyValidator will return a parameters.RequestBodyValidator instance used to validate request bodies
68 GetRequestBodyValidator() requests.RequestBodyValidator
69
70 // GetResponseBodyValidator will return a parameters.ResponseBodyValidator instance used to validate response bodies
71 GetResponseBodyValidator() responses.ResponseBodyValidator
72
73 // SetDocument will set the OpenAPI 3+ document to be validated
74 SetDocument(document libopenapi.Document)
75 }
76
77 // NewValidator will create a new Validator from an OpenAPI 3+ document
78 func NewValidator(document libopenapi.Document, opts ...config.Option) (Validator, []error) {
79 m, errs := document.BuildV3Model()
80 if errs != nil {
81 return nil, []error{errs}
82 }
83 v := NewValidatorFromV3Model(&m.Model, opts...)
84 v.(*validator).document = document
85 return v, nil
86 }
87
88 // NewValidatorFromV3Model will create a new Validator from an OpenAPI Model
89 func NewValidatorFromV3Model(m *v3.Document, opts ...config.Option) Validator {
90 options := config.NewValidationOptions(opts...)
91
92 // Build radix tree for O(k) path lookup (where k = path depth)
93 // Skip if path tree is disabled or a custom tree was provided
94 if options.PathTree == nil && !options.IsPathTreeDisabled() {
95 options.PathTree = radix.BuildPathTree(m)
96 }
97
98 // warm the schema caches by pre-compiling all schemas in the document
99 // (warmSchemaCaches checks for nil cache and skips if disabled)
100 warmSchemaCaches(m, options)
101
102 v := &validator{options: options, v3Model: m}
103
104 // create a new parameter validator
105 v.paramValidator = parameters.NewParameterValidator(m, config.WithExistingOpts(options))
106
107 // create aq new request body validator
108 v.requestValidator = requests.NewRequestBodyValidator(m, config.WithExistingOpts(options))
109
110 // create a response body validator
111 v.responseValidator = responses.NewResponseBodyValidator(m, config.WithExistingOpts(options))
112
113 return v
114 }
115
116 func (v *validator) SetDocument(document libopenapi.Document) {
117 v.document = document
118 }
119
120 func (v *validator) GetParameterValidator() parameters.ParameterValidator {
121 return v.paramValidator
122 }
123
124 func (v *validator) GetRequestBodyValidator() requests.RequestBodyValidator {
125 return v.requestValidator
126 }
127
128 func (v *validator) GetResponseBodyValidator() responses.ResponseBodyValidator {
129 return v.responseValidator
130 }
131
132 func (v *validator) ValidateDocument() (bool, []*errors.ValidationError) {
133 if v.document == nil {
134 return false, []*errors.ValidationError{{
135 ValidationType: helpers.DocumentValidation,
136 ValidationSubType: helpers.ValidationMissing,
137 Message: "Document is not set",
138 Reason: "The document cannot be validated as it is not set",
139 SpecLine: 1,
140 SpecCol: 1,
141 HowToFix: "Set the document via `SetDocument` before validating",
142 }}
143 }
144 var validationOpts []config.Option
145 if v.options != nil {
146 validationOpts = append(validationOpts, config.WithRegexEngine(v.options.RegexEngine))
147 }
148 return schema_validation.ValidateOpenAPIDocument(v.document, validationOpts...)
149 }
150
151 func (v *validator) ValidateHttpResponse(
152 request *http.Request,
153 response *http.Response,
154 ) (bool, []*errors.ValidationError) {
155 var pathItem *v3.PathItem
156 var pathValue string
157 var errs []*errors.ValidationError
158
159 pathItem, errs, pathValue = paths.FindPath(request, v.v3Model, v.options)
160 if pathItem == nil || errs != nil {
161 return false, errs
162 }
163
164 responseBodyValidator := v.responseValidator
165
166 // validate response
167 _, responseErrors := responseBodyValidator.ValidateResponseBodyWithPathItem(request, response, pathItem, pathValue)
168
169 if len(responseErrors) > 0 {
170 return false, responseErrors
171 }
172 return true, nil
173 }
174
175 func (v *validator) ValidateHttpRequestResponse(
176 request *http.Request,
177 response *http.Response,
178 ) (bool, []*errors.ValidationError) {
179 var pathItem *v3.PathItem
180 var pathValue string
181 var errs []*errors.ValidationError
182
183 pathItem, errs, pathValue = paths.FindPath(request, v.v3Model, v.options)
184 if pathItem == nil || errs != nil {
185 return false, errs
186 }
187
188 responseBodyValidator := v.responseValidator
189
190 // validate request and response
191 _, requestErrors := v.ValidateHttpRequestWithPathItem(request, pathItem, pathValue)
192 _, responseErrors := responseBodyValidator.ValidateResponseBodyWithPathItem(request, response, pathItem, pathValue)
193
194 if len(requestErrors) > 0 || len(responseErrors) > 0 {
195 return false, append(requestErrors, responseErrors...)
196 }
197 return true, nil
198 }
199
200 func (v *validator) ValidateHttpRequest(request *http.Request) (bool, []*errors.ValidationError) {
201 pathItem, errs, foundPath := paths.FindPath(request, v.v3Model, v.options)
202 if len(errs) > 0 {
203 return false, errs
204 }
205 return v.ValidateHttpRequestWithPathItem(request, pathItem, foundPath)
206 }
207
208 func (v *validator) ValidateHttpRequestWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) {
209 // create a new parameter validator
210 paramValidator := v.paramValidator
211
212 // create a new request body validator
213 reqBodyValidator := v.requestValidator
214
215 // create some channels to handle async validation
216 doneChan := make(chan struct{})
217 errChan := make(chan []*errors.ValidationError)
218 controlChan := make(chan struct{})
219
220 // async param validation function.
221 parameterValidationFunc := func(control chan struct{}, errorChan chan []*errors.ValidationError) {
222 paramErrs := make(chan []*errors.ValidationError)
223 paramControlChan := make(chan struct{})
224 paramFunctionControlChan := make(chan struct{})
225 var paramValidationErrors []*errors.ValidationError
226
227 validations := []validationFunction{
228 paramValidator.ValidatePathParamsWithPathItem,
229 paramValidator.ValidateCookieParamsWithPathItem,
230 paramValidator.ValidateHeaderParamsWithPathItem,
231 paramValidator.ValidateQueryParamsWithPathItem,
232 paramValidator.ValidateSecurityWithPathItem,
233 }
234
235 // listen for validation errors on parameters. everything will run async.
236 paramListener := func(control chan struct{}, errorChan chan []*errors.ValidationError) {
237 completedValidations := 0
238 for {
239 select {
240 case vErrs := <-errorChan:
241 paramValidationErrors = append(paramValidationErrors, vErrs...)
242 case <-control:
243 completedValidations++
244 if completedValidations == len(validations) {
245 paramFunctionControlChan <- struct{}{}
246 return
247 }
248 }
249 }
250 }
251
252 validateParamFunction := func(
253 control chan struct{},
254 errorChan chan []*errors.ValidationError,
255 validatorFunc validationFunction,
256 ) {
257 valid, pErrs := validatorFunc(request, pathItem, pathValue)
258 if !valid {
259 errorChan <- pErrs
260 }
261 control <- struct{}{}
262 }
263 go paramListener(paramControlChan, paramErrs)
264 for i := range validations {
265 go validateParamFunction(paramControlChan, paramErrs, validations[i])
266 }
267
268 // wait for all the validations to complete
269 <-paramFunctionControlChan
270 if len(paramValidationErrors) > 0 {
271 errorChan <- paramValidationErrors
272 }
273
274 // let runValidation know we are done with this part.
275 controlChan <- struct{}{}
276 }
277
278 requestBodyValidationFunc := func(control chan struct{}, errorChan chan []*errors.ValidationError) {
279 valid, pErrs := reqBodyValidator.ValidateRequestBodyWithPathItem(request, pathItem, pathValue)
280 if !valid {
281 errorChan <- pErrs
282 }
283 control <- struct{}{}
284 }
285
286 // build async functions
287 asyncFunctions := []validationFunctionAsync{
288 parameterValidationFunc,
289 requestBodyValidationFunc,
290 }
291
292 var validationErrors []*errors.ValidationError
293
294 // sit and wait for everything to report back.
295 go runValidation(controlChan, doneChan, errChan, &validationErrors, len(asyncFunctions))
296
297 // run async functions
298 for i := range asyncFunctions {
299 go asyncFunctions[i](controlChan, errChan)
300 }
301
302 // wait for all the validations to complete
303 <-doneChan
304
305 // sort errors for deterministic ordering (async validation can return errors in any order)
306 sortValidationErrors(validationErrors)
307
308 return len(validationErrors) == 0, validationErrors
309 }
310
311 func (v *validator) ValidateHttpRequestSync(request *http.Request) (bool, []*errors.ValidationError) {
312 pathItem, errs, foundPath := paths.FindPath(request, v.v3Model, v.options)
313 if len(errs) > 0 {
314 return false, errs
315 }
316 return v.ValidateHttpRequestSyncWithPathItem(request, pathItem, foundPath)
317 }
318
319 func (v *validator) ValidateHttpRequestSyncWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) {
320 // create a new parameter validator
321 paramValidator := v.paramValidator
322
323 // create a new request body validator
324 reqBodyValidator := v.requestValidator
325
326 validationErrors := make([]*errors.ValidationError, 0)
327
328 paramValidationErrors := make([]*errors.ValidationError, 0)
329 for _, validateFunc := range []validationFunction{
330 paramValidator.ValidatePathParamsWithPathItem,
331 paramValidator.ValidateCookieParamsWithPathItem,
332 paramValidator.ValidateHeaderParamsWithPathItem,
333 paramValidator.ValidateQueryParamsWithPathItem,
334 paramValidator.ValidateSecurityWithPathItem,
335 } {
336 valid, pErrs := validateFunc(request, pathItem, pathValue)
337 if !valid {
338 paramValidationErrors = append(paramValidationErrors, pErrs...)
339 }
340 }
341
342 valid, pErrs := reqBodyValidator.ValidateRequestBodyWithPathItem(request, pathItem, pathValue)
343 if !valid {
344 paramValidationErrors = append(paramValidationErrors, pErrs...)
345 }
346
347 validationErrors = append(validationErrors, paramValidationErrors...)
348 return len(validationErrors) == 0, validationErrors
349 }
350
351 type validator struct {
352 options *config.ValidationOptions
353 v3Model *v3.Document
354 document libopenapi.Document
355 paramValidator parameters.ParameterValidator
356 requestValidator requests.RequestBodyValidator
357 responseValidator responses.ResponseBodyValidator
358 }
359
360 func runValidation(control, doneChan chan struct{},
361 errorChan chan []*errors.ValidationError,
362 validationErrors *[]*errors.ValidationError,
363 total int,
364 ) {
365 var validationLock sync.Mutex
366 completedValidations := 0
367 for {
368 select {
369 case vErrs := <-errorChan:
370 validationLock.Lock()
371 *validationErrors = append(*validationErrors, vErrs...)
372 validationLock.Unlock()
373 case <-control:
374 completedValidations++
375 if completedValidations == total {
376 doneChan <- struct{}{}
377 return
378 }
379 }
380 }
381 }
382
383 type (
384 validationFunction func(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError)
385 validationFunctionAsync func(control chan struct{}, errorChan chan []*errors.ValidationError)
386 )
387
388 // sortValidationErrors sorts validation errors for deterministic ordering.
389 // Errors are sorted by validation type first, then by message.
390 func sortValidationErrors(errs []*errors.ValidationError) {
391 sort.Slice(errs, func(i, j int) bool {
392 if errs[i].ValidationType != errs[j].ValidationType {
393 return errs[i].ValidationType < errs[j].ValidationType
394 }
395 return errs[i].Message < errs[j].Message
396 })
397 }
398
399 // warmSchemaCaches pre-compiles all schemas in the OpenAPI document and stores them in the validator caches.
400 // This frontloads the compilation cost so that runtime validation doesn't need to compile schemas.
401 func warmSchemaCaches(
402 doc *v3.Document,
403 options *config.ValidationOptions,
404 ) {
405 // Skip warming if cache is nil (explicitly disabled via WithSchemaCache(nil))
406 if doc == nil || doc.Paths == nil || doc.Paths.PathItems == nil || options.SchemaCache == nil {
407 return
408 }
409
410 schemaCache := options.SchemaCache
411
412 // Walk through all paths and operations
413 for pathPair := doc.Paths.PathItems.First(); pathPair != nil; pathPair = pathPair.Next() {
414 pathItem := pathPair.Value()
415
416 // Get all operations for this path (handles all HTTP methods including OpenAPI 3.2+ extensions)
417 operations := pathItem.GetOperations()
418 if operations == nil {
419 continue
420 }
421
422 for opPair := operations.First(); opPair != nil; opPair = opPair.Next() {
423 operation := opPair.Value()
424 if operation == nil {
425 continue
426 }
427
428 // Warm request body schemas
429 if operation.RequestBody != nil && operation.RequestBody.Content != nil {
430 for contentPair := operation.RequestBody.Content.First(); contentPair != nil; contentPair = contentPair.Next() {
431 mediaType := contentPair.Value()
432 if mediaType.Schema != nil {
433 warmMediaTypeSchema(mediaType, schemaCache, options)
434 }
435 }
436 }
437
438 // Warm response body schemas
439 if operation.Responses != nil {
440 // Warm status code responses
441 if operation.Responses.Codes != nil {
442 for codePair := operation.Responses.Codes.First(); codePair != nil; codePair = codePair.Next() {
443 response := codePair.Value()
444 if response != nil && response.Content != nil {
445 for contentPair := response.Content.First(); contentPair != nil; contentPair = contentPair.Next() {
446 mediaType := contentPair.Value()
447 if mediaType.Schema != nil {
448 warmMediaTypeSchema(mediaType, schemaCache, options)
449 }
450 }
451 }
452 }
453 }
454
455 // Warm default response schemas
456 if operation.Responses.Default != nil && operation.Responses.Default.Content != nil {
457 for contentPair := operation.Responses.Default.Content.First(); contentPair != nil; contentPair = contentPair.Next() {
458 mediaType := contentPair.Value()
459 if mediaType.Schema != nil {
460 warmMediaTypeSchema(mediaType, schemaCache, options)
461 }
462 }
463 }
464 }
465
466 // Warm parameter schemas
467 if operation.Parameters != nil {
468 for _, param := range operation.Parameters {
469 if param != nil {
470 warmParameterSchema(param, schemaCache, options)
471 }
472 }
473 }
474 }
475
476 // Warm path-level parameters
477 if pathItem.Parameters != nil {
478 for _, param := range pathItem.Parameters {
479 if param != nil {
480 warmParameterSchema(param, schemaCache, options)
481 }
482 }
483 }
484 }
485 }
486
487 // warmMediaTypeSchema warms the cache for a media type schema
488 func warmMediaTypeSchema(mediaType *v3.MediaType, schemaCache cache.SchemaCache, options *config.ValidationOptions) {
489 if mediaType != nil && mediaType.Schema != nil {
490 hash := mediaType.GoLow().Schema.Value.Hash()
491
492 if _, exists := schemaCache.Load(hash); !exists {
493 schema := mediaType.Schema.Schema()
494 if schema != nil {
495 renderCtx := base.NewInlineRenderContextForValidation()
496 renderedInline, _ := schema.RenderInlineWithContext(renderCtx)
497 referenceSchema := string(renderedInline)
498 renderedJSON, _ := utils.ConvertYAMLtoJSON(renderedInline)
499 if len(renderedInline) > 0 {
500 compiledSchema, _ := helpers.NewCompiledSchema(fmt.Sprintf("%x", hash), renderedJSON, options)
501
502 // Pre-parse YAML node for error reporting (avoids re-parsing on each error)
503 var renderedNode yaml.Node
504 _ = yaml.Unmarshal(renderedInline, &renderedNode)
505
506 schemaCache.Store(hash, &cache.SchemaCacheEntry{
507 Schema: schema,
508 RenderedInline: renderedInline,
509 ReferenceSchema: referenceSchema,
510 RenderedJSON: renderedJSON,
511 CompiledSchema: compiledSchema,
512 RenderedNode: &renderedNode,
513 })
514 }
515 }
516 }
517 }
518 }
519
520 // warmParameterSchema warms the cache for a parameter schema
521 func warmParameterSchema(param *v3.Parameter, schemaCache cache.SchemaCache, options *config.ValidationOptions) {
522 if param != nil {
523 var schema *base.Schema
524 var hash uint64
525
526 // Parameters can have schemas in two places: schema property or content property
527 if param.Schema != nil {
528 schema = param.Schema.Schema()
529 if schema != nil {
530 hash = param.GoLow().Schema.Value.Hash()
531 }
532 } else if param.Content != nil {
533 // Check content for schema
534 for contentPair := param.Content.First(); contentPair != nil; contentPair = contentPair.Next() {
535 mediaType := contentPair.Value()
536 if mediaType.Schema != nil {
537 schema = mediaType.Schema.Schema()
538 if schema != nil {
539 hash = mediaType.GoLow().Schema.Value.Hash()
540 }
541 break // Only process first content type
542 }
543 }
544 }
545
546 if schema != nil {
547 if _, exists := schemaCache.Load(hash); !exists {
548 renderCtx := base.NewInlineRenderContextForValidation()
549 renderedInline, _ := schema.RenderInlineWithContext(renderCtx)
550 referenceSchema := string(renderedInline)
551 renderedJSON, _ := utils.ConvertYAMLtoJSON(renderedInline)
552 if len(renderedInline) > 0 {
553 compiledSchema, _ := helpers.NewCompiledSchema(fmt.Sprintf("%x", hash), renderedJSON, options)
554
555 // Pre-parse YAML node for error reporting (avoids re-parsing on each error)
556 var renderedNode yaml.Node
557 _ = yaml.Unmarshal(renderedInline, &renderedNode)
558
559 // Store in cache using the shared SchemaCache type
560 schemaCache.Store(hash, &cache.SchemaCacheEntry{
561 Schema: schema,
562 RenderedInline: renderedInline,
563 ReferenceSchema: referenceSchema,
564 RenderedJSON: renderedJSON,
565 CompiledSchema: compiledSchema,
566 RenderedNode: &renderedNode,
567 })
568 }
569 }
570 }
571 }
572 }