Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions helpers/operation_utilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
}
Expand Down
66 changes: 30 additions & 36 deletions helpers/parameter_utilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now hands back the operation's own Parameters slice when there are no path level params. Everything in the repo only reads the result, so we're fine internally. It's exported though, so I'd add a line to the doc comment saying the result is read-only. Otherwise someone appends to it and writes straight into the shared model.

}
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.
Expand Down
104 changes: 104 additions & 0 deletions helpers/parameter_utilities_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch on the backing array. Concurrent GET and POST requests on the same path item could stomp on each other's parameter lists, which is a properly sneaky bug.

The test can't see it though. item.Parameters here has len == cap, so the old append reallocates and passes too. Revert the fix and this test stays green. Build it with spare capacity, something like make([]*v3.Parameter, 1, 4), then check the slot past len is untouched.

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)
}
28 changes: 22 additions & 6 deletions helpers/regex_maker.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
// SPDX-License-Identifier: MIT

package helpers

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiny one: this file is missing the standard copyright header. Worth adding while you're in here.


import (
"bytes"
"fmt"
"regexp"
"strings"
Expand All @@ -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.
//
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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(')')

}

Expand Down
Loading
Loading