openapi3filter

package
v0.77.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2021 License: MIT Imports: 19 Imported by: 403

Documentation

Overview

Package openapi3filter validates that requests and inputs request an OpenAPI 3 specification file.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sort"
	"strings"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/openapi3filter"
	"github.com/getkin/kin-openapi/routers/gorillamux"
)

func main() {
	doc, err := openapi3.NewLoader().LoadFromFile("./testdata/petstore.yaml")
	if err != nil {
		panic(err)
	}

	router, err := gorillamux.NewRouter(doc)
	if err != nil {
		panic(err)
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		route, pathParams, err := router.FindRoute(r)
		if err != nil {
			fmt.Println(err.Error())
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		err = openapi3filter.ValidateRequest(r.Context(), &openapi3filter.RequestValidationInput{
			Request:    r,
			PathParams: pathParams,
			Route:      route,
			Options: &openapi3filter.Options{
				MultiError: true,
			},
		})
		switch err := err.(type) {
		case nil:
		case openapi3.MultiError:
			issues := convertError(err)
			names := make([]string, 0, len(issues))
			for k := range issues {
				names = append(names, k)
			}
			sort.Strings(names)
			for _, k := range names {
				msgs := issues[k]
				fmt.Println("===== Start New Error =====")
				fmt.Println(k + ":")
				for _, msg := range msgs {
					fmt.Printf("\t%s\n", msg)
				}
			}
			w.WriteHeader(http.StatusBadRequest)
		default:
			fmt.Println(err.Error())
			w.WriteHeader(http.StatusBadRequest)
		}
	}))
	defer ts.Close()

	// (note invalid type for name and invalid status)
	body := strings.NewReader(`{"name": 100, "photoUrls": [], "status": "invalidStatus"}`)
	req, err := http.NewRequest("POST", ts.URL+"/pet", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	fmt.Printf("response: %d %s\n", resp.StatusCode, resp.Body)

}

const (
	prefixBody = "@body"
	unknown    = "@unknown"
)

func convertError(me openapi3.MultiError) map[string][]string {
	issues := make(map[string][]string)
	for _, err := range me {
		switch err := err.(type) {
		case *openapi3.SchemaError:
			// Can inspect schema validation errors here, e.g. err.Value
			field := prefixBody
			if path := err.JSONPointer(); len(path) > 0 {
				field = fmt.Sprintf("%s.%s", field, strings.Join(path, "."))
			}
			if _, ok := issues[field]; !ok {
				issues[field] = make([]string, 0, 3)
			}
			issues[field] = append(issues[field], err.Error())
		case *openapi3filter.RequestError: // possible there were multiple issues that failed validation
			if err, ok := err.Err.(openapi3.MultiError); ok {
				for k, v := range convertError(err) {
					if _, ok := issues[k]; !ok {
						issues[k] = make([]string, 0, 3)
					}
					issues[k] = append(issues[k], v...)
				}
				continue
			}

			// check if invalid HTTP parameter
			if err.Parameter != nil {
				prefix := err.Parameter.In
				name := fmt.Sprintf("%s.%s", prefix, err.Parameter.Name)
				if _, ok := issues[name]; !ok {
					issues[name] = make([]string, 0, 3)
				}
				issues[name] = append(issues[name], err.Error())
				continue
			}

			// check if requestBody
			if err.RequestBody != nil {
				if _, ok := issues[prefixBody]; !ok {
					issues[prefixBody] = make([]string, 0, 3)
				}
				issues[prefixBody] = append(issues[prefixBody], err.Error())
				continue
			}
		default:
			reasons, ok := issues[unknown]
			if !ok {
				reasons = make([]string, 0, 3)
			}
			reasons = append(reasons, err.Error())
			issues[unknown] = reasons
		}
	}
	return issues
}
Output:

===== Start New Error =====
@body.name:
	Error at "/name": Field must be set to string or not be present
Schema:
  {
    "example": "doggie",
    "type": "string"
  }

Value:
  "number, integer"

===== Start New Error =====
@body.status:
	Error at "/status": value is not one of the allowed values
