middleware

package
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoKeyProvided = errors.New("no key provided")
	ErrNotAuthorized = errors.New("not authorized")
)

Functions

func CacheControlMaxAge

func CacheControlMaxAge(seconds uint32) *uint32

func DefaultCORS

func DefaultCORS() webserver.HandlerFunc

DefaultCORS creates a default CORS middleware that allows requests from anywhere

func DefaultSafeBrowsing

func DefaultSafeBrowsing() webserver.HandlerFunc

DefaultSafeBrowsing creates a default SafeBrowsing middleware with commonly used options

func DisableClientCache

func DisableClientCache() webserver.HandlerFunc

DisableClientCache creates a default cache control middleware that disables the client's cache

func NewAuth

func NewAuth(opts AuthOptions) webserver.HandlerFunc

NewAuth wraps a middleware that verifies authentication

func NewCORS

func NewCORS(opts CORSOptions) webserver.HandlerFunc

NewCORS creates a new CORS middleware based on the specified options

func NewCacheControl

func NewCacheControl(opts CacheControlOptions) webserver.HandlerFunc

NewCacheControl creates a new client cache control middleware based on the specified options

func NewCompression

func NewCompression(level CompressionLevel) webserver.HandlerFunc

NewCompression creates a middleware that compress the output

func NewConditional

NewConditional wraps a middleware to conditionally execute or skip it depending on the evaluator's return value

func NewETag

func NewETag(weak bool) webserver.HandlerFunc

NewETag creates a middleware that adds/checks etags

func NewNoOP

func NewNoOP() webserver.HandlerFunc

NewNoOP creates a no-operation middleware

func NewPanic

func NewPanic(opts PanicOptions) webserver.HandlerFunc

NewPanic wraps a middleware that recovers from panics

func NewRateLimiter

func NewRateLimiter(opts RateLimiterOptions) webserver.HandlerFunc

NewRateLimiter wraps a middleware that limits the amount of requests from the same source.

func NewSafeBrowsing

func NewSafeBrowsing(opts SafeBrowsingOptions) webserver.HandlerFunc

NewSafeBrowsing creates a new SafeBrowsing middleware based on the specified options

func NewTrailingSlash

func NewTrailingSlash(opts TrailingSlashOptions) webserver.HandlerFunc

NewTrailingSlash creates a new middleware to handle trailing slashes in request's paths

Types

type AuthErrorHandler

type AuthErrorHandler func(req *webserver.RequestContext, err error) error

AuthErrorHandler defines a function to call when the authorization fails

type AuthOptions

type AuthOptions struct {
	// ErrorHandler defines a handler to execute if authorization fails. If not defined, will return 401 if err is nil
	// else 500.
	ErrorHandler AuthErrorHandler

	// DisableAuthorizationBearer disables inspection of the Authorization Bearer header.
	// NOTE: This check has priority over the rest.
	DisableAuthorizationBearer bool

	// If HeaderName is defined, the value of that header will be used as the key if present.
	// NOTE: HeaderName is evaluated if Authorization Bearer is not present/checked.
	HeaderName string

	// If QueryName is defined, the value of that query parameter will be used as the key if present.
	// NOTE: QueryName is evaluated after the above.
	QueryName string

	// If CookieName is defined, the value of that cookie will be used as the key if present.
	// NOTE: CookieName is evaluated after the above.
	CookieName string

	// ValidateHandler is a function to validate key.
	ValidateHandler AuthValidatorFunc
}

AuthOptions defines an authorization check

type AuthValidatorFunc

type AuthValidatorFunc func(*webserver.RequestContext, []byte) (bool, error)

AuthValidatorFunc defines a function that verifies if the given key is valid

type CORSOptions

type CORSOptions struct {
	// List of origins that may access the resource. Defaults to "*" if list is empty.
	AllowOrigins []string `json:"allow-origins,omitempty"`

	// List methods allowed when accessing the resource. If the list is defined but empty, the preflight `Allow`
	// request header value will be used.
	AllowMethods []string `json:"allow-methods,omitempty"`

	// List of request headers that can be used when making the actual request.
	AllowHeaders []string `json:"allow-headers,omitempty"`

	// This flag indicates whether the response to the request can be exposed when the credentials flag is true.
	// Ignored if allowed origins is "*".
	// See: http://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	AllowCredentials bool `json:"allow-credentials,omitempty"`

	// A whitelist headers that clients are allowed to access.
	ExposeHeaders []string `json:"expose-headers,omitempty"`

	// This field indicates  how many seconds the results of a preflight request can be cached. Defaults to 0.
	MaxAge int `json:"max-age,omitempty"`

	// This flag indicates whether the Access-Control-Allow-Private-Network response header should be set to true and
	// allow requests from private networks. Defaults to false.
	AllowPrivateNetwork bool
}

CORSOptions defines the behavior on how CORS requests should be handled.

type CacheControlOptions

type CacheControlOptions struct {
	Public                        bool
	Private                       bool
	NoCache                       bool
	NoStore                       bool
	NoTransform                   bool
	MustRevalidate                bool
	ProxyRevalidate               bool
	MaxAgeInSeconds               *uint32
	SharedMaxAgeInSeconds         *uint32
	StaleWhileRevalidateInSeconds *uint32
	StaleIfErrorInSeconds         *uint32
}

CacheControlOptions defines the behavior on how Cache-Control headers are sent.

