openapi

package module
v0.0.0-...-3d079a0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2023 License: Apache-2.0 Imports: 17 Imported by: 1

README

Caddy OpenAPI Validator (WIP)

A Caddy module that validates requests and responses against an OpenAPI specification.

Description

The OpenAPI Validator module is a Caddy HTTP handler that validates requests and responses against an OpenAPI specification. The kin-openapi openapi3filter library performs the actual validation. The handler in this repository is a small wrapper for the functionality provided by openapi3filter, with basic configuration and integrations options for Caddy. The project is currently in POC stage, meaning that much of it can, and likely will, change.

The request/response flow is as follows:

  • When a request arrives, the Validator will look for a valid route in the provided OpenAPI specification and validate the request against the schema.
  • The request is then passed on to the next HTTP handler in the chain and the Validator will wait for its response.
  • After capturing the response, the Validator will validate the response to be valid.
  • If no errors occurred during the validation, the response will be returned.

Usage

The simplest way to use the OpenAPI Validator HTTP handler is by using xcaddy:

$ xcaddy build v2.1.1 --with github.com/hslatman/caddy-openapi-validator

Alternatively, the HTTP handler can be included as a Caddy module as follows:

import (
	_ "github.com/hslatman/caddy-openapi-validator"
)

Configure the OpenAPI Validator handler as one of the handlers to be executed by Caddy (in JSON config format):

    ...
        "handle": [
            {
                "handler": "openapi_validator",
                "filepath": "examples/petstore.yaml",
                "validate_routes": true,
                "validate_requests": true,
                "validate_responses": true,
                "validate_servers": true,
                "validate_security": true,
                "path_prefix_to_be_trimmed": "",
                "additional_servers": [""],
                "enforce": true,
                "log": true
            }
        ]
    ...

The OpenAPI Validator handler should be called before an actual API is called. The configuration shown above shows the default settings. The filepath configuration is required; without it, or when pointing to a non-existing file, the module won't be loaded.

Example

An example of the OpenAPI Validatory HTTP handler in use can be found here.

Notes

This project is currently a small POC with the intention to grow it along with my other projects using Go, OpenAPI and Caddy. I only recently started using Caddy, so there may be some rough edges to iron out when more use cases present themselves.

TODO

A small and incomplete list of potential things to implement, improve and think about:

  • Add more tests for the OpenAPI Validator functionality and configuration.
  • Improve Caddyfile handling (e.g. add more subdirectives).
  • Add an example that uses an HTTP proxy/fcgi configuration.
  • Look into ways to specify the error nicely, instead of just logging it (e.g. return error message(s) in specific format) and/or integrate properly with how Caddy handlers errors.
  • Look into if (and how) the Validator can be used outside of Caddy as an alternative (i.e. a more generic middleware).

Documentation

Index

Constants

View Source
const (
	// TKOpenAPIValidator is token for the main directive
	TKOpenAPIValidator = "openapi_validator"
	// TKFilepath is token for the subdirective that points to the OpenAPI filepath
	TKFilepath = "filepath"
	// TKValidateRoutes is token for the subdirective that sets route validation on or off
	TKValidateRoutes = "routes"
	// TKValidateRequests is token for the subdirective that sets requests validation on or off
	TKValidateRequests = "requests"
	// TKValidateResponses is token for the subdirective that sets response validation on or off
	TKValidateResponses = "responses"
)
View Source
const (
	// ReplacerOpenAPIValidatorErrorMessage is a Caddy Replacer key for storing OpenAPI validation error messages
	ReplacerOpenAPIValidatorErrorMessage = "openapi_validator.error_message"
	// ReplacerOpenAPIValidatorStatusCode is a Caddy Replacer key for storing a status code
	ReplacerOpenAPIValidatorStatusCode = "openapi_validator.status_code"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Validator

type Validator struct {
	// The filepath to the OpenAPI (v3) specification to use
	Filepath string `json:"filepath,omitempty"`
	// Indicates whether routes should be validated
	// When ValidateRequests or ValidateResponses is true, ValidateRoutes should also be true
	// Default is true
	ValidateRoutes *bool `json:"validate_routes,omitempty"`
	// Indicates whether request validation should be enabled
	// Default is true
	ValidateRequests *bool `json:"validate_requests,omitempty"`
	// Indicates whether request validation should be enabled
	// Default is true
	ValidateResponses *bool `json:"validate_responses,omitempty"`
	// Indicates whether request validation should be enabled
	// Default is true
	ValidateServers *bool `json:"validate_servers,omitempty"`
	// Indicates whether request validation should be enabled
	// Default is true
	ValidateSecurity *bool `json:"validate_security,omitempty"`
	// URL path prefix that is trimmed from the URL path.
	// It can be of use when server validation is turned off
	// and the paths in an OpenAPI spec do not match the
	// implementation directly, i.e. are missing an /api prefix,
	// for example.
	// Default is empty string, resulting in no prefix trimming.
	PathPrefixToBeTrimmed string `json:"path_prefix_to_be_trimmed,omitempty"`
	// A list of additional servers to be considered valid when
	// when performing the request validation. The additional servers
	// are added to the servers in the OpenAPI specification.
	// Default is empty list
	AdditionalServers []string `json:"additional_servers,omitempty"`
	// Indicates whether the OpenAPI specification should be enforced, meaning that invalid
	// requests and responses will be filtered and an (appropriate) status is returned
	// Default is true
	Enforce *bool `json:"enforce,omitempty"`
	// To log or not to log
	// Default is true
	Log *bool `json:"log,omitempty"`
	// contains filtered or unexported fields
}

Validator is used to validate OpenAPI requests and responses against an OpenAPI specification

func (Validator) CaddyModule

func (Validator) CaddyModule() caddy.ModuleInfo

CaddyModule returns the Caddy module information.

func (*Validator) Provision

func (v *Validator) Provision(ctx caddy.Context) error

Provision sets up the OpenAPI Validator responder.

func (*Validator) ServeHTTP

func (v *Validator) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error

ServeHTTP is the Caddy handler for serving HTTP requests

func (*Validator) UnmarshalCaddyfile

func (v *Validator) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

UnmarshalCaddyfile parses (part of) the Caddyfile and configures a Validator

func (*Validator) Validate

func (v *Validator) Validate() error

Validate validates the configuration of the Validator

Jump to

Keyboard shortcuts

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