Schema:
  {
    "description": "pet status in the store",
    "enum": [
      "available",
      "pending",
      "sold"
    ],
    "type": "string"
  }

Value:
  "invalidStatus"

response: 400 {}

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultOptions = &Options{}

DefaultOptions do not set an AuthenticationFunc. A spec with security schemes defined will not pass validation unless an AuthenticationFunc is defined.

View Source
var ErrAuthenticationServiceMissing = errors.New("missing AuthenticationFunc")

ErrAuthenticationServiceMissing is returned when no authentication service is defined for the request validator

View Source
var ErrInvalidRequired = errors.New("value is required but missing")

ErrInvalidRequired is returned when a required value of a parameter or request body is not defined.

View Source
var JSONPrefixes = []string{
	")]}',\n",
}

Functions

func DefaultErrorEncoder added in v0.10.0

func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter)

DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500. If the error implements Headerer, the provided headers will be applied to the response. If the error implements json.Marshaler, and the marshaling succeeds, a content type of application/json and the JSON encoded form of the error will be used. If the error implements StatusCoder, the provided StatusCode will be used instead of 500.

func FileBodyDecoder added in v0.2.0

func FileBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (interface{}, error)

FileBodyDecoder is a body decoder that decodes a file body to a string.

func NoopAuthenticationFunc added in v0.10.0

func NoopAuthenticationFunc(context.Context, *AuthenticationInput) error

func RegisterBodyDecoder added in v0.2.0

func RegisterBodyDecoder(contentType string, decoder BodyDecoder)

RegisterBodyDecoder registers a request body's decoder for a content type.

If a decoder for the specified content type already exists, the function replaces it with the specified decoder. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

func TrimJSONPrefix

func TrimJSONPrefix(data []byte) []byte

TrimJSONPrefix trims one of the possible prefixes

func UnregisterBodyDecoder added in v0.2.0

func UnregisterBodyDecoder(contentType string)

UnregisterBodyDecoder dissociates a body decoder from a content type.

Decoding this content type will result in an error. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

func ValidateParameter

func ValidateParameter(ctx context.Context, input *RequestValidationInput, parameter *openapi3.Parameter) error

ValidateParameter validates a parameter's value by JSON schema. The function returns RequestError with a ParseError cause when unable to parse a value. The function returns RequestError with ErrInvalidRequired cause when a value of a required parameter is not defined. The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema.

func ValidateRequest

func ValidateRequest(ctx context.Context, input *RequestValidationInput) error

ValidateRequest is used to validate the given input according to previous loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a non-nil error will be returned.

Note: One can tune the behavior of uniqueItems: true verification by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker

func ValidateRequestBody

func ValidateRequestBody(ctx context.Context, input *RequestValidationInput, requestBody *openapi3.RequestBody) error

ValidateRequestBody validates data of a request's body.

The function returns RequestError with ErrInvalidRequired cause when a value is required but not defined. The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema.

func ValidateResponse

func ValidateResponse(ctx context.Context, input *ResponseValidationInput) error

ValidateResponse is used to validate the given input according to previous loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a non-nil error will be returned.

Note: One can tune the behavior of uniqueItems: true verification by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker

func ValidateSecurityRequirements

func ValidateSecurityRequirements(ctx context.Context, input *RequestValidationInput, srs openapi3.SecurityRequirements) error

ValidateSecurityRequirements goes through multiple OpenAPI 3 security requirements in order and returns nil on the first valid requirement. If no requirement is met, errors are returned in order.

Types

type AuthenticationFunc added in v0.10.0

type AuthenticationFunc func(context.Context, *AuthenticationInput) error

type AuthenticationInput

type AuthenticationInput struct {
	RequestValidationInput *RequestValidationInput
	SecuritySchemeName     string
	SecurityScheme         *openapi3.SecurityScheme
	Scopes                 []string
}

func (*AuthenticationInput) NewError

func (input *AuthenticationInput) NewError(err error) error

type BodyDecoder added in v0.2.0

