strict

package
v0.10.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package strict provides strict validation that detects undeclared properties in requests and responses, even when additionalProperties would normally allow them.

Strict mode is designed for API governance scenarios where you want to ensure that clients only send properties that are explicitly documented in the OpenAPI specification, regardless of whether additionalProperties is set to true.

Key Features

  • Detects undeclared properties in request/response bodies (JSON only)
  • Detects undeclared query parameters, headers, and cookies
  • Supports ignore paths with glob patterns (e.g., "$.body.metadata.*")
  • Handles polymorphic schemas (oneOf/anyOf) via per-branch validation
  • Respects readOnly/writeOnly based on request vs response direction
  • Configurable header ignore list with sensible defaults

Known Limitations

Property names containing single quotes (e.g., {"it's": "value"}) cannot be represented in bracket notation and cannot be matched by ignore patterns. Such properties will always be reported as undeclared if not in schema. This is acceptable because property names with quotes are extremely rare.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TruncateValue

func TruncateValue(v any) any

TruncateValue creates a display-friendly version of a value. Long strings are truncated, complex objects show type info. This is exported for use in error messages.

Types

type Direction

type Direction int

Direction indicates whether validation is for a request or response. This affects readOnly/writeOnly handling and Set-Cookie behavior.

const (
	// DirectionRequest indicates validation of an HTTP request.
	// readOnly properties are not expected in request bodies.
	DirectionRequest Direction = iota

	// DirectionResponse indicates validation of an HTTP response.
	// writeOnly properties are not expected in response bodies.
	// Set-Cookie headers are ignored (expected in responses).
	DirectionResponse
)

func (Direction) String

func (d Direction) String() string

String returns a human-readable direction name.

type Input

type Input struct {
	// Schema is the OpenAPI schema to validate against.
	Schema *base.Schema

	// Data is the unmarshalled data to validate (from request/response body).
	// Should be the result of json.Unmarshal.
	Data any

	// Direction indicates request vs response validation.
	// affects readOnly/writeOnly and Set-Cookie handling.
	Direction Direction

	// Options contains validation configuration including ignore paths.
	Options *config.ValidationOptions

	// BasePath is the prefix for generated instance paths.
	// typically "$.body" for bodies, "$.query" for query params, etc.
	BasePath string

	// Version is the OpenAPI version (3.0 or 3.1).
	// affects nullable handling in schema matching.
	Version float32
}

Input contains the parameters for strict validation.

type Result

type Result struct {
	Valid bool

	// UndeclaredValues lists all undeclared properties, parameters,
	// headers, or cookies found during validation.
	UndeclaredValues []UndeclaredValue
}

Result contains the output of strict validation.

func ValidateBody

func ValidateBody(schema *base.Schema, data any, direction Direction, options *config.ValidationOptions, version float32) *Result

ValidateBody is a convenience method for validating request/response bodies.

type UndeclaredValue

type UndeclaredValue struct {
	// Path is the instance JSONPath where the undeclared value was found.
	// uses bracket notation for property names with special characters.
	// examples: "$.body.user.extra", "$.body['a.b'].value", "$.query.debug"
	Path string

	// Name is the property, parameter, header, or cookie name.
	Name string

	// Value is the actual value found (it may be truncated for display).
	Value any

	// Type indicates what kind of value this is.
	// one of: "property", "header", "query", "cookie", "item"
	Type string

	// DeclaredProperties lists property names that ARE declared at this
	// location in the schema. Helps users understand what's expected.
	// for headers/query/cookies, this lists declared parameter names.
	DeclaredProperties []string

	// Direction indicates whether this was in a request or response.
	// used for error message disambiguation when Path is "$.body".
	Direction Direction

	// SpecLine is the line number in the OpenAPI spec where the parent
	// schema is defined. Zero if unavailable.
	SpecLine int

	// SpecCol is the column number in the OpenAPI spec where the parent
	// schema is defined. Zero if unavailable.
	SpecCol int
}

UndeclaredValue represents a value found in data that is not declared in the schema. This is the core output of strict validation.

func ValidateCookies

func ValidateCookies(
	request *http.Request,
	declaredParams []*v3.Parameter,
	options *config.ValidationOptions,
) []UndeclaredValue

ValidateCookies checks for undeclared cookies in an HTTP request.

func ValidateQueryParams

func ValidateQueryParams(
	request *http.Request,
	declaredParams []*v3.Parameter,
	options *config.ValidationOptions,
) []UndeclaredValue

ValidateQueryParams checks for undeclared query parameters in an HTTP request. It compares the query parameters present in the request against those declared in the OpenAPI operation.

func ValidateRequestHeaders

func ValidateRequestHeaders(
	headers http.Header,
	declaredParams []*v3.Parameter,
	securityHeaders []string,
	options *config.ValidationOptions,
) []UndeclaredValue

ValidateRequestHeaders checks for undeclared headers in an HTTP request. Header names are normalized to lowercase for path generation and pattern matching.

The securityHeaders parameter contains header names that are valid due to security scheme definitions (e.g., "X-API-Key" for apiKey schemes, "Authorization" for http/oauth2/openIdConnect schemes). These headers are considered "declared" even though they don't appear in the operation's parameters array.

func ValidateResponseHeaders

func ValidateResponseHeaders(
	headers http.Header,
	declaredHeaders *map[string]*v3.Header,
	options *config.ValidationOptions,
) []UndeclaredValue

ValidateResponseHeaders checks for undeclared headers in an HTTP response. Uses the declared headers from the OpenAPI response object. Header names are normalized to lowercase for path generation and pattern matching.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator performs strict property validation against OpenAPI schemas. It detects any properties present in data that are not explicitly declared in the schema, regardless of additionalProperties settings.

A new Validator should be created for each validation call to ensure isolation of internal caches and render contexts.

Cycle Detection

The Validator uses two distinct cycle detection mechanisms:

  1. traversalContext.visited: Tracks visited (path, schemaKey) combinations during the main validation traversal. This prevents infinite recursion when the same schema is encountered at the same instance path. The key uses a struct for zero-allocation lookups in the hot path.

  2. renderCtx (InlineRenderContext): libopenapi's built-in cycle detection for schema rendering. This is used when compiling schemas for oneOf/anyOf variant matching. It operates at the schema reference level rather than instance path level.

These mechanisms serve complementary purposes: visited tracks data traversal while renderCtx tracks schema resolution during compilation.

func NewValidator

func NewValidator(options *config.ValidationOptions, version float32) *Validator

NewValidator creates a fresh validator for a single validation call. The validator should not be reused across concurrent requests. Uses the logger from options if available, otherwise logging is silent.

func (*Validator) Validate

func (v *Validator) Validate(input Input) *Result

Validate performs strict validation on the input data against the schema. This is the main entry point for body validation.

It detects undeclared properties even when additionalProperties: true would normally allow them. This is useful for API governance scenarios where you want to ensure clients only send explicitly documented properties.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL