middleware

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2023 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const CSRFNonceCtxKey csrfCtxKey = 1
View Source
const CSRFNonceRequestParamName = "_csrf"
View Source
const CSRFRestNonceHeaderName = "X-Csrf-Token"

Variables

View Source
var CSRFExpirationTime = 1 * time.Hour
View Source
var Error2HttpStatusCode = func(err error) int {
	if _, ok := err.(errors.ErrBadRequest); ok {
		return http.StatusBadRequest
	} else if _, ok := err.(errors.ErrObjectNotFound); ok {
		return http.StatusNotFound
	} else if err == errors.ErrUnauthorizedRequest {
		return http.StatusUnauthorized
	} else if err == errors.ErrWrongCredentials ||
		err == errors.ErrAccessDenied {
		return http.StatusForbidden
	}
	return http.StatusInternalServerError
}

Error2HttpStatusCode translates an error to an HTTP status code

Functions

func GetCSRFNonceFromContext

func GetCSRFNonceFromContext(ctx context.Context) string

GetCSRFNonceFromContext returns the CSRF nonce from the request context.Context

Types

type CorsConfig

type CorsConfig struct {
	// determines if any origin is allowed to make request
	AnyOriginAllowed bool
	// this flag should be true when the resource supports user credentials in the request and false otherwise.
	SupportsCredentials bool
	// indicates how long the results of a pre-flight request can be cached in a pre-flight result cache
	PreflightMaxAgeSeconds int
	// a list of exposed headers that the resource might use and can be exposed (can be empty)
	ExposedHeaders []string
	// a list of methods that are supported by the resource (can be empty)
	AllowedHttpMethods []string
	// a list of headers that are supported by the resource (can be empty)
	AllowedHttpHeaders []string
	// a list of origins that are allowed access to the resource (can be empty)
	AllowedOrigins []string
}

CorsConfig encapsulates the cors middleware settings

type Middleware

type Middleware func(handler handler.Handler) handler.Handler

A Middleware is a function that receives a NewMuxHandler and returns another NewMuxHandler

func Authorize added in v1.2.0

func Authorize(supplier PermissionsSupplierFunc, matchAllPermissions bool) Middleware

Authorize checks if the authenticated auth.SecurityPrincipal has all permission if the parameter matchAllPermissions is true or at least one permission, otherwise An errors.ErrUnauthorizedRequest error is returned if not at least one permission is allowed to be executed by the current auth.SecurityPrincipal

func AuthorizeAll

func AuthorizeAll(permissions ...auth.Permission) Middleware

AuthorizeAll checks if the authenticated auth.SecurityPrincipal has all the requested permissions An errors.ErrUnauthorizedRequest error is returned if not all permissions are allowed to be executed by the current auth.SecurityPrincipal

func AuthorizeAny

func AuthorizeAny(permissions ...auth.Permission) Middleware

AuthorizeAny checks if the authenticated auth.SecurityPrincipal has at least one from the requested permissions An errors.ErrUnauthorizedRequest error is returned if not at least one permission is allowed to be executed by the current auth.SecurityPrincipal

func CSRFPrevention

func CSRFPrevention(nonceCache cache.Cache) Middleware

CSRFPrevention provides basic CSRF protection for a web application

func CSRFPreventionWithCustomParamAndHeaderName

func CSRFPreventionWithCustomParamAndHeaderName(nonceCache cache.Cache, csrfNonceRequestParamName string, csrfRestNonceHeaderName string) Middleware

CSRFPreventionWithCustomParamAndHeaderName provides basic CSRF protection for a web application using a custom form param name and header name

func CompressResponse

func CompressResponse(compressionLevel int) Middleware

CompressResponse enables the HTTP response compressing as long as the client support it via `Accept-Encoding` request header

func Cors

func Cors(config CorsConfig) Middleware

Cors enable client-side cross-origin requests by implementing W3C's CORS (Cross-Origin Resource Sharing) specification for resources This function is a transcription of Java code org.apache.catalina.filters.CorsFilter

func ErrJsonResponse

func ErrJsonResponse() Middleware

ErrJsonResponse translates an error to a JSON response

func ErrResponse

func ErrResponse(responseSupplier ResponseSupplier) Middleware

ErrResponse translates an error to an response.HttpResponse

func PanicRecover

func PanicRecover() Middleware

PanicRecover is middleware that recovers from panic and convert it to an error

func RequestDumper added in v1.0.0

func RequestDumper(logger func(val string)) Middleware

RequestDumper dumps the request (before processing) and the corresponding response in JSON format. It is especially useful in debugging problems.

func SecurityHeaders

func SecurityHeaders(config SecurityHeadersConfig) Middleware

SecurityHeaders provides some security HTTP headers to the response

func SecurityPrincipalSupplier added in v1.0.0

func SecurityPrincipalSupplier(sps SecurityPrincipalSupplierFunc) Middleware

SecurityPrincipalSupplier extracts the auth.SecurityPrincipal and propagate it to the context.Context

type PermissionsSupplierFunc added in v1.2.0

type PermissionsSupplierFunc func(ctx context.Context, mc path.MatchingContext) ([]auth.Permission, error)

type ResponseSupplier

type ResponseSupplier func(statusCode int, err error) response.HttpResponse

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	STS                         ShStrictTransportSecurityConfig
	ClickJacking                ShClickJackingConfig
	BlockContentSniffingEnabled bool
	XSSProtectionEnabled        bool
}

type SecurityPrincipalSupplierFunc added in v1.0.0

type SecurityPrincipalSupplierFunc func(ctx context.Context, mc path.MatchingContext) (auth.SecurityPrincipal, error)

type ShClickJackingConfig

type ShClickJackingConfig struct {
	Enabled                 bool
	XFrameOption            XFrameOption
	XFrameOptionHeaderValue string
	XFrameAllowFromUri      string
	// contains filtered or unexported fields
}

type ShStrictTransportSecurityConfig

type ShStrictTransportSecurityConfig struct {
	Enabled           bool
	MaxAgeSeconds     int
	IncludeSubDomains bool
	Preload           bool
	// contains filtered or unexported fields
}

type XFrameOption

type XFrameOption int
const (
	XFrameOptionDeny XFrameOption = iota
	XFrameOptionSameOrigin
	XFrameOptionAllowFrom
)

Jump to

Keyboard shortcuts

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