diff --git a/config/config.go b/config/config.go index f5aae1c..1de5af9 100644 --- a/config/config.go +++ b/config/config.go @@ -159,6 +159,11 @@ func (o *ValidationOptions) Release() { releaseIfSupported(o.SchemaCache) releaseIfSupported(o.SchemaResourceCache) releaseIfSupported(o.PathTree) + // the default per-validator regex cache is owned by these options; + // empty it so a Release frees the compiled regexes eagerly. + if cache, ok := o.RegexCache.(interface{ Clear() }); ok { + cache.Clear() + } } o.RegexEngine = nil diff --git a/helpers/operation_utilities.go b/helpers/operation_utilities.go index b66030a..5d90373 100644 --- a/helpers/operation_utilities.go +++ b/helpers/operation_utilities.go @@ -12,6 +12,10 @@ import ( // ExtractOperation extracts the operation from the path item based on the request method. If there is no // matching operation found, then nil is returned. +// +// HEAD requests fall back to the get operation, matching router behavior. +// QUERY (OpenAPI 3.2) and methods declared under additionalOperations are +// resolved as well. func ExtractOperation(request *http.Request, item *v3.PathItem) *v3.Operation { switch request.Method { case http.MethodGet: @@ -33,6 +37,13 @@ func ExtractOperation(request *http.Request, item *v3.PathItem) *v3.Operation { return item.Patch case http.MethodTrace: return item.Trace + case "QUERY": + return item.Query + } + if item.AdditionalOperations != nil { + if additional, found := item.AdditionalOperations.Get(request.Method); found { + return additional + } } return nil } diff --git a/helpers/parameter_utilities.go b/helpers/parameter_utilities.go index 9111819..9832ca5 100644 --- a/helpers/parameter_utilities.go +++ b/helpers/parameter_utilities.go @@ -29,7 +29,11 @@ type QueryParam struct { // ExtractRawQueryValues parses a URL's RawQuery into a map of decoded key to raw // (still percent-encoded) values, index-aligned per key with request.URL.Query(). +// A query without parameters returns nil. func ExtractRawQueryValues(rawQuery string) map[string][]string { + if rawQuery == "" { + return nil + } rawValues := make(map[string][]string) for rawQuery != "" { var segment string @@ -52,43 +56,33 @@ func ExtractRawQueryValues(rawQuery string) map[string][]string { // ExtractParamsForOperation will extract the parameters for the operation based on the request method. // Both the path level params and the method level params will be returned. +// +// Method resolution matches ExtractOperation: HEAD falls back to get, and +// QUERY (OpenAPI 3.2) plus additionalOperations methods are resolved. +// +// The result may alias the model's own parameter slices: treat it as +// read-only. Appending to it can write into the shared model backing array. func ExtractParamsForOperation(request *http.Request, item *v3.PathItem) []*v3.Parameter { - params := item.Parameters - switch request.Method { - case http.MethodGet: - if item.Get != nil { - params = append(params, item.Get.Parameters...) - } - case http.MethodPost: - if item.Post != nil { - params = append(params, item.Post.Parameters...) - } - case http.MethodPut: - if item.Put != nil { - params = append(params, item.Put.Parameters...) - } - case http.MethodDelete: - if item.Delete != nil { - params = append(params, item.Delete.Parameters...) - } - case http.MethodOptions: - if item.Options != nil { - params = append(params, item.Options.Parameters...) - } - case http.MethodHead: - if item.Head != nil { - params = append(params, item.Head.Parameters...) - } - case http.MethodPatch: - if item.Patch != nil { - params = append(params, item.Patch.Parameters...) - } - case http.MethodTrace: - if item.Trace != nil { - params = append(params, item.Trace.Parameters...) - } - } - return params + // delegate to ExtractOperation so method resolution stays in sync with + // the router: HEAD falls back to get, QUERY and additionalOperations + // are resolved. + var operationParams []*v3.Parameter + if operation := ExtractOperation(request, item); operation != nil { + operationParams = operation.Parameters + } + + // Return the model slices untouched when one side is empty: appending to + // item.Parameters can write into the model backing array, and the model + // stays shared across validators and requests. + if len(operationParams) == 0 { + return item.Parameters + } + if len(item.Parameters) == 0 { + return operationParams + } + merged := make([]*v3.Parameter, 0, len(item.Parameters)+len(operationParams)) + merged = append(merged, item.Parameters...) + return append(merged, operationParams...) } // ExtractSecurityForOperation will extract the security requirements for the operation based on the request method. diff --git a/helpers/parameter_utilities_test.go b/helpers/parameter_utilities_test.go index 6a450c8..75be490 100644 --- a/helpers/parameter_utilities_test.go +++ b/helpers/parameter_utilities_test.go @@ -1430,3 +1430,107 @@ func TestExtractRawQueryValues(t *testing.T) { "novalue": {""}, }, raw) } + +func TestExtractRawQueryValuesEmptyQuery(t *testing.T) { + require.Nil(t, ExtractRawQueryValues("")) +} + +func TestExtractParamsForOperationOneSideEmpty(t *testing.T) { + operationOnly := &v3.Parameter{Name: "id", In: Path} + + t.Run("no path level parameters returns the operation slice itself", func(t *testing.T) { + item := &v3.PathItem{Get: &v3.Operation{Parameters: []*v3.Parameter{operationOnly}}} + got := ExtractParamsForOperation(&http.Request{Method: http.MethodGet}, item) + require.Equal(t, []*v3.Parameter{operationOnly}, got) + // the operation's own slice is handed back, not a copy + require.Same(t, &got[0], &item.Get.Parameters[0]) + }) + + t.Run("no operation parameters returns path slice untouched", func(t *testing.T) { + item := &v3.PathItem{Parameters: []*v3.Parameter{operationOnly}, Get: &v3.Operation{}} + got := ExtractParamsForOperation(&http.Request{Method: http.MethodGet}, item) + require.Equal(t, []*v3.Parameter{operationOnly}, got) + // the path level slice is returned as-is, not copied + require.Same(t, &got[0], &item.Parameters[0]) + }) + + t.Run("both sides merge without writing into the model slice", func(t *testing.T) { + pathLevel := &v3.Parameter{Name: "shared", In: Path} + operationLevel := &v3.Parameter{Name: "id", In: Path} + // spare capacity: with len == cap the old append into the model + // slice reallocated and this test could not see the bug + item := &v3.PathItem{ + Parameters: make([]*v3.Parameter, 1, 4), + Get: &v3.Operation{Parameters: []*v3.Parameter{operationLevel}}, + } + item.Parameters[0] = pathLevel + + got := ExtractParamsForOperation(&http.Request{Method: http.MethodGet}, item) + + require.Equal(t, []*v3.Parameter{pathLevel, operationLevel}, got) + // the model slice keeps its own length, and the capacity slot past + // its length stays empty: the old append wrote the merged result + // straight into the model backing array + require.Len(t, item.Parameters, 1) + require.Equal(t, pathLevel, item.Parameters[0]) + require.Nil(t, item.Parameters[1:cap(item.Parameters)][0]) + }) +} + +// The tests below pin the pre-existing gaps flagged in the PR 340 review. +// They assert the CURRENT behavior; the fixes flip the assertions. + +var yesVar = true + +func TestExtractParamsForOperationHeadFallsBackToGet(t *testing.T) { + // ExtractOperation falls back to get for HEAD, so a HEAD request is + // validated as the GET operation. ExtractParamsForOperation makes the + // same fallback, so GET's required query and header parameters are + // checked for HEAD requests too. + item := &v3.PathItem{ + Get: &v3.Operation{Parameters: []*v3.Parameter{{Name: "limit", In: Query, Required: &yesVar}}}, + Head: nil, + } + + request, _ := http.NewRequest(http.MethodHead, "/reports", nil) + + // the router and ExtractOperation resolve HEAD to the get operation + require.Same(t, item.Get, ExtractOperation(request, item)) + + // and the extracted parameters now carry the get operation's parameters + got := ExtractParamsForOperation(request, item) + require.Len(t, got, 1) + require.Equal(t, "limit", got[0].Name) +} + +func TestExtractParamsForOperationQueryOperation(t *testing.T) { + // OpenAPI 3.2 query operations carry their own parameters, and QUERY + // requests resolve to them. + queryOperation := &v3.Operation{Parameters: []*v3.Parameter{{Name: "limit", In: Query, Required: &yesVar}}} + item := &v3.PathItem{Query: queryOperation} + + request, _ := http.NewRequest("QUERY", "/search", nil) + + require.Same(t, queryOperation, ExtractOperation(request, item)) + + got := ExtractParamsForOperation(request, item) + require.Len(t, got, 1, "query operation parameters should be extracted for QUERY requests") + require.Equal(t, "limit", got[0].Name) +} + +func TestExtractParamsForOperationAdditionalOperations(t *testing.T) { + // the router resolves AdditionalOperations, and method extraction now + // resolves custom methods as well. + custom := &v3.Operation{Parameters: []*v3.Parameter{{Name: "range", In: Query, Required: &yesVar}}} + item := &v3.PathItem{} + item.AdditionalOperations = orderedmap.New[string, *v3.Operation]() + item.AdditionalOperations.Set("CUSTOM", custom) + + request, _ := http.NewRequest("CUSTOM", "/search", nil) + + require.Same(t, custom, ExtractOperation(request, item)) + + got := ExtractParamsForOperation(request, item) + require.Len(t, got, 1, "additional operation parameters should be extracted for custom methods") + require.Equal(t, "range", got[0].Name) +} diff --git a/helpers/regex_maker.go b/helpers/regex_maker.go index 3fcbc2e..d9926ea 100644 --- a/helpers/regex_maker.go +++ b/helpers/regex_maker.go @@ -1,7 +1,9 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: MIT + package helpers import ( - "bytes" "fmt" "regexp" "strings" @@ -26,6 +28,10 @@ var ( // The function ensures that the template is well-formed, with balanced and properly // nested braces. If the template is invalid, an error is returned. // +// The function holds no state: every call compiles the template again. Validators +// cache compiled regexes per validator in config.ValidationOptions.RegexCache; +// set config.WithRegexCache to share or supply a cache. +// // Parameters: // - tpl: The path template string to convert into a regular expression. // @@ -39,6 +45,12 @@ var ( // // regex: ^/orders/([0-9]+)/items/([^/]+)$ // // err: nil func GetRegexForPath(tpl string) (*regexp.Regexp, error) { + return compilePathRegex(tpl) +} + +// compilePathRegex builds and compiles a regular expression for the given +// path template. +func compilePathRegex(tpl string) (*regexp.Regexp, error) { // Check if it is well-formed. idxs, errBraces := BraceIndices(tpl) if errBraces != nil { @@ -48,7 +60,11 @@ func GetRegexForPath(tpl string) (*regexp.Regexp, error) { // Backup the original. template := tpl - pattern := bytes.NewBufferString("^") + // strings.Builder writes cannot fail: the builder grows on demand and + // panics on overflow instead of returning an error, so the pattern is + // assembled with plain writes and no error checks. + var pattern strings.Builder + pattern.WriteString("^") var end int for i := 0; i < len(idxs); i += 2 { @@ -69,10 +85,10 @@ func GetRegexForPath(tpl string) (*regexp.Regexp, error) { } // Build the regexp pattern. - _, err := fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt) - if err != nil { - return nil, err - } + pattern.WriteString(regexp.QuoteMeta(raw)) + pattern.WriteByte('(') + pattern.WriteString(patt) + pattern.WriteByte(')') } diff --git a/helpers/regex_maker_bench_test.go b/helpers/regex_maker_bench_test.go new file mode 100644 index 0000000..27700af --- /dev/null +++ b/helpers/regex_maker_bench_test.go @@ -0,0 +1,122 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: MIT + +package helpers + +import ( + "fmt" + "regexp" + "sync" + "sync/atomic" + "testing" +) + +// benchTemplates covers the path template shapes this library sees in real specs. +var benchTemplates = []struct { + name string + tpl string +}{ + {"no_params", "/health/live"}, + {"one_default_param", "/users/{id}"}, + {"one_custom_pattern", "/users/{id:[0-9a-f-]{36}}"}, + {"many_params", "/orgs/{org}/repos/{repo}/pulls/{pull}/files/{file}"}, + {"odata_style", "/entities('{id}')"}, +} + +// BenchmarkGetRegexForPath measures the stateless compile: every call +// compiles the template again. Validators avoid this with the per-validator +// regex cache, so this benchmark shows the cost the cache removes. +func BenchmarkGetRegexForPath(b *testing.B) { + for _, bc := range benchTemplates { + b.Run(bc.name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + r, err := GetRegexForPath(bc.tpl) + if err != nil { + b.Fatalf("unexpected error for %q: %v", bc.tpl, err) + } + if r == nil { + b.Fatalf("nil regex for %q", bc.tpl) + } + } + }) + } +} + +// BenchmarkGetRegexForPathCached measures the cached path with the same +// sync.Map shape the validator defaults to: a hit returns the stored regex. +func BenchmarkGetRegexForPathCached(b *testing.B) { + for _, bc := range benchTemplates { + b.Run(bc.name, func(b *testing.B) { + var cache sync.Map + seed, err := GetRegexForPath(bc.tpl) + if err != nil { + b.Fatalf("unexpected error for %q: %v", bc.tpl, err) + } + cache.Store(bc.tpl, seed) + + b.ReportAllocs() + for b.Loop() { + cached, found := cache.Load(bc.tpl) + if !found { + b.Fatalf("expected a cached regex for %q", bc.tpl) + } + if cached.(*regexp.Regexp) == nil { + b.Fatalf("nil regex for %q", bc.tpl) + } + } + }) + } +} + +// coldCounter hands every cold-benchmark iteration a template that no earlier +// iteration in this process used, so each call is a cache miss. +var coldCounter atomic.Int64 + +// BenchmarkGetRegexForPathCold measures a compile of a unique template on +// every iteration. It shows the cost the per-validator cache removes from +// the repeat path, and the fixed overhead a miss keeps. +func BenchmarkGetRegexForPathCold(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + tpl := fmt.Sprintf("/users/%d/{id}", coldCounter.Add(1)) + if _, err := GetRegexForPath(tpl); err != nil { + b.Fatalf("unexpected error for %q: %v", tpl, err) + } + } +} + +// BenchmarkGetRegexForPathParallel hammers a small, stable template set from +// many goroutines through a shared per-validator-shaped cache, which is what +// a request-validation hot path looks like. +func BenchmarkGetRegexForPathParallel(b *testing.B) { + templates := []string{ + "/users/{id}", + "/users/{id:[0-9a-f-]{36}}", + "/orgs/{org}/repos/{repo}", + "/health/live", + } + var cache sync.Map + for _, tpl := range templates { + seed, err := GetRegexForPath(tpl) + if err != nil { + b.Fatalf("unexpected error for %q: %v", tpl, err) + } + cache.Store(tpl, seed) + } + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := 0 + for pb.Next() { + tpl := templates[i%len(templates)] + if cached, found := cache.Load(tpl); found { + _ = cached.(*regexp.Regexp) + } else { + if _, err := GetRegexForPath(tpl); err != nil { + b.Fatalf("unexpected error for %q: %v", tpl, err) + } + } + i++ + } + }) +} diff --git a/helpers/regex_maker_test.go b/helpers/regex_maker_test.go index 99315d1..6e37065 100644 --- a/helpers/regex_maker_test.go +++ b/helpers/regex_maker_test.go @@ -144,6 +144,18 @@ func TestDefaultPatternCompileCache(t *testing.T) { assert.Equal(t, res.String(), DefaultPatternRegexString) } +// TestGetRegexForPathHoldsNoState pins the stateless contract: repeated +// calls for one template each compile fresh regexes. Validators cache +// compiled regexes per validator in config.ValidationOptions.RegexCache. +func TestGetRegexForPathHoldsNoState(t *testing.T) { + first, errFirst := GetRegexForPath("/stateless/{id}") + second, errSecond := GetRegexForPath("/stateless/{id}") + + assert.NoError(t, errFirst) + assert.NoError(t, errSecond) + assert.NotSame(t, first, second, "expected a fresh compile per call") +} + func equal(a, b []int) bool { if len(a) != len(b) { return false @@ -155,3 +167,16 @@ func equal(a, b []int) bool { } return true } + +func TestGetRegexForPathInvalidCustomPattern(t *testing.T) { + // an unterminated character class fails regexp compilation + _, err := GetRegexForPath("/x/{id:[a-z}") + assert.Error(t, err) +} + +func TestGetRegexForPathCapturingGroupRejected(t *testing.T) { + // capturing groups in custom patterns are rejected + _, err := GetRegexForPath("/x/{id:(abc)}") + assert.Error(t, err) + assert.Contains(t, err.Error(), "capture groups") +} diff --git a/libopenapi-validator.test b/libopenapi-validator.test new file mode 100755 index 0000000..f26f1f2 Binary files /dev/null and b/libopenapi-validator.test differ diff --git a/parameters/parameters.go b/parameters/parameters.go index db57cfa..3e92b88 100644 --- a/parameters/parameters.go +++ b/parameters/parameters.go @@ -5,11 +5,13 @@ package parameters import ( "net/http" + "sync" v3 "github.com/pb33f/libopenapi/datamodel/high/v3" "github.com/pb33f/libopenapi-validator/config" "github.com/pb33f/libopenapi-validator/errors" + "github.com/pb33f/libopenapi-validator/helpers" ) // ParameterValidator is an interface that defines the methods for validating parameters @@ -79,6 +81,24 @@ func NewParameterValidator(document *v3.Document, opts ...config.Option) Paramet type paramValidator struct { options *config.ValidationOptions document *v3.Document + // braceIdxCache stores the brace indices of path templates seen by this + // validator. Entries live for the life of the validator and die with it, + // so Release needs no explicit clear. + braceIdxCache sync.Map +} + +// braceIndicesFor returns the brace indices of a path template, cached for +// the life of this validator. Invalid templates stay uncached. +func (p *paramValidator) braceIndicesFor(template string) ([]int, error) { + if cached, ok := p.braceIdxCache.Load(template); ok { + return cached.([]int), nil + } + idxs, err := helpers.BraceIndices(template) + if err != nil { + return nil, err + } + p.braceIdxCache.LoadOrStore(template, idxs) + return idxs, nil } func (p *paramValidator) Release() { diff --git a/parameters/path_parameters.go b/parameters/path_parameters.go index d676a10..454f567 100644 --- a/parameters/path_parameters.go +++ b/parameters/path_parameters.go @@ -10,6 +10,7 @@ import ( "regexp" "strconv" "strings" + "sync" "github.com/pb33f/libopenapi/datamodel/high/base" @@ -62,6 +63,14 @@ func (v *paramValidator) ValidatePathParamsWithPathItem(request *http.Request, p // extract params for the operation params := helpers.ExtractParamsForOperation(request, pathItem) validationErrors := v.validateContentParameters(request, pathItem, pathValue, helpers.Path) + + // the default regex cache is a *sync.Map: calling it concretely keeps + // the template key off the heap on every lookup. A custom cache keeps + // the interface path. + var syncRegexCache *sync.Map + if v.options != nil { + syncRegexCache, _ = v.options.RegexCache.(*sync.Map) + } for _, p := range params { if p.In == helpers.Path && p.Schema != nil { // a mismatch in segment counts means the submitted path cannot be @@ -77,7 +86,11 @@ func (v *paramValidator) ValidatePathParamsWithPathItem(request *http.Request, p for x := range pathSegments { var rgx *regexp.Regexp - if v.options.RegexCache != nil { + if syncRegexCache != nil { + if cachedRegex, found := syncRegexCache.Load(pathSegments[x]); found { + rgx = cachedRegex.(*regexp.Regexp) + } + } else if v.options != nil && v.options.RegexCache != nil { if cachedRegex, found := v.options.RegexCache.Load(pathSegments[x]); found { rgx = cachedRegex.(*regexp.Regexp) } @@ -92,7 +105,10 @@ func (v *paramValidator) ValidatePathParamsWithPathItem(request *http.Request, p rgx = r - if v.options.RegexCache != nil { + switch { + case syncRegexCache != nil: + syncRegexCache.Store(pathSegments[x], r) + case v.options != nil && v.options.RegexCache != nil: v.options.RegexCache.Store(pathSegments[x], r) } } @@ -115,7 +131,7 @@ func (v *paramValidator) ValidatePathParamsWithPathItem(request *http.Request, p matches = matches[1:] // Check if it is well-formed. - idxs, errBraces := helpers.BraceIndices(pathSegments[x]) + idxs, errBraces := v.braceIndicesFor(pathSegments[x]) if errBraces != nil { continue } @@ -442,14 +458,14 @@ func segmentReferencesParam(segment, name string) bool { // nonEmptyPathSegments splits a path on "/" and drops empty segments, so that // leading, trailing, or repeated slashes do not introduce empty entries that // would shift index alignment between submitted and template segments. +// One pass with an iterator: strings.Split would allocate the raw slice and +// copy the non-empty entries into a second slice. func nonEmptyPathSegments(path string) []string { - raw := strings.Split(path, helpers.Slash) - segments := make([]string, 0, len(raw)) - for _, segment := range raw { - if segment == "" { - continue + segments := make([]string, 0, strings.Count(path, helpers.Slash)+1) + for segment := range strings.SplitSeq(path, helpers.Slash) { + if segment != "" { + segments = append(segments, segment) } - segments = append(segments, segment) } return segments } diff --git a/parameters/path_parameters_test.go b/parameters/path_parameters_test.go index 0d3ac51..eb5e576 100644 --- a/parameters/path_parameters_test.go +++ b/parameters/path_parameters_test.go @@ -5,6 +5,7 @@ package parameters import ( "net/http" + "regexp" "sync" "sync/atomic" "testing" @@ -2528,3 +2529,38 @@ paths: assert.Empty(t, validationErrors, tc.mode) } } + +// TestValidatePathParamsWithPathItem_SkipsUnbracedSegment pins the defensive +// behavior when the user-supplied regex cache holds a regex for a segment +// with unbalanced braces: the segment regex matches, but the segment carries +// no brace indices, so validation skips it instead of mis-validating it. +func TestValidatePathParamsWithPathItem_SkipsUnbracedSegment(t *testing.T) { + spec := `openapi: 3.1.0 +paths: + /burgers/{burgerId}/locate: + parameters: + - in: path + name: burgerId + schema: + type: integer + get: + operationId: locateBurgers` + doc, _ := libopenapi.NewDocument([]byte(spec)) + m, _ := doc.BuildV3Model() + + // a regex stored under a key with unbalanced braces: GetRegexForPath + // cannot produce it, so only a user-populated cache can hit this state. + cache := &sync.Map{} + cache.Store("{oops", regexp.MustCompile(".*")) + + v := NewParameterValidator(&m.Model, config.WithRegexCache(cache)) + + request, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers/123/locate", nil) + pathItem, _, _ := paths.FindPath(request, &m.Model, nil) + require.NotNil(t, pathItem) + + // the crafted template adds a segment with unbalanced braces; the + // validator must skip that segment and still validate burgerId. + ok, errs := v.ValidatePathParamsWithPathItem(request, pathItem, "/burgers/{burgerId}/{oops") + assert.True(t, ok, "expected the unbraced segment to be skipped without errors: %v", errs) +} diff --git a/parameters/validate_parameter.go b/parameters/validate_parameter.go index eaec8c9..7329d61 100644 --- a/parameters/validate_parameter.go +++ b/parameters/validate_parameter.go @@ -78,6 +78,11 @@ func GetRenderedSchema(schema *base.Schema, opts *config.ValidationOptions) stri 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 { + // ReferenceSchema holds the string form of RenderedInline; return it + // instead of copying the bytes into a new string on every call. + if cached.ReferenceSchema != "" { + return cached.ReferenceSchema + } return string(cached.RenderedInline) } } diff --git a/requests/validate_body.go b/requests/validate_body.go index 5a7aa03..ff15f83 100644 --- a/requests/validate_body.go +++ b/requests/validate_body.go @@ -12,7 +12,6 @@ import ( v3 "github.com/pb33f/libopenapi/datamodel/high/v3" - "github.com/pb33f/libopenapi-validator/config" "github.com/pb33f/libopenapi-validator/content" "github.com/pb33f/libopenapi-validator/errors" "github.com/pb33f/libopenapi-validator/helpers" @@ -154,14 +153,14 @@ func (v *requestBodyValidator) ValidateRequestBodyWithPathItem(request *http.Req decoded = true validationSucceeded, validationErrors := ValidateRequestSchema(&ValidateRequestSchemaInput{ - Request: request, - Schema: schema, - Version: helpers.VersionToFloat(v.document.Version), - Options: []config.Option{config.WithExistingOpts(v.options)}, - BodyRequired: required, - DecodedValue: decodedValue, - RawBody: requestBody, - ValueDecoded: decoded, + Request: request, + Schema: schema, + Version: helpers.VersionToFloat(v.document.Version), + ValidationOptions: v.options, + BodyRequired: required, + DecodedValue: decodedValue, + RawBody: requestBody, + ValueDecoded: decoded, }) errors.PopulateValidationErrors(validationErrors, request, pathValue) diff --git a/requests/validate_request.go b/requests/validate_request.go index f5d8a9b..b218ef7 100644 --- a/requests/validate_request.go +++ b/requests/validate_request.go @@ -38,6 +38,15 @@ type ValidateRequestSchemaInput struct { DecodedValue any // Optional: A value produced by a registered body decoder RawBody []byte // Optional: Original bytes used for diagnostics with DecodedValue ValueDecoded bool // Distinguishes an explicitly decoded nil from the legacy JSON path + + // ValidationOptions carries pre-built options. When set, the function uses + // it directly and skips NewValidationOptions, which allocates fresh default + // schema caches on every call. The options are treated as read-only and + // must stay valid for the duration of the call. + // + // ValidationOptions and Options are mutually exclusive: when both are + // set, Options is ignored. + ValidationOptions *config.ValidationOptions } func setRequestBody(request *http.Request, body []byte) { @@ -53,7 +62,10 @@ func readAndResetRequestBody(request *http.Request) []byte { // 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, []*liberrors.ValidationError) { - validationOptions := config.NewValidationOptions(input.Options...) + validationOptions := input.ValidationOptions + if validationOptions == nil { + validationOptions = config.NewValidationOptions(input.Options...) + } var validationErrors []*liberrors.ValidationError var renderedSchema, jsonSchema []byte var referenceSchema string diff --git a/responses/validate_body.go b/responses/validate_body.go index d363f2f..a385dd3 100644 --- a/responses/validate_body.go +++ b/responses/validate_body.go @@ -17,7 +17,6 @@ import ( v3 "github.com/pb33f/libopenapi/datamodel/high/v3" lowv3 "github.com/pb33f/libopenapi/datamodel/low/v3" - "github.com/pb33f/libopenapi-validator/config" "github.com/pb33f/libopenapi-validator/content" "github.com/pb33f/libopenapi-validator/errors" "github.com/pb33f/libopenapi-validator/helpers" @@ -107,7 +106,7 @@ func (v *responseBodyValidator) ValidateResponseBodyWithPathItem(request *http.R if isDefault { headerCode = lowv3.DefaultLabel } - if ok, hErrs := ValidateResponseHeaders(request, response, foundResponse.Headers, pathFound, headerCode, config.WithExistingOpts(v.options)); !ok { + if ok, hErrs := validateResponseHeaders(request, response, foundResponse.Headers, pathFound, headerCode, v.options); !ok { validationErrors = append(validationErrors, hErrs...) } } @@ -161,7 +160,7 @@ func (v *responseBodyValidator) checkResponseSchema( } _, bodyErrors := ValidateResponseSchema(&ValidateResponseSchemaInput{ Request: request, Response: validationResponse, Schema: schema, - Version: helpers.VersionToFloat(v.document.Version), Options: []config.Option{config.WithExistingOpts(v.options)}, + Version: helpers.VersionToFloat(v.document.Version), ValidationOptions: v.options, }) return bodyErrors } @@ -209,14 +208,14 @@ func (v *responseBodyValidator) checkResponseSchema( // Validate response schema valid, vErrs := ValidateResponseSchema(&ValidateResponseSchemaInput{ - Request: request, - Response: response, - Schema: schema, - Version: helpers.VersionToFloat(v.document.Version), - Options: []config.Option{config.WithExistingOpts(v.options)}, - DecodedValue: decodedValue, - RawBody: responseBody, - ValueDecoded: decoded, + Request: request, + Response: response, + Schema: schema, + Version: helpers.VersionToFloat(v.document.Version), + ValidationOptions: v.options, + DecodedValue: decodedValue, + RawBody: responseBody, + ValueDecoded: decoded, }) if !valid { diff --git a/responses/validate_headers.go b/responses/validate_headers.go index f12680c..a163f3c 100644 --- a/responses/validate_headers.go +++ b/responses/validate_headers.go @@ -32,8 +32,22 @@ func ValidateResponseHeaders( statusCode string, opts ...config.Option, ) (bool, []*errors.ValidationError) { - options := config.NewValidationOptions(opts...) + return validateResponseHeaders(request, response, headers, pathTemplate, statusCode, + config.NewValidationOptions(opts...)) +} +// validateResponseHeaders holds the header validation flow for a response with +// pre-built options. Building options here would allocate fresh default schema +// caches on every call, so callers with built options pass them directly. The +// options are treated as read-only. +func validateResponseHeaders( + request *http.Request, + response *http.Response, + headers *orderedmap.Map[string, *v3.Header], + pathTemplate string, + statusCode string, + options *config.ValidationOptions, +) (bool, []*errors.ValidationError) { // locate headers type headerPair struct { name string diff --git a/responses/validate_response.go b/responses/validate_response.go index 474b0c3..d9e9edf 100644 --- a/responses/validate_response.go +++ b/responses/validate_response.go @@ -39,6 +39,15 @@ type ValidateResponseSchemaInput struct { DecodedValue any // Optional: A value produced by a registered body decoder RawBody []byte // Optional: Original bytes used for diagnostics with DecodedValue ValueDecoded bool // Distinguishes an explicitly decoded nil from the legacy JSON path + + // ValidationOptions carries pre-built options. When set, the function uses + // it directly and skips NewValidationOptions, which allocates fresh default + // schema caches on every call. The options are treated as read-only and + // must stay valid for the duration of the call. + // + // ValidationOptions and Options are mutually exclusive: when both are + // set, Options is ignored. + ValidationOptions *config.ValidationOptions } // ValidateResponseSchema will validate the response body for a http.Response pointer. The request is used to @@ -48,7 +57,10 @@ type ValidateResponseSchemaInput struct { // This function is used by the ValidateResponseBody function, but can be used independently. // The schema will be compiled from cache if available, otherwise it will be compiled and cached. func ValidateResponseSchema(input *ValidateResponseSchemaInput) (bool, []*liberrors.ValidationError) { - validationOptions := config.NewValidationOptions(input.Options...) + validationOptions := input.ValidationOptions + if validationOptions == nil { + validationOptions = config.NewValidationOptions(input.Options...) + } var validationErrors []*liberrors.ValidationError var renderedSchema []byte var referenceSchema string diff --git a/validator.go b/validator.go index c5e74ed..2887764 100644 --- a/validator.go +++ b/validator.go @@ -93,6 +93,13 @@ func NewValidatorFromV3Model(m *v3.Document, opts ...config.Option) Validator { options := config.NewValidationOptions(opts...) bodycodec.Apply(options) + // Default to a per-validator regex cache: compiled path regexes live for + // the life of the validator and Release drops them with it. A cache + // supplied through config.WithRegexCache is shared instead. + if options.RegexCache == nil { + options.RegexCache = &sync.Map{} + } + // Build radix tree for O(k) path lookup (where k = path depth) // Skip if path tree is disabled or a custom tree was provided if options.PathTree == nil && !options.IsPathTreeDisabled() { diff --git a/validator_operation_fallback_test.go b/validator_operation_fallback_test.go new file mode 100644 index 0000000..ff408fa --- /dev/null +++ b/validator_operation_fallback_test.go @@ -0,0 +1,129 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: MIT + +package validator + +import ( + "net/http" + "strings" + "testing" + + "github.com/pb33f/libopenapi" + "github.com/pb33f/testify/require" +) + +// These tests cover the operation resolution gaps flagged in the PR 340 +// review: HEAD requests fall back to get, and QUERY (OpenAPI 3.2) plus +// additionalOperations methods resolve to their own operations. The +// operation level parameters now take part in validation. + +func TestHEADRequestOnGetOnlyPathValidatesGetParameters(t *testing.T) { + spec := `openapi: 3.1.0 +info: + title: claims + version: 1.0.0 +paths: + /reports: + get: + parameters: + - name: limit + in: query + required: true + schema: + type: integer + responses: + '200': + description: ok +` + doc, err := libopenapi.NewDocument([]byte(spec)) + require.NoError(t, err) + + v, errs := NewValidator(doc) + require.Empty(t, errs) + t.Cleanup(v.Release) + + request, err := http.NewRequest(http.MethodHead, "https://things.com/reports", nil) + require.NoError(t, err) + + // HEAD is validated as the get operation, so its required query + // parameter is checked: the request without limit fails. + valid, validationErrors := v.ValidateHttpRequestSync(request) + require.False(t, valid, "expected HEAD to validate as the get operation") + found := false + for _, e := range validationErrors { + if strings.Contains(e.Error(), "limit") { + found = true + } + } + require.True(t, found, "expected a missing limit parameter error, got %v", validationErrors) +} + +func TestQueryOperationValidatesItsParameters(t *testing.T) { + spec := `openapi: 3.2.0 +info: + title: claims + version: 1.0.0 +paths: + /search: + query: + parameters: + - name: limit + in: query + required: true + schema: + type: integer + responses: + '200': + description: ok +` + doc, err := libopenapi.NewDocument([]byte(spec)) + require.NoError(t, err) + + v, errs := NewValidator(doc) + require.Empty(t, errs) + t.Cleanup(v.Release) + + request, err := http.NewRequest("QUERY", "https://things.com/search", nil) + require.NoError(t, err) + + // the query operation resolves and its required query parameter is + // checked: the request without limit fails validation. + valid, validationErrors := v.ValidateHttpRequestSync(request) + require.False(t, valid, "expected the query operation's required parameter to be enforced") + require.NotEmpty(t, validationErrors) +} + +func TestAdditionalOperationValidatesItsParameters(t *testing.T) { + spec := `openapi: 3.2.0 +info: + title: claims + version: 1.0.0 +paths: + /search: + additionalOperations: + CUSTOM: + parameters: + - name: range + in: query + required: true + schema: + type: string + responses: + '200': + description: ok +` + doc, err := libopenapi.NewDocument([]byte(spec)) + require.NoError(t, err) + + v, errs := NewValidator(doc) + require.Empty(t, errs) + t.Cleanup(v.Release) + + request, err := http.NewRequest("CUSTOM", "https://things.com/search", nil) + require.NoError(t, err) + + // the custom method's operation resolves and its required query + // parameter is checked: the request without range fails validation. + _, validationErrors := v.ValidateHttpRequestSync(request) + require.NotEmpty(t, validationErrors, "expected the custom method's required parameter to be enforced") +} diff --git a/validator_request_bench_test.go b/validator_request_bench_test.go new file mode 100644 index 0000000..303b9ee --- /dev/null +++ b/validator_request_bench_test.go @@ -0,0 +1,273 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: MIT + +package validator + +import ( + "bytes" + "io" + "net/http" + "testing" + + "github.com/pb33f/libopenapi" +) + +// requestBenchSpec holds the happy-path shapes a gateway validates: a single +// path parameter, several parameters of mixed locations, a JSON body, a +// query-heavy search operation, and an operation with enum parameters. +const requestBenchSpec = `openapi: 3.1.0 +info: + title: bench + version: 1.0.0 +paths: + /users/{id}: + get: + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: ok + headers: + X-Trace-Id: + schema: + type: string + /orders/{orderId}/items/{itemId}: + get: + parameters: + - name: orderId + in: path + required: true + schema: + type: integer + minimum: 1 + - name: itemId + in: path + required: true + schema: + type: string + pattern: '^[A-Z]{2}[0-9]{4}$' + - name: status + in: query + schema: + type: string + enum: [open, closed] + - name: X-Request-Id + in: header + required: true + schema: + type: string + format: uuid + responses: + '200': + description: ok + /burgers: + post: + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + responses: + '200': + description: ok + /search: + get: + parameters: + - name: q + in: query + required: true + schema: + type: string + - name: limit + in: query + schema: + type: integer + minimum: 1 + maximum: 100 + - name: status + in: query + schema: + type: string + enum: [open, closed, all] + - name: sort + in: query + schema: + type: string + - name: X-Channel + in: header + schema: + type: string + enum: [web, mobile] + responses: + '200': + description: ok +` + +func prepareRequestBenchValidator(b *testing.B) Validator { + b.Helper() + + doc, err := libopenapi.NewDocument([]byte(requestBenchSpec)) + if err != nil { + b.Fatalf("error creating document: %v", err) + } + + v, errs := NewValidator(doc) + if len(errs) > 0 { + b.Fatalf("errors building validator: %v", errs) + } + b.Cleanup(v.Release) + return v +} + +func benchRequest(b *testing.B, method, target string, body io.Reader) *http.Request { + b.Helper() + + req, err := http.NewRequest(method, target, body) + if err != nil { + b.Fatalf("error building request: %v", err) + } + return req +} + +// BenchmarkValidateHttpRequestSync measures one valid GET with one uuid path +// parameter through the full synchronous entry point: routing plus path, +// header, cookie and query parameter validation. +func BenchmarkValidateHttpRequestSync(b *testing.B) { + v := prepareRequestBenchValidator(b) + req := benchRequest(b, http.MethodGet, "/users/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncPathQueryHeader measures one valid GET that +// exercises routing, two path parameters, one query parameter and one header +// parameter. +func BenchmarkValidateHttpRequestSyncPathQueryHeader(b *testing.B) { + v := prepareRequestBenchValidator(b) + req := benchRequest(b, http.MethodGet, "/orders/12/items/AB1234?status=closed", nil) + req.Header.Set("X-Request-Id", "3f2504e0-4f89-11d3-9a0c-0305e82c3301") + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpResponse measures one valid 200 response for the +// /users/{id} operation: routing, response headers and response body +// validation. +func BenchmarkValidateHttpResponse(b *testing.B) { + v := prepareRequestBenchValidator(b) + req := benchRequest(b, http.MethodGet, "/users/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + + b.ReportAllocs() + + for b.Loop() { + resp := &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"X-Trace-Id": []string{"3f2504e0-4f89-11d3-9a0c-0305e82c3301"}}, + Body: http.NoBody, + } + + valid, validationErrors := v.ValidateHttpResponse(req, resp) + if !valid { + b.Fatalf("response should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncJSONBody measures one valid POST with a JSON +// body. The request is rebuilt per iteration, because validation consumes the +// body reader; the repo benchmark pattern does the same. +func BenchmarkValidateHttpRequestSyncJSONBody(b *testing.B) { + v := prepareRequestBenchValidator(b) + body := []byte(`{"name":"cheeseburger"}`) + + b.ReportAllocs() + + for b.Loop() { + req := benchRequest(b, http.MethodPost, "/burgers", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncQuery measures one valid GET with four query +// parameters and an enum header parameter, the query-heavy gateway shape. +func BenchmarkValidateHttpRequestSyncQuery(b *testing.B) { + v := prepareRequestBenchValidator(b) + req := benchRequest(b, http.MethodGet, "/search?q=burger&limit=10&status=closed&sort=price", nil) + req.Header.Set("X-Channel", "web") + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncInvalid measures one invalid GET: the +// orderId path parameter fails its integer schema. Validation reports errors, +// so this shape carries the error-construction cost by design. +func BenchmarkValidateHttpRequestSyncInvalidParam(b *testing.B) { + v := prepareRequestBenchValidator(b) + req := benchRequest(b, http.MethodGet, "/orders/not-a-number/items/AB1234?status=closed", nil) + req.Header.Set("X-Request-Id", "3f2504e0-4f89-11d3-9a0c-0305e82c3301") + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if valid || len(validationErrors) == 0 { + b.Fatalf("request should fail validation with errors, got valid=%v errors=%d", valid, len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncParallel runs the plain GET shape from many +// goroutines: a gateway shares the validator and its caches across requests. +func BenchmarkValidateHttpRequestSyncParallel(b *testing.B) { + v := prepareRequestBenchValidator(b) + + b.ReportAllocs() + + req := benchRequest(b, http.MethodGet, "/users/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } + }) +} diff --git a/validator_scenario_bench_test.go b/validator_scenario_bench_test.go new file mode 100644 index 0000000..8ddfcd0 --- /dev/null +++ b/validator_scenario_bench_test.go @@ -0,0 +1,249 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: MIT + +package validator + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/pb33f/libopenapi" + + "github.com/pb33f/libopenapi-validator/config" +) + +// The scenario specs below cover the gateway shapes the main benchmark file +// does not: format assertions, strict server matching, urlencoded bodies, +// JSON response bodies, and a large routing table. + +const formatAssertionsSpec = `openapi: 3.1.0 +info: + title: bench + version: 1.0.0 +paths: + /users/{id}: + get: + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: ok +` + +const strictServerSpec = `openapi: 3.1.0 +info: + title: bench + version: 1.0.0 +servers: + - url: https://things.com/api +paths: + /users/{id}: + get: + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: ok +` + +const urlEncodedSpec = `openapi: 3.1.0 +info: + title: bench + version: 1.0.0 +paths: + /burgers: + post: + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + type: object + required: [name] + properties: + name: + type: string + size: + type: string + responses: + '200': + description: ok +` + +const responseJSONSpec = `openapi: 3.1.0 +info: + title: bench + version: 1.0.0 +paths: + /reports/{id}: + get: + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: ok + content: + application/json: + schema: + type: object + required: [ok] + properties: + ok: + type: boolean +` + +// largeRouteSpec builds a document with count templated path items. +func largeRouteSpec(count int) string { + var spec strings.Builder + spec.WriteString(`openapi: 3.1.0 +info: + title: bench + version: 1.0.0 +paths: +`) + for i := 0; i < count; i++ { + fmt.Fprintf(&spec, " /resource-%d/{id}:\n get:\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n format: uuid\n responses:\n '200':\n description: ok\n", i) + } + return spec.String() +} + +func nopBody(body []byte) io.ReadCloser { + return io.NopCloser(bytes.NewReader(body)) +} + +// prepareScenarioValidator builds a validator for the given spec and options +// and fails the benchmark on build errors. +func prepareScenarioValidator(b *testing.B, spec string, opts ...config.Option) Validator { + b.Helper() + + doc, err := libopenapi.NewDocument([]byte(spec)) + if err != nil { + b.Fatalf("error creating document: %v", err) + } + + v, errs := NewValidator(doc, opts...) + if len(errs) > 0 { + b.Fatalf("errors building validator: %v", errs) + } + b.Cleanup(v.Release) + return v +} + +// BenchmarkValidateHttpRequestSyncFormatAssertions measures one valid GET with +// format assertions enabled, so the uuid format machinery runs on every call. +func BenchmarkValidateHttpRequestSyncFormatAssertions(b *testing.B) { + v := prepareScenarioValidator(b, formatAssertionsSpec, config.WithFormatAssertions()) + + req := benchRequest(b, http.MethodGet, "/users/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncStrictServer measures one valid GET with +// strict server matching enabled: scheme, host and base path take part in +// routing. +func BenchmarkValidateHttpRequestSyncStrictServer(b *testing.B) { + v := prepareScenarioValidator(b, strictServerSpec, config.WithStrictServerMatching()) + + req := benchRequest(b, http.MethodGet, "https://things.com/api/users/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncURLEncoded measures one valid POST with a +// form-urlencoded body. The request is rebuilt per iteration, because +// validation consumes the body reader. +func BenchmarkValidateHttpRequestSyncURLEncoded(b *testing.B) { + v := prepareScenarioValidator(b, urlEncodedSpec, config.WithURLEncodedBodyValidation()) + + body := []byte("name=cheeseburger&size=large") + + b.ReportAllocs() + + for b.Loop() { + req := benchRequest(b, http.MethodPost, "/burgers", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpResponseJSONBody measures one valid 200 response with a +// JSON body. The response is rebuilt per iteration, because validation +// consumes the body reader. +func BenchmarkValidateHttpResponseJSONBody(b *testing.B) { + v := prepareScenarioValidator(b, responseJSONSpec) + + req := benchRequest(b, http.MethodGet, "/reports/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + body := []byte(`{"ok":true}`) + + b.ReportAllocs() + + for b.Loop() { + resp := &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: nopBody(body), + } + + valid, validationErrors := v.ValidateHttpResponse(req, resp) + if !valid { + b.Fatalf("response should validate, got %d errors", len(validationErrors)) + } + } +} + +// BenchmarkValidateHttpRequestSyncLargeRoutes measures one valid request +// against a document with 200 path items, where the routing table and the +// regex fallback show their cost. +func BenchmarkValidateHttpRequestSyncLargeRoutes(b *testing.B) { + v := prepareScenarioValidator(b, largeRouteSpec(200)) + + req := benchRequest(b, http.MethodGet, "/resource-150/3f2504e0-4f89-11d3-9a0c-0305e82c3301", nil) + + b.ReportAllocs() + + for b.Loop() { + valid, validationErrors := v.ValidateHttpRequestSync(req) + if !valid { + b.Fatalf("request should validate, got %d errors", len(validationErrors)) + } + } +}