| 1 |
// Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
// Package strict provides strict validation that detects undeclared |
| 5 |
// properties in requests and responses, even when additionalProperties |
| 6 |
// would normally allow them. |
| 7 |
// |
| 8 |
// Strict mode is designed for API governance scenarios where you want to |
| 9 |
// ensure that clients only send properties that are explicitly documented |
| 10 |
// in the OpenAPI specification, regardless of whether additionalProperties |
| 11 |
// is set to true. |
| 12 |
// |
| 13 |
// # Key Features |
| 14 |
// |
| 15 |
// - Detects undeclared properties in request/response bodies (JSON only) |
| 16 |
// - Detects undeclared query parameters, headers, and cookies |
| 17 |
// - Supports ignore paths with glob patterns (e.g., "$.body.metadata.*") |
| 18 |
// - Handles polymorphic schemas (oneOf/anyOf) via per-branch validation |
| 19 |
// - Respects readOnly/writeOnly based on request vs response direction |
| 20 |
// - Configurable header ignore list with sensible defaults |
| 21 |
// |
| 22 |
// # Known Limitations |
| 23 |
// |
| 24 |
// Property names containing single quotes (e.g., {"it's": "value"}) cannot be |
| 25 |
// represented in bracket notation and cannot be matched by ignore patterns. |
| 26 |
// Such properties will always be reported as undeclared if not in schema. |
| 27 |
// This is acceptable because property names with quotes are extremely rare. |
| 28 |
package strict |
| 29 |
|
| 30 |
import ( |
| 31 |
"context" |
| 32 |
"fmt" |
| 33 |
"log/slog" |
| 34 |
"regexp" |
| 35 |
|
| 36 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 37 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 38 |
|
| 39 |
"github.com/pb33f/libopenapi-validator/config" |
| 40 |
) |
| 41 |
|
| 42 |
// Direction indicates whether validation is for a request or response. |
| 43 |
// This affects readOnly/writeOnly handling and Set-Cookie behavior. |
| 44 |
type Direction int |
| 45 |
|
| 46 |
const ( |
| 47 |
// DirectionRequest indicates validation of an HTTP request. |
| 48 |
// readOnly properties are not expected in request bodies. |
| 49 |
DirectionRequest Direction = iota |
| 50 |
|
| 51 |
// DirectionResponse indicates validation of an HTTP response. |
| 52 |
// writeOnly properties are not expected in response bodies. |
| 53 |
// Set-Cookie headers are ignored (expected in responses). |
| 54 |
DirectionResponse |
| 55 |
) |
| 56 |
|
| 57 |
// String returns a human-readable direction name. |
| 58 |
func (d Direction) String() string { |
| 59 |
if d == DirectionResponse { |
| 60 |
return "response" |
| 61 |
} |
| 62 |
return "request" |
| 63 |
} |
| 64 |
|
| 65 |
// Type constants for UndeclaredValue.Type, defined here for use in the |
| 66 |
// request/response dispatch switch (existing types use inline strings). |
| 67 |
const ( |
| 68 |
TypeReadOnlyProperty = "readonly" |
| 69 |
TypeWriteOnlyProperty = "writeonly" |
| 70 |
) |
| 71 |
|
| 72 |
// UndeclaredValue represents a value found in data that is not declared |
| 73 |
// in the schema. This is the core output of strict validation. |
| 74 |
type UndeclaredValue struct { |
| 75 |
// Path is the instance JSONPath where the undeclared value was found. |
| 76 |
// uses bracket notation for property names with special characters. |
| 77 |
// examples: "$.body.user.extra", "$.body['a.b'].value", "$.query.debug" |
| 78 |
Path string |
| 79 |
|
| 80 |
// Name is the property, parameter, header, or cookie name. |
| 81 |
Name string |
| 82 |
|
| 83 |
// Value is the actual value found (it may be truncated for display). |
| 84 |
Value any |
| 85 |
|
| 86 |
// Type indicates what kind of value this is. |
| 87 |
// one of: "property", "header", "query", "cookie", "item", "readonly", "writeonly" |
| 88 |
Type string |
| 89 |
|
| 90 |
// DeclaredProperties lists property names that ARE declared at this |
| 91 |
// location in the schema. Helps users understand what's expected. |
| 92 |
// for headers/query/cookies, this lists declared parameter names. |
| 93 |
DeclaredProperties []string |
| 94 |
|
| 95 |
// Direction indicates whether this was in a request or response. |
| 96 |
// used for error message disambiguation when Path is "$.body". |
| 97 |
Direction Direction |
| 98 |
|
| 99 |
// SpecLine is the line number in the OpenAPI spec where the parent |
| 100 |
// schema is defined. Zero if unavailable. |
| 101 |
SpecLine int |
| 102 |
|
| 103 |
// SpecCol is the column number in the OpenAPI spec where the parent |
| 104 |
// schema is defined. Zero if unavailable. |
| 105 |
SpecCol int |
| 106 |
} |
| 107 |
|
| 108 |
// extractSchemaLocation extracts the line and column from a schema's low-level |
| 109 |
// representation. returns (0, 0) if the schema is nil or has no low-level info. |
| 110 |
func extractSchemaLocation(schema *base.Schema) (line, col int) { |
| 111 |
if schema == nil { |
| 112 |
return 0, 0 |
| 113 |
} |
| 114 |
low := schema.GoLow() |
| 115 |
if low == nil || low.RootNode == nil { |
| 116 |
return 0, 0 |
| 117 |
} |
| 118 |
return low.RootNode.Line, low.RootNode.Column |
| 119 |
} |
| 120 |
|
| 121 |
// newUndeclaredProperty creates an UndeclaredValue for an undeclared object property. |
| 122 |
// the schema parameter is the parent schema where the property would need to be declared. |
| 123 |
func newUndeclaredProperty(path, name string, value any, declaredNames []string, direction Direction, schema *base.Schema) UndeclaredValue { |
| 124 |
line, col := extractSchemaLocation(schema) |
| 125 |
return UndeclaredValue{ |
| 126 |
Path: path, |
| 127 |
Name: name, |
| 128 |
Value: TruncateValue(value), |
| 129 |
Type: "property", |
| 130 |
DeclaredProperties: declaredNames, |
| 131 |
Direction: direction, |
| 132 |
SpecLine: line, |
| 133 |
SpecCol: col, |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
// newReadWriteOnlyViolation creates an UndeclaredValue for a readOnly/writeOnly violation. |
| 138 |
func newReadWriteOnlyViolation(path, name string, value any, direction Direction, schema *base.Schema) UndeclaredValue { |
| 139 |
line, col := extractSchemaLocation(schema) |
| 140 |
violationType := TypeReadOnlyProperty |
| 141 |
if direction == DirectionResponse { |
| 142 |
violationType = TypeWriteOnlyProperty |
| 143 |
} |
| 144 |
return UndeclaredValue{ |
| 145 |
Path: path, |
| 146 |
Name: name, |
| 147 |
Value: TruncateValue(value), |
| 148 |
Type: violationType, |
| 149 |
Direction: direction, |
| 150 |
SpecLine: line, |
| 151 |
SpecCol: col, |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
// newUndeclaredParam creates an UndeclaredValue for an undeclared parameter (query/header/cookie). |
| 156 |
// note: parameters don't have SpecLine/SpecCol because they're defined in OpenAPI parameter objects, |
| 157 |
// not schema objects. the parameter itself is the issue, not a schema definition. |
| 158 |
func newUndeclaredParam(path, name string, value any, paramType string, declaredNames []string, direction Direction) UndeclaredValue { |
| 159 |
return UndeclaredValue{ |
| 160 |
Path: path, |
| 161 |
Name: name, |
| 162 |
Value: value, |
| 163 |
Type: paramType, |
| 164 |
DeclaredProperties: declaredNames, |
| 165 |
Direction: direction, |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
// newUndeclaredItem creates an UndeclaredValue for an undeclared array item. |
| 170 |
func newUndeclaredItem(path, name string, value any, direction Direction) UndeclaredValue { |
| 171 |
return UndeclaredValue{ |
| 172 |
Path: path, |
| 173 |
Name: name, |
| 174 |
Value: TruncateValue(value), |
| 175 |
Type: "item", |
| 176 |
Direction: direction, |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
// Input contains the parameters for strict validation. |
| 181 |
type Input struct { |
| 182 |
// Schema is the OpenAPI schema to validate against. |
| 183 |
Schema *base.Schema |
| 184 |
|
| 185 |
// Data is the unmarshalled data to validate (from request/response body). |
| 186 |
// Should be the result of json.Unmarshal. |
| 187 |
Data any |
| 188 |
|
| 189 |
// Direction indicates request vs response validation. |
| 190 |
// affects readOnly/writeOnly and Set-Cookie handling. |
| 191 |
Direction Direction |
| 192 |
|
| 193 |
// Options contains validation configuration including ignore paths. |
| 194 |
Options *config.ValidationOptions |
| 195 |
|
| 196 |
// BasePath is the prefix for generated instance paths. |
| 197 |
// typically "$.body" for bodies, "$.query" for query params, etc. |
| 198 |
BasePath string |
| 199 |
|
| 200 |
// Version is the OpenAPI version (3.0 or 3.1). |
| 201 |
// affects nullable handling in schema matching. |
| 202 |
Version float32 |
| 203 |
} |
| 204 |
|
| 205 |
// Result contains the output of strict validation. |
| 206 |
type Result struct { |
| 207 |
Valid bool |
| 208 |
|
| 209 |
// UndeclaredValues lists all undeclared properties, parameters, |
| 210 |
// headers, or cookies found during validation. |
| 211 |
UndeclaredValues []UndeclaredValue |
| 212 |
} |
| 213 |
|
| 214 |
// cycleKey uniquely identifies a schema at a specific validation path. |
| 215 |
// Using a struct key avoids string allocation in the hot path. |
| 216 |
type cycleKey struct { |
| 217 |
path string |
| 218 |
schemaKey string |
| 219 |
} |
| 220 |
|
| 221 |
// traversalContext tracks state during schema traversal to detect cycles |
| 222 |
// and limit recursion depth. |
| 223 |
type traversalContext struct { |
| 224 |
// visited tracks schemas already being validated at specific paths. |
| 225 |
// key combines instance path + schema key to allow same schema at different paths. |
| 226 |
visited map[cycleKey]bool |
| 227 |
|
| 228 |
// depth tracks current recursion depth for safety limits. |
| 229 |
depth int |
| 230 |
|
| 231 |
// maxDepth is the maximum allowed recursion depth (default: 100). |
| 232 |
maxDepth int |
| 233 |
|
| 234 |
// direction indicates request vs response for readOnly/writeOnly. |
| 235 |
direction Direction |
| 236 |
|
| 237 |
// ignorePaths are compiled regex patterns for paths to skip. |
| 238 |
ignorePaths []*regexp.Regexp |
| 239 |
|
| 240 |
// path is the current instance path being validated. |
| 241 |
path string |
| 242 |
} |
| 243 |
|
| 244 |
// newTraversalContext creates a new context for schema traversal. |
| 245 |
func newTraversalContext(direction Direction, ignorePaths []*regexp.Regexp, basePath string) *traversalContext { |
| 246 |
return &traversalContext{ |
| 247 |
visited: make(map[cycleKey]bool), |
| 248 |
depth: 0, |
| 249 |
maxDepth: 100, |
| 250 |
direction: direction, |
| 251 |
ignorePaths: ignorePaths, |
| 252 |
path: basePath, |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// withPath returns a new context with an updated path. |
| 257 |
func (c *traversalContext) withPath(path string) *traversalContext { |
| 258 |
return &traversalContext{ |
| 259 |
visited: c.visited, |
| 260 |
depth: c.depth + 1, |
| 261 |
maxDepth: c.maxDepth, |
| 262 |
direction: c.direction, |
| 263 |
ignorePaths: c.ignorePaths, |
| 264 |
path: path, |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
// shouldIgnore checks if the current path matches any ignore pattern. |
| 269 |
func (c *traversalContext) shouldIgnore() bool { |
| 270 |
for _, pattern := range c.ignorePaths { |
| 271 |
if pattern.MatchString(c.path) { |
| 272 |
return true |
| 273 |
} |
| 274 |
} |
| 275 |
return false |
| 276 |
} |
| 277 |
|
| 278 |
// exceedsDepth checks if we've exceeded the maximum recursion depth. |
| 279 |
func (c *traversalContext) exceedsDepth() bool { |
| 280 |
return c.depth > c.maxDepth |
| 281 |
} |
| 282 |
|
| 283 |
// checkAndMarkVisited checks if a schema has been visited at the current path. |
| 284 |
// Returns true if this is a cycle (already visited), false otherwise. |
| 285 |
// If not a cycle, marks the schema as visited. |
| 286 |
func (c *traversalContext) checkAndMarkVisited(schemaKey string) bool { |
| 287 |
key := cycleKey{path: c.path, schemaKey: schemaKey} |
| 288 |
if c.visited[key] { |
| 289 |
return true // Cycle detected |
| 290 |
} |
| 291 |
c.visited[key] = true |
| 292 |
return false |
| 293 |
} |
| 294 |
|
| 295 |
// Validator performs strict property validation against OpenAPI schemas. |
| 296 |
// It detects any properties present in data that are not explicitly |
| 297 |
// declared in the schema, regardless of additionalProperties settings. |
| 298 |
// |
| 299 |
// A new Validator should be created for each validation call to ensure |
| 300 |
// isolation of internal caches and render contexts. |
| 301 |
// |
| 302 |
// # Cycle Detection |
| 303 |
// |
| 304 |
// The Validator uses two distinct cycle detection mechanisms: |
| 305 |
// |
| 306 |
// 1. traversalContext.visited: Tracks visited (path, schemaKey) combinations |
| 307 |
// during the main validation traversal. This prevents infinite recursion |
| 308 |
// when the same schema is encountered at the same instance path. The key |
| 309 |
// uses a struct for zero-allocation lookups in the hot path. |
| 310 |
// |
| 311 |
// 2. renderCtx (InlineRenderContext): libopenapi's built-in cycle detection |
| 312 |
// for schema rendering. This is used when compiling schemas for oneOf/anyOf |
| 313 |
// variant matching. It operates at the schema reference level rather than |
| 314 |
// instance path level. |
| 315 |
// |
| 316 |
// These mechanisms serve complementary purposes: visited tracks data traversal |
| 317 |
// while renderCtx tracks schema resolution during compilation. |
| 318 |
type Validator struct { |
| 319 |
options *config.ValidationOptions |
| 320 |
logger *slog.Logger |
| 321 |
|
| 322 |
// localCache stores compiled schemas for reuse within this validation. |
| 323 |
// ley is schema hash (as string for map compatibility), value is compiled jsonschema. |
| 324 |
localCache map[string]*jsonschema.Schema |
| 325 |
|
| 326 |
// patternCache stores compiled regex patterns for patternProperties. |
| 327 |
// key is the pattern string, value is the compiled regex. |
| 328 |
patternCache map[string]*regexp.Regexp |
| 329 |
|
| 330 |
// renderCtx is used for safe schema rendering with cycle detection. |
| 331 |
// see Validator doc comment for how this relates to traversalContext.visited. |
| 332 |
renderCtx *base.InlineRenderContext |
| 333 |
|
| 334 |
// version is the OpenAPI version (3.0 or 3.1). |
| 335 |
version float32 |
| 336 |
|
| 337 |
// compiledIgnorePaths are the pre-compiled regex patterns. |
| 338 |
compiledIgnorePaths []*regexp.Regexp |
| 339 |
} |
| 340 |
|
| 341 |
// NewValidator creates a fresh validator for a single validation call. |
| 342 |
// The validator should not be reused across concurrent requests. |
| 343 |
// Uses the logger from options if available, otherwise logging is silent. |
| 344 |
func NewValidator(options *config.ValidationOptions, version float32) *Validator { |
| 345 |
var logger *slog.Logger |
| 346 |
if options != nil && options.Logger != nil { |
| 347 |
logger = options.Logger |
| 348 |
} else { |
| 349 |
// create a no-op logger that discards all output |
| 350 |
logger = slog.New(discardHandler{}) |
| 351 |
} |
| 352 |
|
| 353 |
v := &Validator{ |
| 354 |
options: options, |
| 355 |
logger: logger, |
| 356 |
localCache: make(map[string]*jsonschema.Schema), |
| 357 |
patternCache: make(map[string]*regexp.Regexp), |
| 358 |
renderCtx: base.NewInlineRenderContextForValidation(), |
| 359 |
version: version, |
| 360 |
} |
| 361 |
|
| 362 |
if options != nil { |
| 363 |
v.compiledIgnorePaths = compileIgnorePaths(options.StrictIgnorePaths) |
| 364 |
} |
| 365 |
|
| 366 |
return v |
| 367 |
} |
| 368 |
|
| 369 |
// discardHandler is a slog.Handler that discards all log records. |
| 370 |
type discardHandler struct{} |
| 371 |
|
| 372 |
func (discardHandler) Enabled(context.Context, slog.Level) bool { return false } |
| 373 |
func (discardHandler) Handle(context.Context, slog.Record) error { return nil } |
| 374 |
func (d discardHandler) WithAttrs([]slog.Attr) slog.Handler { return d } |
| 375 |
func (d discardHandler) WithGroup(string) slog.Handler { return d } |
| 376 |
|
| 377 |
// matchesIgnorePath checks if a path matches any pre-compiled ignore pattern. |
| 378 |
func (v *Validator) matchesIgnorePath(path string) bool { |
| 379 |
for _, pattern := range v.compiledIgnorePaths { |
| 380 |
if pattern.MatchString(path) { |
| 381 |
return true |
| 382 |
} |
| 383 |
} |
| 384 |
return false |
| 385 |
} |
| 386 |
|
| 387 |
// getCompiledPattern returns a cached compiled regex for a pattern string. |
| 388 |
// If the pattern is not in the cache, it compiles and caches it. |
| 389 |
// Returns nil if the pattern is invalid. |
| 390 |
func (v *Validator) getCompiledPattern(pattern string) *regexp.Regexp { |
| 391 |
if cached, ok := v.patternCache[pattern]; ok { |
| 392 |
return cached |
| 393 |
} |
| 394 |
|
| 395 |
compiled, err := regexp.Compile(pattern) |
| 396 |
if err != nil { |
| 397 |
return nil |
| 398 |
} |
| 399 |
|
| 400 |
v.patternCache[pattern] = compiled |
| 401 |
return compiled |
| 402 |
} |
| 403 |
|
| 404 |
// getSchemaKey returns a unique key for a schema used in cycle detection. |
| 405 |
// Uses the schema's low-level hash if available, otherwise the pointer address. |
| 406 |
func (v *Validator) getSchemaKey(schema *base.Schema) string { |
| 407 |
if schema == nil { |
| 408 |
return "" |
| 409 |
} |
| 410 |
if low := schema.GoLow(); low != nil { |
| 411 |
hash := low.Hash() |
| 412 |
return fmt.Sprintf("%x", hash) // uint64 hash as hex string |
| 413 |
} |
| 414 |
// fallback to pointer address for inline schemas without low-level info |
| 415 |
return fmt.Sprintf("%p", schema) |
| 416 |
} |