openapi3filter

package
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2019 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

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

Index

Constants

This section is empty.

Variables

View Source
var DefaultOptions = &Options{}
View Source
var (
	ErrAuthenticationServiceMissing = errors.New("Request validator doesn't have an authentication service defined")
)
View Source
var ErrInvalidRequired = errors.New("must have a value")

ErrInvalidRequired is an error that happens when a required value of a parameter or request's body is not defined.

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

Functions

func FileBodyDecoder added in v0.6.2

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 RegisterBodyDecoder added in v0.6.2

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.

func TrimJSONPrefix

func TrimJSONPrefix(data []byte) []byte

TrimJSONPrefix trims one of the possible prefixes

func UnregisterBodyDecoder added in v0.6.2

func UnregisterBodyDecoder(contentType string)

UnregisterBodyDecoder dissociates a body decoder from a content type.

Decoding this content type will result in an error.

func ValidateParameter

func ValidateParameter(c 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(c 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(c 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(c 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(c context.Context, input *RequestValidationInput, srs openapi3.SecurityRequirements) error

ValidateSecurityRequirements validates a multiple OpenAPI 3 security requirements. Returns nil if one of them inputed. Otherwise returns an error describing the security failures.

Types

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.6.2

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{}.

type ContentParameterDecoder added in v0.6.2

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

A ContentParameterDecoder takes a parameter definition from the swagger 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.6.2

type EncodingFn func(partName string) *openapi3.Encoding

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

type Options

type Options struct {
	ExcludeRequestBody    bool
	ExcludeResponseBody   bool
	IncludeResponseStatus bool
	AuthenticationFunc    func(c context.Context, input *AuthenticationInput) error
}

type ParseError added in v0.6.2

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.6.2

func (e *ParseError) Error() string

func (*ParseError) Path added in v0.6.2

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

Path returns a path to the root cause.

func (*ParseError) RootCause added in v0.6.2

func (e *ParseError) RootCause() error

RootCause returns a root cause of ParseError.

type ParseErrorKind added in v0.6.2

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
	Status      int
	Reason      string
	Err         error
}

func (*RequestError) Error

func (err *RequestError) Error() string

func (*RequestError) HTTPStatus

func (err *RequestError) HTTPStatus() int

type RequestValidationInput

type RequestValidationInput struct {
	Request      *http.Request
	PathParams   map[string]string
	QueryParams  url.Values
	Route        *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
}

func (*ResponseError) Error

func (err *ResponseError) Error() string

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 Route

type Route struct {
	Swagger   *openapi3.Swagger
	Server    *openapi3.Server
	Path      string
	PathItem  *openapi3.PathItem
	Method    string
	Operation *openapi3.Operation

	// For developers who want use the router for handling too
	Handler http.Handler
}

type RouteError

type RouteError struct {
	Route  Route
	Reason string
}

func (*RouteError) Error

func (err *RouteError) Error() string

type Router

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

Router maps a HTTP request to an OpenAPI operation.

func NewRouter

func NewRouter() *Router

NewRouter creates a new router.

If the given Swagger has servers, router will use them. All operations of the Swagger will be added to the router.

func (*Router) AddRoute

func (router *Router) AddRoute(route *Route) error

AddRoute adds a route in the router.

func (*Router) AddSwagger

func (router *Router) AddSwagger(swagger *openapi3.Swagger) error

AddSwagger adds all operations in the OpenAPI specification.

func (*Router) AddSwaggerFromFile

func (router *Router) AddSwaggerFromFile(path string) error

AddSwaggerFromFile loads the Swagger file and adds it using AddSwagger.

func (*Router) FindRoute

func (router *Router) FindRoute(method string, url *url.URL) (*Route, map[string]string, error)

func (*Router) WithSwagger

func (router *Router) WithSwagger(swagger *openapi3.Swagger) *Router

WithSwagger adds all operations in the OpenAPI specification. Panics on any error.

func (*Router) WithSwaggerFromFile

func (router *Router) WithSwaggerFromFile(path string) *Router

WithSwaggerFromFile loads the Swagger file and adds it using WithSwagger. Panics on any error.

type Routers

type Routers []*Router

Routers maps a HTTP request to a Router.

func (Routers) FindRoute

func (routers Routers) FindRoute(method string, url *url.URL) (*Router, *Route, map[string]string, error)

type SecurityRequirementsError

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

func (*SecurityRequirementsError) Error

func (err *SecurityRequirementsError) Error() string

Jump to

Keyboard shortcuts

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