| 1 |
package config |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"log/slog" |
| 6 |
"net/http" |
| 7 |
|
| 8 |
v3 "github.com/pb33f/libopenapi/datamodel/high/v3" |
| 9 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 10 |
|
| 11 |
"github.com/pb33f/libopenapi-validator/cache" |
| 12 |
"github.com/pb33f/libopenapi-validator/radix" |
| 13 |
) |
| 14 |
|
| 15 |
// RegexCache can be set to enable compiled regex caching. |
| 16 |
// It can be just a sync.Map, or a custom implementation with possible cleanup. |
| 17 |
// |
| 18 |
// Be aware that the cache should be thread safe |
| 19 |
type RegexCache interface { |
| 20 |
Load(key any) (value any, ok bool) // Get a compiled regex from the cache |
| 21 |
Store(key, value any) // Set a compiled regex to the cache |
| 22 |
} |
| 23 |
|
| 24 |
// AuthenticationFunc validates a security scheme for an HTTP request. |
| 25 |
// Return nil when the scheme is satisfied; return an error to fail the current security requirement. |
| 26 |
type AuthenticationFunc func(context.Context, *AuthenticationInput) error |
| 27 |
|
| 28 |
// AuthenticationInput contains the request and OpenAPI security scheme details passed to an AuthenticationFunc. |
| 29 |
type AuthenticationInput struct { |
| 30 |
Request *http.Request |
| 31 |
SecuritySchemeName string |
| 32 |
SecurityScheme *v3.SecurityScheme |
| 33 |
Scopes []string |
| 34 |
} |
| 35 |
|
| 36 |
// ValidationOptions A container for validation configuration. |
| 37 |
// |
| 38 |
// Generally fluent With... style functions are used to establish the desired behavior. |
| 39 |
type ValidationOptions struct { |
| 40 |
RegexEngine jsonschema.RegexpEngine |
| 41 |
RegexCache RegexCache // Enable compiled regex caching |
| 42 |
FormatAssertions bool |
| 43 |
ContentAssertions bool |
| 44 |
SecurityValidation bool |
| 45 |
AuthenticationFunc AuthenticationFunc |
| 46 |
OpenAPIMode bool // Enable OpenAPI-specific vocabulary validation |
| 47 |
AllowScalarCoercion bool // Enable string->boolean/number coercion |
| 48 |
Formats map[string]func(v any) error |
| 49 |
SchemaCache cache.SchemaCache // Optional cache for compiled schemas |
| 50 |
PathTree radix.PathLookup // O(k) path lookup via radix tree (built automatically) |
| 51 |
pathTreeDisabled bool // Internal: true if radix tree auto-build was disabled via DisablePathTree |
| 52 |
Logger *slog.Logger // Logger for debug/error output (nil = silent) |
| 53 |
AllowXMLBodyValidation bool // Allows to convert XML to JSON for validating a request/response body. |
| 54 |
AllowURLEncodedBodyValidation bool // Allows to convert URL Encoded to JSON for validating a request/response body. |
| 55 |
|
| 56 |
// strict mode options - detect undeclared properties even when additionalProperties: true |
| 57 |
StrictMode bool // Enable strict property validation |
| 58 |
StrictIgnorePaths []string // Instance JSONPath patterns to exclude from strict checks |
| 59 |
StrictIgnoredHeaders []string // Headers to always ignore in strict mode (nil = use defaults) |
| 60 |
strictIgnoredHeadersMerge bool // Internal: true if merging with defaults |
| 61 |
StrictRejectReadOnly bool // Reject readOnly properties in requests |
| 62 |
StrictRejectWriteOnly bool // Reject writeOnly properties in responses |
| 63 |
} |
| 64 |
|
| 65 |
// Option Enables an 'Options pattern' approach |
| 66 |
type Option func(*ValidationOptions) |
| 67 |
|
| 68 |
// NewValidationOptions creates a new ValidationOptions instance with default values. |
| 69 |
func NewValidationOptions(opts ...Option) *ValidationOptions { |
| 70 |
// create the set of default values |
| 71 |
o := &ValidationOptions{ |
| 72 |
FormatAssertions: false, |
| 73 |
ContentAssertions: false, |
| 74 |
SecurityValidation: true, |
| 75 |
OpenAPIMode: true, // Enable OpenAPI vocabulary by default |
| 76 |
SchemaCache: cache.NewDefaultCache(), // Enable caching by default |
| 77 |
} |
| 78 |
|
| 79 |
for _, opt := range opts { |
| 80 |
if opt != nil { |
| 81 |
opt(o) |
| 82 |
} |
| 83 |
} |
| 84 |
return o |
| 85 |
} |
| 86 |
|
| 87 |
// WithExistingOpts returns an Option that will copy the values from the supplied ValidationOptions instance |
| 88 |
func WithExistingOpts(options *ValidationOptions) Option { |
| 89 |
return func(o *ValidationOptions) { |
| 90 |
if options != nil { |
| 91 |
o.RegexEngine = options.RegexEngine |
| 92 |
o.RegexCache = options.RegexCache |
| 93 |
o.FormatAssertions = options.FormatAssertions |
| 94 |
o.ContentAssertions = options.ContentAssertions |
| 95 |
o.SecurityValidation = options.SecurityValidation |
| 96 |
o.AuthenticationFunc = options.AuthenticationFunc |
| 97 |
o.OpenAPIMode = options.OpenAPIMode |
| 98 |
o.AllowScalarCoercion = options.AllowScalarCoercion |
| 99 |
o.Formats = options.Formats |
| 100 |
o.SchemaCache = options.SchemaCache |
| 101 |
o.PathTree = options.PathTree |
| 102 |
o.pathTreeDisabled = options.pathTreeDisabled |
| 103 |
o.Logger = options.Logger |
| 104 |
o.AllowXMLBodyValidation = options.AllowXMLBodyValidation |
| 105 |
o.AllowURLEncodedBodyValidation = options.AllowURLEncodedBodyValidation |
| 106 |
o.StrictMode = options.StrictMode |
| 107 |
o.StrictIgnorePaths = options.StrictIgnorePaths |
| 108 |
o.StrictIgnoredHeaders = options.StrictIgnoredHeaders |
| 109 |
o.strictIgnoredHeadersMerge = options.strictIgnoredHeadersMerge |
| 110 |
o.StrictRejectReadOnly = options.StrictRejectReadOnly |
| 111 |
o.StrictRejectWriteOnly = options.StrictRejectWriteOnly |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
// WithLogger sets the logger for validation debug/error output. |
| 117 |
// If not set, logging is silent (nil logger is handled gracefully). |
| 118 |
func WithLogger(logger *slog.Logger) Option { |
| 119 |
return func(o *ValidationOptions) { |
| 120 |
o.Logger = logger |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
// WithRegexEngine Assigns a custom regular-expression engine to be used during validation. |
| 125 |
func WithRegexEngine(engine jsonschema.RegexpEngine) Option { |
| 126 |
return func(o *ValidationOptions) { |
| 127 |
o.RegexEngine = engine |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
// WithRegexCache assigns a cache for compiled regular expressions. |
| 132 |
// A sync.Map should be sufficient for most use cases. It does not implement any cleanup |
| 133 |
func WithRegexCache(regexCache RegexCache) Option { |
| 134 |
return func(o *ValidationOptions) { |
| 135 |
o.RegexCache = regexCache |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
// WithFormatAssertions enables checks for 'format' assertions (such as date, date-time, uuid, etc) |
| 140 |
func WithFormatAssertions() Option { |
| 141 |
return func(o *ValidationOptions) { |
| 142 |
o.FormatAssertions = true |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
// WithContentAssertions enables checks for contentType, contentEncoding, etc |
| 147 |
func WithContentAssertions() Option { |
| 148 |
return func(o *ValidationOptions) { |
| 149 |
o.ContentAssertions = true |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
// WithoutSecurityValidation disables security validation for request validation |
| 154 |
func WithoutSecurityValidation() Option { |
| 155 |
return func(o *ValidationOptions) { |
| 156 |
o.SecurityValidation = false |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
// WithAuthenticationFunc sets a custom function for validating security requirements. |
| 161 |
// When set, the function is authoritative for all security scheme types, including oauth2 and openIdConnect. |
| 162 |
func WithAuthenticationFunc(fn AuthenticationFunc) Option { |
| 163 |
return func(o *ValidationOptions) { |
| 164 |
o.AuthenticationFunc = fn |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
// WithCustomFormat adds custom formats and their validators that checks for custom 'format' assertions |
| 169 |
// When you add different validators with the same name, they will be overridden, |
| 170 |
// and only the last registration will take effect. |
| 171 |
func WithCustomFormat(name string, validator func(v any) error) Option { |
| 172 |
return func(o *ValidationOptions) { |
| 173 |
if o.Formats == nil { |
| 174 |
o.Formats = make(map[string]func(v any) error) |
| 175 |
} |
| 176 |
|
| 177 |
o.Formats[name] = validator |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
// WithOpenAPIMode enables OpenAPI-specific keyword validation (default: true) |
| 182 |
func WithOpenAPIMode() Option { |
| 183 |
return func(o *ValidationOptions) { |
| 184 |
o.OpenAPIMode = true |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// WithoutOpenAPIMode disables OpenAPI-specific keyword validation |
| 189 |
func WithoutOpenAPIMode() Option { |
| 190 |
return func(o *ValidationOptions) { |
| 191 |
o.OpenAPIMode = false |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
// WithScalarCoercion enables string to boolean/number coercion (Jackson-style) |
| 196 |
func WithScalarCoercion() Option { |
| 197 |
return func(o *ValidationOptions) { |
| 198 |
o.AllowScalarCoercion = true |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
// WithXmlBodyValidation enables converting an XML body to a JSON when validating the schema from a request and response body |
| 203 |
// The default option is set to false |
| 204 |
func WithXmlBodyValidation() Option { |
| 205 |
return func(o *ValidationOptions) { |
| 206 |
o.AllowXMLBodyValidation = true |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
// WithURLEncodedBodyValidation enables converting an URL Encoded body to a JSON when validating the schema from a request and response body |
| 211 |
// The default option is set to false |
| 212 |
func WithURLEncodedBodyValidation() Option { |
| 213 |
return func(o *ValidationOptions) { |
| 214 |
o.AllowURLEncodedBodyValidation = true |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
// WithSchemaCache sets a custom cache implementation or disables caching if nil. |
| 219 |
// Pass nil to disable schema caching and skip cache warming during validator initialization. |
| 220 |
// The default cache is a thread-safe sync.Map wrapper. |
| 221 |
func WithSchemaCache(schemaCache cache.SchemaCache) Option { |
| 222 |
return func(o *ValidationOptions) { |
| 223 |
o.SchemaCache = schemaCache |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
// WithPathTree sets a custom radix tree for path matching. |
| 228 |
// The default is built automatically from the OpenAPI specification. |
| 229 |
func WithPathTree(pathTree radix.PathLookup) Option { |
| 230 |
return func(o *ValidationOptions) { |
| 231 |
o.PathTree = pathTree |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
// DisablePathTree prevents automatic radix tree construction. |
| 236 |
// Use this to fall back to regex-based path matching only. |
| 237 |
func DisablePathTree() Option { |
| 238 |
return func(o *ValidationOptions) { |
| 239 |
o.pathTreeDisabled = true |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
// WithStrictMode enables strict property validation. |
| 244 |
// In strict mode, undeclared properties are reported as errors even when |
| 245 |
// additionalProperties: true would normally allow them. |
| 246 |
// |
| 247 |
// This is useful for API governance scenarios where you want to ensure |
| 248 |
// clients only send properties that are explicitly documented in the |
| 249 |
// OpenAPI specification. |
| 250 |
func WithStrictMode() Option { |
| 251 |
return func(o *ValidationOptions) { |
| 252 |
o.StrictMode = true |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// WithStrictIgnorePaths sets JSONPath patterns for paths to exclude from strict validation. |
| 257 |
// Patterns use glob syntax: |
| 258 |
// - * matches a single path segment |
| 259 |
// - ** matches any depth (zero or more segments) |
| 260 |
// - [*] matches any array index |
| 261 |
// - \* escapes a literal asterisk |
| 262 |
// |
| 263 |
// Examples: |
| 264 |
// - "$.body.metadata.*" - any property under metadata |
| 265 |
// - "$.body.**.x-*" - any x-* property at any depth |
| 266 |
// - "$.headers.X-*" - any header starting with X- |
| 267 |
func WithStrictIgnorePaths(paths ...string) Option { |
| 268 |
return func(o *ValidationOptions) { |
| 269 |
o.StrictIgnorePaths = paths |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
// WithStrictRejectReadOnly enables rejection of readOnly properties in requests. |
| 274 |
// When enabled, readOnly properties present in request bodies are reported as |
| 275 |
// validation errors instead of being silently skipped. |
| 276 |
func WithStrictRejectReadOnly() Option { |
| 277 |
return func(o *ValidationOptions) { |
| 278 |
o.StrictRejectReadOnly = true |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
// WithStrictRejectWriteOnly enables rejection of writeOnly properties in responses. |
| 283 |
// When enabled, writeOnly properties present in response bodies are reported as |
| 284 |
// validation errors instead of being silently skipped. |
| 285 |
func WithStrictRejectWriteOnly() Option { |
| 286 |
return func(o *ValidationOptions) { |
| 287 |
o.StrictRejectWriteOnly = true |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
// WithStrictIgnoredHeaders replaces the default ignored headers list entirely. |
| 292 |
// Use this to fully control which headers are ignored in strict mode. |
| 293 |
// For the default list, see the strict package's DefaultIgnoredHeaders. |
| 294 |
func WithStrictIgnoredHeaders(headers ...string) Option { |
| 295 |
return func(o *ValidationOptions) { |
| 296 |
o.StrictIgnoredHeaders = headers |
| 297 |
o.strictIgnoredHeadersMerge = false |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
// WithStrictIgnoredHeadersExtra adds headers to the default ignored list. |
| 302 |
// Unlike WithStrictIgnoredHeaders, this merges with the defaults rather |
| 303 |
// than replacing them. |
| 304 |
func WithStrictIgnoredHeadersExtra(headers ...string) Option { |
| 305 |
return func(o *ValidationOptions) { |
| 306 |
o.StrictIgnoredHeaders = headers |
| 307 |
o.strictIgnoredHeadersMerge = true |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
// defaultIgnoredHeaders contains standard HTTP headers ignored by default. |
| 312 |
// This is the fallback list used when no custom headers are configured. |
| 313 |
var defaultIgnoredHeaders = []string{ |
| 314 |
"content-type", "content-length", "accept", "authorization", |
| 315 |
"user-agent", "host", "connection", "accept-encoding", |
| 316 |
"accept-language", "cache-control", "pragma", "origin", |
| 317 |
"referer", "cookie", "date", "etag", "expires", |
| 318 |
"if-match", "if-none-match", "if-modified-since", |
| 319 |
"last-modified", "transfer-encoding", "vary", "x-forwarded-for", |
| 320 |
"x-forwarded-proto", "x-real-ip", "x-request-id", |
| 321 |
"request-start-time", // Added by some API clients for timing |
| 322 |
} |
| 323 |
|
| 324 |
// IsPathTreeDisabled returns true if radix tree auto-build was disabled via DisablePathTree. |
| 325 |
func (o *ValidationOptions) IsPathTreeDisabled() bool { |
| 326 |
return o.pathTreeDisabled |
| 327 |
} |
| 328 |
|
| 329 |
// GetEffectiveStrictIgnoredHeaders returns the list of headers to ignore |
| 330 |
// based on configuration. Returns defaults if not configured, merged list |
| 331 |
// if extra headers were added, or replaced list if headers were fully replaced. |
| 332 |
func (o *ValidationOptions) GetEffectiveStrictIgnoredHeaders() []string { |
| 333 |
if o.StrictIgnoredHeaders == nil { |
| 334 |
return defaultIgnoredHeaders |
| 335 |
} |
| 336 |
if o.strictIgnoredHeadersMerge { |
| 337 |
return append(defaultIgnoredHeaders, o.StrictIgnoredHeaders...) |
| 338 |
} |
| 339 |
return o.StrictIgnoredHeaders |
| 340 |
} |