type CompressionLevel

type CompressionLevel int
const (
	CompressionLevelDefault    CompressionLevel = 0
	CompressionLevelFavorSpeed CompressionLevel = 1
	CompressionLevelFavorSize  CompressionLevel = 2
)

type ConditionEvaluator

type ConditionEvaluator func(req *webserver.RequestContext) (bool, error)

ConditionEvaluator defines a function that executes the wrapped middleware if returns true

type KeyGeneratorFunc

type KeyGeneratorFunc func(req *webserver.RequestContext) []byte

KeyGeneratorFunc defines a function to call when the authorization fails

type LimitReachedHandler

type LimitReachedHandler func(req *webserver.RequestContext) error

LimitReachedHandler defines a function to call when the authorization fails

type PanicErrorHandler

type PanicErrorHandler func(req *webserver.RequestContext, err error, stack []byte) error

PanicErrorHandler defines a function to call when a panic occurs.

type PanicOptions

type PanicOptions struct {
	// StackSize establishes the maximum stack buffer to print in bytes.
	StackSize int `json:"stackSize,omitempty"`

	// IncludeAllGoRoutines, if true, then the stack of all the go routines are included.
	IncludeAllGoRoutines bool `json:"includeAllGoRoutines,omitempty"`

	// PanicErrorHandler is an optional custom callback to call if a panic is raised.
	PanicErrorHandler PanicErrorHandler
}

PanicOptions defines the behavior on how to deal with panics raised by request handlers.

type RateLimiterOptions

type RateLimiterOptions struct {
	// Max number of connections during `Expiration` seconds before sending a 429 response. Defaults to 6
	Max int

	// Expiration defines the window size. Defaults to 1 minute.
	Expiration time.Duration

	// KeyGenerator allows you to generate custom keys. Defaults to req.RemoteIP().String()
	KeyGenerator KeyGeneratorFunc

	// LimitReached is called when a request hits the limit. Defaults to return status 429.
	LimitReached LimitReachedHandler

	// If true, requests with StatusCode >= 400 won't be counted.
	SkipFailedRequests bool

	// Store is used to store the state of the middleware. If not defined, an internal memory storage will be used.
	ExternalStorage storage.Storage

	// MaxMemoryCacheSize indicates the maximum amount of memory to use if no external storage is used.
	MaxMemoryCacheSize int
}

RateLimiterOptions defines the behavior of the rate limiter middleware.

type SafeBrowsingOptions

type SafeBrowsingOptions struct {
	// XXSSProtection sets the `X-XSS-Protection` header to stops pages from loading when they detect reflected
	// cross-site scripting (XSS) attacks.
	// Optional. Defaults to "1; mode=block".
	XXSSProtection string `json:"x-xss-protection,omitempty"`

	// XContentTypeNoSniff sets the `X-Content-Type-Options` header to indicate that the MIME types advertised
	// in the Content-Type headers should be followed and not be changed.
	// Optional. Defaults to "nosniff".
	XContentTypeNoSniff string `json:"x-content-type-options,omitempty"`

	// XFrameOptions can be used to indicate whether a browser should be allowed to render a page in a <frame>,
	// <iframe> or <object>.
	// Optional. Defaults to "sameorigin".
	// Possible values: "sameorigin", "deny", "allow-from uri"
	XFrameOptions string `json:"x-frame-options,omitempty"`

	// HSTS controls the `Strict-Transport-Security` header to inform browsers that the site should only be
	// accessed using HTTPS, and that any future attempts to access it using HTTP should automatically be
	// converted to HTTPS.
	HSTS struct {
		// MaxAge establishes the time, in seconds, that the browser should remember that a site is only to be
		// accessed using HTTPS.
		// Optional. Defaults to 0.
		MaxAge uint `json:"max-age,omitempty"`

		// IncludeSubdomains is used to apply the HSTS settings to all the site's subdomains as well. Optional.
		IncludeSubdomains bool `json:"include-subdomains,omitempty"`

		// Preload will add the preload tag in the HSTS header. See https://hstspreload.org/ for details. Optional.
		Preload bool `json:"preload,omitempty"`
	} `json:"hsts,omitempty"`

	// ContentSecurityPolicy sets the `Content-Security-Policy` header to enhance security against XSS. Optional.
	ContentSecurityPolicy string `json:"content-security-policy,omitempty"`

	// ContentSecurityPolicyReportOnly would use the `Content-Security-Policy-Report-Only` header instead
	// of the `Content-Security-Policy` header. Used to report violations instead of blocking resources. Optional.
	ContentSecurityPolicyReportOnly bool `json:"csp-report-only,omitempty"`

	// ReferrerPolicy sets the `Referrer-Policy` header providing security against leaking potentially sensitive
	// request paths to third parties. Optional.
	ReferrerPolicy string `json:"referrer-policy,omitempty"`
}

SafeBrowsingOptions defines how common response headers for safe browsing are added.

type TrailingSlashOptions

type TrailingSlashOptions struct {
	// Remove tells the middleware to remove trailing slashes if present.
	// If this setting is false, then the trailing slash is added if absent.
	Remove bool

	// RedirectCode, if not zero, will make the middleware to return a redirect response.
	RedirectCode uint
}

TrailingSlashOptions defines a middleware that adds or removes trailing slashes in paths.

Jump to

Keyboard shortcuts

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