type BodyDecoder func(io.Reader, http.Header, *openapi3.SchemaRef, EncodingFn) (interface{}, error)

BodyDecoder is an interface to decode a body of a request or response. An implementation must return a value that is a primitive, []interface{}, or map[string]interface{}.

func RegisteredBodyDecoder added in v0.54.0

func RegisteredBodyDecoder(contentType string) BodyDecoder

RegisteredBodyDecoder returns the registered body decoder for the given content type.

If no decoder was registered for the given content type, nil is returned. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

type ContentParameterDecoder added in v0.2.0

type ContentParameterDecoder func(param *openapi3.Parameter, values []string) (interface{}, *openapi3.Schema, error)

A ContentParameterDecoder takes a parameter definition from the OpenAPI spec, and the value which we received for it. It is expected to return the value unmarshaled into an interface which can be traversed for validation, it should also return the schema to be used for validating the object, since there can be more than one in the content spec.

If a query parameter appears multiple times, values[] will have more than one value, but for all other parameter types it should have just one.

type EncodingFn added in v0.2.0

type EncodingFn func(partName string) *openapi3.Encoding

EncodingFn is a function that returns an encoding of a request body's part.

type ErrorEncoder added in v0.10.0

type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter)

ErrorEncoder is responsible for encoding an error to the ResponseWriter. Users are encouraged to use custom ErrorEncoders to encode HTTP errors to their clients, and will likely want to pass and check for their own error types. See the example shipping/handling service.

type Headerer added in v0.10.0

type Headerer interface {
	Headers() http.Header
}

Headerer is checked by DefaultErrorEncoder. If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.

type Options

type Options struct {
	// Set ExcludeRequestBody so ValidateRequest skips request body validation
	ExcludeRequestBody bool

	// Set ExcludeResponseBody so ValidateResponse skips response body validation
	ExcludeResponseBody bool

	// Set IncludeResponseStatus so ValidateResponse fails on response
	// status not defined in OpenAPI spec
	IncludeResponseStatus bool

	MultiError bool

	// See NoopAuthenticationFunc
	AuthenticationFunc AuthenticationFunc
}

Options used by ValidateRequest and ValidateResponse

type ParseError added in v0.2.0

type ParseError struct {
	Kind   ParseErrorKind
	Value  interface{}
	Reason string
	Cause  error
	// contains filtered or unexported fields
}

ParseError describes errors which happens while parse operation's parameters, requestBody, or response.

func (*ParseError) Error added in v0.2.0

func (e *ParseError) Error() string

func (*ParseError) Path added in v0.2.0

func (e *ParseError) Path() []interface{}

Path returns a path to the root cause.

func (*ParseError) RootCause added in v0.2.0

func (e *ParseError) RootCause() error

RootCause returns a root cause of ParseError.

func (ParseError) Unwrap added in v0.77.0

func (e ParseError) Unwrap() error

type ParseErrorKind added in v0.2.0

type ParseErrorKind int

ParseErrorKind describes a kind of ParseError. The type simplifies comparison of errors.

const (
	// KindOther describes an untyped parsing error.
	KindOther ParseErrorKind = iota
	// KindUnsupportedFormat describes an error that happens when a value has an unsupported format.
	KindUnsupportedFormat
	// KindInvalidFormat describes an error that happens when a value does not conform a format
	// that is required by a serialization method.
	KindInvalidFormat
)

type RequestError

type RequestError struct {
	Input       *RequestValidationInput
	Parameter   *openapi3.Parameter
	RequestBody *openapi3.RequestBody
	Reason      string
	Err         error
}

RequestError is returned by ValidateRequest when request does not match OpenAPI spec

func (*RequestError) Error

func (err *RequestError) Error() string

func (RequestError) Unwrap added in v0.77.0

func (err RequestError) Unwrap() error

type RequestValidationInput

type RequestValidationInput struct {
	Request      *http.Request
	PathParams   map[string]string
	QueryParams  url.Values
	Route        *routers.Route
	Options      *Options
	ParamDecoder ContentParameterDecoder
}

