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
9 changes: 9 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ type ValidationOptions struct {
ValidateResponseStatus bool // ValidateResponseStatus rejects undocumented response status codes.
RequestDefaults bool // RequestDefaults stages and atomically applies request defaults.
StrictServerMatching bool // StrictServerMatching matches scheme, host, port, base path, and server variables.
ValidateDocumentPathParams bool // ValidateDocumentPathParams rejects documents where path templates and declared path parameters do not correspond.
bodyDecoders []content.Registration
bodyEncoders []content.EncoderRegistration
borrowedState bool
Expand Down Expand Up @@ -223,6 +224,7 @@ func WithExistingOpts(options *ValidationOptions) Option {
o.ValidateResponseStatus = options.ValidateResponseStatus
o.RequestDefaults = options.RequestDefaults
o.StrictServerMatching = options.StrictServerMatching
o.ValidateDocumentPathParams = options.ValidateDocumentPathParams
o.StrictMode = options.StrictMode
o.StrictIgnorePaths = options.StrictIgnorePaths
o.StrictIgnoredHeaders = options.StrictIgnoredHeaders
Expand Down Expand Up @@ -433,6 +435,13 @@ func WithStrictServerMatching() Option {
return func(o *ValidationOptions) { o.StrictServerMatching = true }
}

// WithPathParameterDocumentValidation enables document-level validation that each path template
// variable has a corresponding `in: path` parameter, and that every declared `in: path`
// parameter matches a template variable in the path.
func WithPathParameterDocumentValidation() Option {
return func(o *ValidationOptions) { o.ValidateDocumentPathParams = true }
}

// WithSchemaCache sets a custom cache implementation or disables caching if nil.
// Pass nil to disable schema caching and skip cache warming during validator initialization.
// The default cache is a thread-safe sync.Map wrapper.
Expand Down
3 changes: 3 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func TestNewValidationOptions_Defaults(t *testing.T) {
assert.True(t, opts.OpenAPIMode) // Default is true
assert.False(t, opts.AllowScalarCoercion) // Default is false
assert.False(t, opts.AllowXMLBodyValidation) // Default is false
assert.False(t, opts.ValidateDocumentPathParams) // Default is false
assert.False(t, opts.AllowURLEncodedBodyValidation) // Default is false
assert.False(t, opts.ValidateContentParameters)
assert.Nil(t, opts.RegexEngine)
Expand Down Expand Up @@ -236,12 +237,14 @@ func TestMultipleOptions(t *testing.T) {
WithFormatAssertions(),
WithContentAssertions(),
WithXmlBodyValidation(),
WithPathParameterDocumentValidation(),
)

assert.True(t, opts.FormatAssertions)
assert.True(t, opts.ContentAssertions)
assert.True(t, opts.SecurityValidation)
assert.True(t, opts.AllowXMLBodyValidation)
assert.True(t, opts.ValidateDocumentPathParams)
assert.True(t, opts.OpenAPIMode) // Default is true
assert.False(t, opts.AllowScalarCoercion) // Default is false
assert.Nil(t, opts.RegexEngine)
Expand Down
60 changes: 60 additions & 0 deletions schema_validation/keyed_mutex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
// SPDX-License-Identifier: MIT

package schema_validation

import "sync"

type keyedMutex struct {
mu sync.Mutex
locks map[any]*countedMutex
}

type countedMutex struct {
mu sync.Mutex
refs int
}

func newKeyedMutex() *keyedMutex {
return &keyedMutex{locks: make(map[any]*countedMutex)}
}

func (k *keyedMutex) lock(key any) {
k.mu.Lock()
cm, ok := k.locks[key]
if !ok {
cm = &countedMutex{}
k.locks[key] = cm
}
cm.refs++
k.mu.Unlock()

cm.mu.Lock()
}

func (k *keyedMutex) unlock(key any) {
k.mu.Lock()
defer k.mu.Unlock()

cm, ok := k.locks[key]
if !ok {
return
}
cm.mu.Unlock()
cm.refs--
if cm.refs == 0 {
delete(k.locks, key)
}
}

func (k *keyedMutex) do(key any, fn func()) {
k.lock(key)
defer k.unlock(key)
fn()
}

func (k *keyedMutex) len() int {
k.mu.Lock()
defer k.mu.Unlock()
return len(k.locks)
}
150 changes: 150 additions & 0 deletions schema_validation/keyed_mutex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
// SPDX-License-Identifier: MIT

package schema_validation

import (
"sync"
"testing"
"time"

"github.com/pb33f/testify/assert"
"github.com/pb33f/testify/require"
)

func TestKeyedMutex_SameKeyIsMutuallyExclusive(t *testing.T) {
km := newKeyedMutex()

const goroutines = 50
const perGoroutine = 200
counters := map[string]*int{"x": new(int), "y": new(int)}

var wg sync.WaitGroup
for i := range goroutines {
key := "x"
if i%2 == 1 {
key = "y"
}
wg.Add(1)
go func(key string) {
defer wg.Done()
for range perGoroutine {
km.do(key, func() {
*counters[key]++
})
}
}(key)
}
wg.Wait()

assert.Equal(t, (goroutines/2)*perGoroutine, *counters["x"])
assert.Equal(t, (goroutines/2)*perGoroutine, *counters["y"])
assert.Equal(t, 0, km.len(), "every key must be reclaimed once released")
}

func TestKeyedMutex_SameKeyBlocksConcurrentHolder(t *testing.T) {
km := newKeyedMutex()
const key = "doc"

km.lock(key)

entered := make(chan struct{})
released := make(chan struct{})
go func() {
km.lock(key)
close(entered)
km.unlock(key)
close(released)
}()

select {
case <-entered:
km.unlock(key)
t.Fatal("second holder entered the critical section while the key was locked")
case <-time.After(200 * time.Millisecond):
}

assert.Equal(t, 1, km.len())

km.unlock(key)

select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("second holder never acquired the key after it was released")
}

<-released
assert.Equal(t, 0, km.len())
}

func TestKeyedMutex_DifferentKeysRunConcurrently(t *testing.T) {
km := newKeyedMutex()

entered := make(chan struct{}, 2)
release := make(chan struct{})

for _, key := range []string{"a", "b"} {
go func(key string) {
km.do(key, func() {
entered <- struct{}{}
<-release
})
}(key)
}

for range 2 {
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("different keys blocked each other - lock is not scoped per key")
}
}
close(release)
}

func TestKeyedMutex_NoLeakUnderChurn(t *testing.T) {
km := newKeyedMutex()

var wg sync.WaitGroup
for g := range 64 {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := range 1000 {
km.do(g*1000+i, func() {})
}
}(g)
}
wg.Wait()

assert.Equal(t, 0, km.len(), "keyed mutex leaked entries after all work drained")
}

func TestKeyedMutex_DoReleasesLockOnPanic(t *testing.T) {
km := newKeyedMutex()
const key = "boom"

require.Panics(t, func() {
km.do(key, func() { panic("kaboom") })
})

assert.Equal(t, 0, km.len(), "panicking key must still be reclaimed")

done := make(chan struct{})
go func() {
km.do(key, func() {})
close(done)
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("re-locking a key after a panic deadlocked")
}
}

func TestKeyedMutex_UnlockWithoutLockIsNoOp(t *testing.T) {
km := newKeyedMutex()
assert.NotPanics(t, func() { km.unlock("never-locked") })
assert.Equal(t, 0, km.len())
}
24 changes: 24 additions & 0 deletions schema_validation/validate_document.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/pb33f/jsonschema/v6"
"github.com/pb33f/jsonschema/v6/kind"
"github.com/pb33f/libopenapi"
v3high "github.com/pb33f/libopenapi/datamodel/high/v3"
"golang.org/x/text/language"
"golang.org/x/text/message"

Expand All @@ -23,6 +24,8 @@ import (
"github.com/pb33f/libopenapi-validator/helpers"
)

var buildModelLocks = newKeyedMutex()

type nonStringMappingKey struct {
Value string
Tag string
Expand Down Expand Up @@ -423,6 +426,27 @@ func ValidateOpenAPIDocumentWithPrecompiled(doc libopenapi.Document, compiledSch
}
validationErrors = append(validationErrors, documentError)
}

if options.ValidateDocumentPathParams {
var model *libopenapi.DocumentModel[v3high.Document]
var modelErr error

buildModelLocks.do(doc, func() {
model, modelErr = doc.BuildV3Model()
})

if model != nil {
validationErrors = append(validationErrors, validatePathParameters(&model.Model)...)
} else {
validationErrors = append(validationErrors, &liberrors.ValidationError{
ValidationType: helpers.Schema,
Message: "Document does not pass path parameter validation",
Reason: fmt.Sprintf("The document model could not be build: %v", modelErr),
HowToFix: fmt.Sprintf("ensure the document is valid according to the OpenAPI %s spec", doc.GetVersion()),
})
}
}

if len(validationErrors) > 0 {
return false, validationErrors
}
Expand Down
Loading