middleware

package
v0.0.0-...-a942fbd Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2023 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequestMalformedToken                = httperrors.NewHTTPError(http.StatusBadRequest, "MALFORMED_TOKEN", "Auth token is malformed")
	ErrUnauthorizedLastAuthenticatedAtExceeded = httperrors.NewHTTPError(http.StatusUnauthorized, "LAST_AUTHENTICATED_AT_EXCEEDED", "LastAuthenticatedAt timestamp exceeds threshold, re-authentication required")
	ErrForbiddenUserDeactivated                = httperrors.NewHTTPError(http.StatusForbidden, "USER_DEACTIVATED", "User account is deactivated")
	ErrForbiddenMissingScopes                  = httperrors.NewHTTPError(http.StatusForbidden, "MISSING_SCOPES", "User is missing required scopes")
	ErrAuthTokenValidationFailed               = errors.New("auth token validation failed")
)
View Source
var (
	DefaultAuthConfig = AuthConfig{
		Mode:            AuthModeRequired,
		FailureMode:     AuthFailureModeUnauthorized,
		TokenSource:     AuthTokenSourceHeader,
		TokenSourceKey:  echo.HeaderAuthorization,
		Scheme:          "Bearer",
		Skipper:         middleware.DefaultSkipper,
		FormatValidator: DefaultAuthTokenFormatValidator,
		TokenValidator:  DefaultAuthTokenValidator,
		Scopes:          []string{auth.AuthScopeApp.String()},
	}
)
View Source
var (
	DefaultCacheControlConfig = CacheControlConfig{
		Skipper: middleware.DefaultSkipper,
	}
)
View Source
var (
	DefaultLoggerConfig = LoggerConfig{
		Skipper:                  middleware.DefaultSkipper,
		Level:                    zerolog.DebugLevel,
		LogRequestBody:           false,
		LogRequestHeader:         false,
		LogRequestQuery:          false,
		RequestBodyLogSkipper:    DefaultRequestBodyLogSkipper,
		RequestBodyLogReplacer:   DefaultBodyLogReplacer,
		RequestHeaderLogReplacer: DefaultHeaderLogReplacer,
		RequestQueryLogReplacer:  DefaultQueryLogReplacer,
		LogResponseBody:          false,
		LogResponseHeader:        false,
		ResponseBodyLogSkipper:   DefaultResponseBodyLogSkipper,
		ResponseBodyLogReplacer:  DefaultBodyLogReplacer,
	}
)
View Source
var (

	// DefaultNoCacheConfig is the default nocache middleware config.
	DefaultNoCacheConfig = NoCacheConfig{
		Skipper: middleware.DefaultSkipper,
	}
)

Functions

func Auth

func Auth(s *api.Server) echo.MiddlewareFunc

func AuthWithConfig

func AuthWithConfig(config AuthConfig) echo.MiddlewareFunc

func CacheControl

func CacheControl() echo.MiddlewareFunc

func CacheControlWithConfig

func CacheControlWithConfig(config CacheControlConfig) echo.MiddlewareFunc

func DefaultAuthTokenFormatValidator

func DefaultAuthTokenFormatValidator(token string) bool

func DefaultAuthTokenValidator

func DefaultAuthTokenValidator(c echo.Context, config AuthConfig, token string) (auth.AuthenticationResult, error)

func DefaultBodyLogReplacer

func DefaultBodyLogReplacer(body []byte) []byte

DefaultBodyLogReplacer returns the body received without any modifications.

func DefaultHeaderLogReplacer

func DefaultHeaderLogReplacer(header http.Header) http.Header

DefaultHeaderLogReplacer replaces all Authorization, X-CSRF-Token and Proxy-Authorization header entries with a redacted string, indicating their presence without revealing actual, potentially sensitive values in the logs.

func DefaultQueryLogReplacer

func DefaultQueryLogReplacer(query url.Values) url.Values

DefaultQueryLogReplacer returns the query received without any modifications.

func DefaultRequestBodyLogSkipper

func DefaultRequestBodyLogSkipper(req *http.Request) bool

DefaultRequestBodyLogSkipper returns true for all requests with Content-Type application/x-www-form-urlencoded or multipart/form-data as those might contain binary or URL-encoded file uploads unfit for logging purposes.

func DefaultResponseBodyLogSkipper

func DefaultResponseBodyLogSkipper(req *http.Request, res *echo.Response) bool

DefaultResponseBodyLogSkipper returns false for all responses with Content-Type application/json, preventing logging for all other types of payloads as those might contain binary or URL-encoded data unfit for logging purposes.

func Logger

func Logger() echo.MiddlewareFunc

func LoggerWithConfig

func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc

func NoCache

func NoCache() echo.MiddlewareFunc

NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router (or subrouter) from being cached by an upstream proxy and/or client.

As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:

Expires: Thu, 01 Jan 1970 00:00:00 UTC
Cache-Control: no-cache, private, max-age=0
X-Accel-Expires: 0
Pragma: no-cache (for HTTP/1.0 proxies/clients)

func NoCacheWithConfig

func NoCacheWithConfig(config NoCacheConfig) echo.MiddlewareFunc

NoCacheWithConfig returns a nocache middleware with config.

func Noop

func Noop() echo.MiddlewareFunc

Types

type AuthConfig

type AuthConfig struct {
	S               *api.Server              // API server used for database and service access
	Mode            AuthMode                 // Controls type of authentication required (default: AuthModeRequired)
	FailureMode     AuthFailureMode          // Controls response on auth failure (default: AuthFailureModeUnauthorized)
	TokenSource     AuthTokenSource          // Sets source of auth token (default: AuthTokenSourceHeader)
	TokenSourceKey  string                   // Sets key for auth token source lookup (default: "Authorization")
	Scheme          string                   // Sets required token scheme (default: "Bearer")
	Skipper         middleware.Skipper       // Controls skipping of certain routes (default: no skipped routes)
	FormatValidator AuthTokenFormatValidator // Validates the format of the token retrieved
	TokenValidator  AuthTokenValidator       // Validates token retrieved and returns associated user (default: performs lookup in access_tokens table)
	Scopes          []string                 // List of scopes required to access endpoint (default: none required)
}

func (AuthConfig) CheckLastAuthenticatedAt

func (c AuthConfig) CheckLastAuthenticatedAt(user *models.User) bool

func (AuthConfig) CheckUserScopes

func (c AuthConfig) CheckUserScopes(user *models.User) bool

type AuthFailureMode

type AuthFailureMode int
const (
	// AuthFailureModeUnauthorized returns a 401 Unauthorized response on missing or invalid authentication
	AuthFailureModeUnauthorized AuthFailureMode = iota
	// AuthFailureModeNotFound returns a 404 Not Found response on missing or invalid authentication
	AuthFailureModeNotFound
)

func (AuthFailureMode) Error

func (m AuthFailureMode) Error() error

func (AuthFailureMode) String

func (m AuthFailureMode) String() string

type AuthMode

type AuthMode int

AuthMode controls the type of authentication check performed for a specific route or group

const (
	// AuthModeRequired requires an auth token to be present and valid in order to access the route or group
	AuthModeRequired AuthMode = iota
	// AuthModeSecure requires an auth token to be present and for the user to have recently re-confirmed their authentication in order to access the route or group
	AuthModeSecure
	// AuthModeOptional does not require an auth token to be present, however if it is, it must be valid in order to access the route or group
	AuthModeOptional
	// AuthModeTry does not require an auth token to be present in order to access the route or group and will process the request even if an invalid one has been provided
	AuthModeTry
	// AuthModeNone does not require an auth token to be present in order to access the route or group and will not attempt to parse any authentication provided
	AuthModeNone
)

func (AuthMode) String

func (m AuthMode) String() string

type AuthTokenFormatValidator

type AuthTokenFormatValidator func(string) bool

type AuthTokenSource

type AuthTokenSource int
const (
	// AuthTokenSourceHeader retrieves the auth token from a header, specified by TokenSourceKey
	AuthTokenSourceHeader AuthTokenSource = iota
	// AuthTokenSourceQuery retrieves the auth token from a query parameter, specified by TokenSourceKey
	AuthTokenSourceQuery
	// AuthTokenSourceForm retrieves the auth token from a form parameter, specified by TokenSourceKey
	AuthTokenSourceForm
)

func (AuthTokenSource) Extract

func (s AuthTokenSource) Extract(c echo.Context, key string, scheme string) (token string, exists bool)

func (AuthTokenSource) String

func (s AuthTokenSource) String() string

type AuthTokenValidator

type AuthTokenValidator func(c echo.Context, config AuthConfig, token string) (auth.AuthenticationResult, error)

type BodyLogReplacer

type BodyLogReplacer func(body []byte) []byte

BodyLogReplacer defines a function to replace certain parts of a body before logging it, mainly used to strip sensitive information from a request or response payload. The []byte returned should contain a sanitized payload ready for logging.

type CacheControlConfig

type CacheControlConfig struct {
	Skipper middleware.Skipper
}

type HeaderLogReplacer

type HeaderLogReplacer func(header http.Header) http.Header

HeaderLogReplacer defines a function to replace certain parts of a header before logging it, mainly used to strip sensitive information from a request or response header. The http.Header returned should be a sanitized copy of the original header as not to modify the request or response while logging.

type LoggerConfig

type LoggerConfig struct {
	Skipper                   middleware.Skipper
	Level                     zerolog.Level
	LogRequestBody            bool
	LogRequestHeader          bool
	LogRequestQuery           bool
	RequestBodyLogSkipper     RequestBodyLogSkipper
	RequestBodyLogReplacer    BodyLogReplacer
	RequestHeaderLogReplacer  HeaderLogReplacer
	RequestQueryLogReplacer   QueryLogReplacer
	LogResponseBody           bool
	LogResponseHeader         bool
	ResponseBodyLogSkipper    ResponseBodyLogSkipper
	ResponseBodyLogReplacer   BodyLogReplacer
	ResponseHeaderLogReplacer HeaderLogReplacer
}

type NoCacheConfig

type NoCacheConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper
}

NoCacheConfig defines the config for nocache middleware.

type QueryLogReplacer

type QueryLogReplacer func(query url.Values) url.Values

QueryLogReplacer defines a function to replace certain parts of a URL query before logging it, mainly used to strip sensitive information from a request query. The url.Values returned should be a sanitized copy of the original query as not to modify the request while logging.

type RequestBodyLogSkipper

type RequestBodyLogSkipper func(req *http.Request) bool

RequestBodyLogSkipper defines a function to skip logging certain request bodies. Returning true skips logging the payload of the request.

type ResponseBodyLogSkipper

type ResponseBodyLogSkipper func(req *http.Request, res *echo.Response) bool

ResponseBodyLogSkipper defines a function to skip logging certain response bodies. Returning true skips logging the payload of the response.

Jump to

Keyboard shortcuts

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