func (*RequestValidationInput) GetQueryParams

func (input *RequestValidationInput) GetQueryParams() url.Values

type ResponseError

type ResponseError struct {
	Input  *ResponseValidationInput
	Reason string
	Err    error
}

ResponseError is returned by ValidateResponse when response does not match OpenAPI spec

func (*ResponseError) Error

func (err *ResponseError) Error() string

func (ResponseError) Unwrap added in v0.77.0

func (err ResponseError) Unwrap() error

type ResponseValidationInput

type ResponseValidationInput struct {
	RequestValidationInput *RequestValidationInput
	Status                 int
	Header                 http.Header
	Body                   io.ReadCloser
	Options                *Options
}

func (*ResponseValidationInput) SetBodyBytes

func (input *ResponseValidationInput) SetBodyBytes(value []byte) *ResponseValidationInput

type SecurityRequirementsError

type SecurityRequirementsError struct {
	SecurityRequirements openapi3.SecurityRequirements
	Errors               []error
}

SecurityRequirementsError is returned by ValidateSecurityRequirements when no requirement is met.

func (*SecurityRequirementsError) Error

func (err *SecurityRequirementsError) Error() string

type StatusCoder added in v0.10.0

type StatusCoder interface {
	StatusCode() int
}

StatusCoder is checked by DefaultErrorEncoder. If an error value implements StatusCoder, the StatusCode will be used when encoding the error. By default, StatusInternalServerError (500) is used.

type ValidationError added in v0.10.0

type ValidationError struct {
	// A unique identifier for this particular occurrence of the problem.
	Id string `json:"id,omitempty"`
	// The HTTP status code applicable to this problem.
	Status int `json:"status,omitempty"`
	// An application-specific error code, expressed as a string value.
	Code string `json:"code,omitempty"`
	// A short, human-readable summary of the problem. It **SHOULD NOT** change from occurrence to occurrence of the problem, except for purposes of localization.
	Title string `json:"title,omitempty"`
	// A human-readable explanation specific to this occurrence of the problem.
	Detail string `json:"detail,omitempty"`
	// An object containing references to the source of the error
	Source *ValidationErrorSource `json:"source,omitempty"`
}

ValidationError struct provides granular error information useful for communicating issues back to end user and developer. Based on https://jsonapi.org/format/#error-objects

func (*ValidationError) Error added in v0.10.0

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) StatusCode added in v0.10.0

func (e *ValidationError) StatusCode() int

StatusCode implements the StatusCoder interface for DefaultErrorEncoder

type ValidationErrorEncoder added in v0.10.0

type ValidationErrorEncoder struct {
	Encoder ErrorEncoder
}

ValidationErrorEncoder wraps a base ErrorEncoder to handle ValidationErrors

func (*ValidationErrorEncoder) Encode added in v0.10.0

Encode implements the ErrorEncoder interface for encoding ValidationErrors

type ValidationErrorSource added in v0.10.0

type ValidationErrorSource struct {
	// A JSON Pointer [RFC6901] to the associated entity in the request document [e.g. \"/data\" for a primary data object, or \"/data/attributes/title\" for a specific attribute].
	Pointer string `json:"pointer,omitempty"`
	// A string indicating which query parameter caused the error.
	Parameter string `json:"parameter,omitempty"`
}

ValidationErrorSource struct

type ValidationHandler added in v0.10.0

type ValidationHandler struct {
	Handler            http.Handler
	AuthenticationFunc AuthenticationFunc
	File               string
	ErrorEncoder       ErrorEncoder
	// contains filtered or unexported fields
}

func (*ValidationHandler) Load added in v0.10.0

func (h *ValidationHandler) Load() error

func (*ValidationHandler) Middleware added in v0.12.0

func (h *ValidationHandler) Middleware(next http.Handler) http.Handler

Middleware implements gorilla/mux MiddlewareFunc

func (*ValidationHandler) ServeHTTP added in v0.10.0

func (h *ValidationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

Jump to

Keyboard shortcuts

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