middleware

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2024 License: MIT Imports: 31 Imported by: 1

Documentation

Index

Constants

View Source
const (
	HttpServerMetricsRequestsCount    = "http_server_requests_total"
	HttpServerMetricsRequestsDuration = "http_server_requests_duration_seconds"
)
View Source
const GZIPEncoding string = "gzip"

GZIPEncoding content-encoding header if set to "gzip", decompress body contents.

Variables

View Source
var DefaultSecureConfig = SecureConfig{
	XSSProtection:      "1; mode=block",
	ContentTypeNosniff: "nosniff",
	XFrameOptions:      "SAMEORIGIN",
	HSTSPreloadEnabled: false,
}

DefaultSecureConfig is the default Secure middleware config.

View Source
var ErrCSRFInvalid = httpx.NewHTTPError(http.StatusForbidden, "invalid csrf token")

ErrCSRFInvalid is returned when CSRF check fails

View Source
var ErrExtractorError = httpx.NewHTTPError(http.StatusForbidden, "error while extracting identifier")

ErrExtractorError denotes an error raised when extractor function is unsuccessful

View Source
var ErrInvalidKey = httpx.NewHTTPError(http.StatusUnauthorized, "invalid key")

ErrInvalidKey denotes an error raised when key value is invalid by validator

View Source
var ErrKeyMissing = httpx.NewHTTPError(http.StatusUnauthorized, "missing key")

ErrKeyMissing denotes an error raised when key value could not be extracted from request

View Source
var ErrRateLimitExceeded = httpx.NewHTTPError(http.StatusTooManyRequests, "rate limit exceeded")

ErrRateLimitExceeded denotes an error raised when rate limit is exceeded

Functions

func BasicAuth

func BasicAuth(cfg BasicAuthConfig) func(http.Handler) http.Handler

BasicAuth returns an BasicAuth middleware.

For valid credentials it calls the next handler. For missing or invalid credentials, it sends "401 - Unauthorized" response.

func BodyLimit

func BodyLimit(cfg BodyLimitConfig) func(http.Handler) http.Handler

BodyLimit returns a BodyLimit middleware.

BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it sends "413 - Request Entity Too Large" response. The BodyLimit is determined based on both `Content-Length` request header and actual content read, which makes it super secure.

func CORS

func CORS(cfg CORSConfig) func(http.Handler) http.Handler

func CSRF

func CSRF(cfg CSRFConfig) func(http.Handler) http.Handler

func CheckMethod

func CheckMethod(method, skip string) (string, bool)

func Decompress

func Decompress(cfg DecompressConfig) func(http.Handler) http.Handler

func DefaultSkipper

func DefaultSkipper(*http.Request) bool

func Gzip

func Gzip(cfg GzipConfig) func(http.Handler) http.Handler

Gzip returns a middleware which compresses HTTP response using gzip compression scheme.

func KeyAuth

func KeyAuth(cfg KeyAuthConfig) func(http.Handler) http.Handler

KeyAuth returns an KeyAuth middleware.

For valid key it calls the next handler. For invalid key, it sends "401 - Unauthorized" response. For missing key, it sends "400 - Bad Request" response.

func NoCache

func NoCache() func(http.Handler) http.Handler

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 NormalizeStatus

func NormalizeStatus(status int) string

func RateLimiter

func RateLimiter(cfg RateLimiterConfig) func(http.Handler) http.Handler

func RealIP

func RealIP() func(http.Handler) http.Handler

RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the X-Forwarded-For or X-Real-IP headers.

This middleware should only be used if user can trust the headers sent with request. If reverse proxies are configured to pass along arbitrary header values from the client, or if this middleware used without a reverse proxy, malicious clients could set anything as X-Forwarded-For header and attack the server in various ways.

func Recover

func Recover(cfg RecoverConfig) func(http.Handler) http.Handler

func RequestID

func RequestID() func(http.Handler) http.Handler

func RequestLogger

func RequestLogger(cfg RequestLoggerConfig) func(http.Handler) http.Handler

RequestLogger returns middleware that logs HTTP requests.

func RequestMetrics

func RequestMetrics(cfg RequestMetricsConfig) func(http.Handler) http.Handler

func RequestTracer

func RequestTracer(cfg RequestTracerConfig) func(http.Handler) http.Handler

func Response

func Response() func(http.Handler) http.Handler

func Secure

func Secure(cfg SecureConfig) func(http.Handler) http.Handler

Secure returns a Secure middleware. Secure middleware provides protection against cross-site scripting (XSS) attack, content type sniffing, clickjacking, insecure connection and other code injection attacks.

func Session

func Session(cfg SessionConfig) func(http.Handler) http.Handler

Types

type BasicAuthConfig

type BasicAuthConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// Validator is a function to validate credentials. Note: if request contains multiple basic auth headers
	// this function would be called once for each header until first valid result is returned
	// Required.
	Validator BasicAuthValidator `json:"-" yaml:"-"`

	// Realm is a string to define realm attribute.
	// Default value "Restricted".
	Realm string `json:"realm,omitempty" yaml:"realm,omitempty"`
}

type BasicAuthValidator

type BasicAuthValidator func(r *http.Request, user, password string) (*http.Request, bool, error)

type BodyLimitConfig

type BodyLimitConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// LimitBytes is maximum allowed size in bytes for a request body
	LimitBytes int64 `json:"limit_bytes,omitempty" yaml:"limit_bytes,omitempty"`
}

BodyLimitConfig defines the config for BodyLimitWithConfig middleware.

type CORSConfig

type CORSConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// AllowOriginFunc is a custom function to validate the origin. It takes the
	// origin as an argument and returns true if allowed or false otherwise. If
	// an error is returned, it is returned by the handler. If this option is
	// set, AllowOrigins is ignored.
	//
	// Security: use extreme caution when handling the origin, and carefully
	// validate any logic. Remember that attackers may register hostile domain names.
	// See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	//
	// Optional.
	AllowOriginFunc func(origin string) (bool, error) `json:"-" yaml:"-"`

	// AllowOrigins determines the value of the Access-Control-Allow-Origin
	// response header.  This header defines a list of origins that may access the
	// resource.  The wildcard characters '*' and '?' are supported and are
	// converted to regex fragments '.*' and '.' accordingly.
	//
	// Security: use extreme caution when handling the origin, and carefully
	// validate any logic. Remember that attackers may register hostile domain names.
	// See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	//
	// Optional. Default value []string{"*"}.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
	AllowOrigins []string `json:"allow_origins,omitempty" yaml:"allow_origins,omitempty"`

	// AllowMethods determines the value of the Access-Control-Allow-Methods
	// response header.  This header specified the list of methods allowed when
	// accessing the resource.  This is used in response to a preflight request.
	//
	// Optional. Default value DefaultCORSConfig.AllowMethods.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
	AllowMethods []string `json:"allow_methods,omitempty" yaml:"allow_methods,omitempty"`

	// AllowHeaders determines the value of the Access-Control-Allow-Headers
	// response header.  This header is used in response to a preflight request to
	// indicate which HTTP headers can be used when making the actual request.
	//
	// Optional. Default value []string{}.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
	AllowHeaders []string `json:"allow_headers,omitempty" yaml:"allow_headers,omitempty"`

	// AllowCredentials determines the value of the
	// Access-Control-Allow-Credentials response header.  This header indicates
	// whether or not the response to the request can be exposed when the
	// credentials mode (Request.credentials) is true. When used as part of a
	// response to a preflight request, this indicates whether or not the actual
	// request can be made using credentials.  See also
	// [MDN: Access-Control-Allow-Credentials].
	//
	// Optional. Default value false, in which case the header is not set.
	//
	// Security: avoid using `AllowCredentials = true` with `AllowOrigins = *`.
	// See "Exploiting CORS misconfigurations for Bitcoins and bounties",
	// https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
	AllowCredentials bool `json:"allow_credentials,omitempty" yaml:"allow_credentials,omitempty"`

	// UnsafeWildcardOriginWithAllowCredentials UNSAFE/INSECURE: allows wildcard '*' origin to be used with AllowCredentials
	// flag. In that case we consider any origin allowed and send it back to the client with `Access-Control-Allow-Origin` header.
	//
	// This is INSECURE and potentially leads to [cross-origin](https://portswigger.net/research/exploiting-cors-misconfigurations-for-bitcoins-and-bounties)
	// attacks. See: https://github.com/labstack/echo/issues/2400 or https://github.com/go-chi/cors/pull/6 or https://github.com/rs/cors/issues/55 for discussion on the subject.
	//
	// Optional. Default value is false.
	UnsafeWildcardOriginWithAllowCredentials bool `json:"unsafe_wildcard_origin_with_allow_credentials,omitempty" yaml:"unsafe_wildcard_origin_with_allow_credentials,omitempty"`

	// ExposeHeaders determines the value of Access-Control-Expose-Headers, which
	// defines a list of headers that clients are allowed to access.
	//
	// Optional. Default value []string{}, in which case the header is not set.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Header
	ExposeHeaders []string `json:"expose_headers,omitempty" yaml:"expose_headers,omitempty"`

	// MaxAge determines the value of the Access-Control-Max-Age response header.
	// This header indicates how long (in seconds) the results of a preflight
	// request can be cached.
	//
	// Optional. Default value 0.  The header is set only if MaxAge > 0.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
	MaxAge int `json:"max_age,omitempty" yaml:"max_age,omitempty"`
}

type CSRFConfig

type CSRFConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// TokenLength is the length of the generated token.
	TokenLength uint8 `json:"token_length,omitempty" yaml:"token_length,omitempty"`

	// TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:X-CSRF-Token".
	// Possible values:
	// - "header:<name>" or "header:<name>:<cut-prefix>"
	// - "query:<name>"
	// - "form:<name>"
	// Multiple sources example:
	// - "header:X-CSRF-Token,query:csrf"
	TokenLookup string `json:"token_lookup,omitempty" yaml:"token_lookup,omitempty"`

	// Generator defines a function to generate token.
	// Optional. Defaults tp randomString(TokenLength).
	Generator func() string `json:"-" yaml:"-"`

	// Context key to store generated CSRF token into context.
	// Optional. Default value "csrf".
	ContextKey string `json:"context_key,omitempty" yaml:"context_key,omitempty"`

	Cookie struct {
		Name     string        `json:"name" yaml:"name"`
		Domain   string        `json:"domain" yaml:"domain"`
		Path     string        `json:"path" yaml:"path"`
		MaxAge   time.Duration `json:"max_age,omitempty" yaml:"max_age,omitempty"`
		Secure   bool          `json:"secure" yaml:"secure"`
		HTTPOnly bool          `json:"http_only" yaml:"http_only"`
		SameSite SameSiteType  `json:"same_site" yaml:"same_site"`
	} `json:"cookie" yaml:"cookie"`
}

type DecompressConfig

type DecompressConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers
	GzipDecompressPool Decompressor `json:"-" yaml:"-"`
}

DecompressConfig defines the config for Decompress middleware.

type Decompressor

type Decompressor interface {
	// contains filtered or unexported methods
}

Decompressor is used to get the sync.Pool used by the middleware to get Gzip readers

type DefaultGzipDecompressPool

type DefaultGzipDecompressPool struct {
}

DefaultGzipDecompressPool is the default implementation of Decompressor interface

type Extractor

type Extractor func(r *http.Request) (string, error)

Extractor is used to extract data from http.Request

type ExtractorSource

type ExtractorSource string

ExtractorSource is type to indicate source for extracted value

const (
	// ExtractorSourceHeader means value was extracted from request header
	ExtractorSourceHeader ExtractorSource = "header"
	// ExtractorSourceQuery means value was extracted from request query parameters
	ExtractorSourceQuery ExtractorSource = "query"
	// ExtractorSourcePathParam means value was extracted from route path parameters
	ExtractorSourcePathParam ExtractorSource = "param"
	// ExtractorSourceCookie means value was extracted from request cookies
	ExtractorSourceCookie ExtractorSource = "cookie"
	// ExtractorSourceForm means value was extracted from request form values
	ExtractorSourceForm ExtractorSource = "form"
)

type GzipConfig

type GzipConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// Gzip compression level.
	Level int `json:"level,omitempty" yaml:"level,omitempty"`

	// Length threshold before gzip compression is applied.
	//
	// Most of the time you will not need to change the default. Compressing
	// a short response might increase the transmitted data because of the
	// gzip format overhead. Compressing the response will also consume CPU
	// and time on the server and the client (for decompressing). Depending on
	// your use case such a threshold might be useful.
	//
	// See also:
	// https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
	MinLength int `json:"min_length,omitempty" yaml:"min_length,omitempty"`
}

GzipConfig defines the config for Gzip middleware.

type KeyAuthConfig

type KeyAuthConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// KeyLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
	// to extract key from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>" or "header:<name>:<cut-prefix>"
	// 			`<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header
	//			value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we
	//			want to cut is `<auth-scheme> ` note the space at the end.
	//			In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `.
	// - "query:<name>"
	// - "form:<name>"
	// - "cookie:<name>"
	// Multiple sources example:
	// - "header:Authorization,header:X-Api-Key"
	KeyLookup string `json:"key_lookup,omitempty" yaml:"key_lookup,omitempty"`

	// Validator is a function to validate key.
	// Required.
	Validator KeyAuthValidator `json:"-" yaml:"-"`

	// ErrorHandler defines a function which is executed when all lookups have been done and none of them passed Validator
	// function. ErrorHandler is executed with last missing (ErrExtractionValueMissing) or an invalid key.
	// It may be used to define a custom error.
	//
	// Note: when error handler swallows the error (returns nil) middleware continues handler chain execution towards handler.
	// This is useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users
	// In that case you can use ErrorHandler to set default public auth value to request and continue with handler chain.
	ErrorHandler KeyAuthErrorHandler `json:"-" yaml:"-"`

	// ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to
	// ignore the error (by returning `nil`).
	// This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality.
	// In that case you can use ErrorHandler to set a default public key auth value in the request context
	// and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then.
	ContinueOnIgnoredError bool `json:"continue_on_ignored_error,omitempty" yaml:"continue_on_ignored_error,omitempty"`
}

KeyAuthConfig defines the config for KeyAuth middleware.

type KeyAuthErrorHandler

type KeyAuthErrorHandler func(r *http.Request, err error) error

KeyAuthErrorHandler defines a function which is executed for an invalid key.

type KeyAuthValidator

type KeyAuthValidator func(r *http.Request, key string, source ExtractorSource) (*http.Request, bool, error)

KeyAuthValidator defines a function to validate KeyAuth credentials.

type RateLimiterConfig

type RateLimiterConfig struct {
	Skipper Skipper `json:"-" yaml:"-"`

	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// Store defines a store for the rate limiter
	Store RateLimiterStore `json:"-" yaml:"-"`

	// IdentifierExtractor uses http.Request to extract the identifier for a visitor
	IdentifierExtractor Extractor `json:"-" yaml:"-"`

	// DenyHandler provides a handler to be called when RateLimiter denies access
	DenyHandler func(r *http.Request, identifier string, err error) error `json:"-" yaml:"-"`
}

RateLimiterConfig defines the configuration for the rate limiter

type RateLimiterMemoryStore

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

RateLimiterMemoryStore is the built-in store implementation for RateLimiter

func NewRateLimiterMemoryStore

func NewRateLimiterMemoryStore(cfg RateLimiterMemoryStoreConfig) *RateLimiterMemoryStore

NewRateLimiterMemoryStore returns an instance of RateLimiterMemoryStore with the provided configuration. Rate must be provided. Burst will be set to the rounded down value of the configured rate if not provided or set to 0.

The build-in memory store is usually capable for modest loads. For higher loads other store implementations should be considered.

Characteristics:

  • Concurrency above 100 parallel requests may causes measurable lock contention
  • A high number of different IP addresses (above 16000) may be impacted by the internally used Go map
  • A high number of requests from a single IP address may cause lock contention

Example:

limiterStore := middleware.NewRateLimiterMemoryStore(
	middleware.RateLimiterMemoryStoreConfig{Rate: 50, Burst: 200, ExpiresIn: 5 * time.Minute},
)

func (*RateLimiterMemoryStore) Allow

func (store *RateLimiterMemoryStore) Allow(identifier string) (bool, error)

Allow implements RateLimiterStore.Allow

type RateLimiterMemoryStoreConfig

type RateLimiterMemoryStoreConfig struct {
	Rate      float64       // Rate of requests allowed to pass as req/s. For more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit.
	Burst     int           // Burst is maximum number of requests to pass at the same moment. It additionally allows a number of requests to pass when rate limit is reached.
	ExpiresIn time.Duration // ExpiresIn is the duration after that a rate limiter is cleaned up
}

RateLimiterMemoryStoreConfig represents configuration for RateLimiterMemoryStore

type RateLimiterStore

type RateLimiterStore interface {
	Allow(identifier string) (bool, error)
}

RateLimiterStore is the interface to be implemented by custom stores.

type RecoverConfig

type RecoverConfig struct {
	// ErrorWrapper provides an error wrapper
	ErrorWrapper httpx.ErrorWrapper `json:"-" yaml:"-"`

	// Size of the stack to be printed.
	// Optional. Default value 4KB.
	StackSize int `json:"stack_size,omitempty" yaml:"stack_size,omitempty"`

	// DisableStackAll disables formatting stack traces of all other goroutines
	// into buffer after the trace for the current goroutine.
	// Optional. Default value false.
	DisableStackAll bool `json:"disable_stack_all,omitempty" yaml:"disable_stack_all,omitempty"`

	// DisablePrintStack disables printing stack trace.
	// Optional. Default value as false.
	DisablePrintStack bool `json:"disable_print_stack,omitempty" yaml:"disable_print_stack,omitempty"`
}

type RequestLoggerConfig

type RequestLoggerConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// Logger a logger to use in middleware.
	Logger *zap.Logger `json:"-" yaml:"-"`
}

RequestLoggerConfig is configuration for Request Logger middleware.

type RequestMetricsConfig

type RequestMetricsConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper                 Skipper               `json:"-" yaml:"-"`
	Registry                prometheus.Registerer `json:"-" yaml:"-"`
	Namespace               string                `json:"namespace,omitempty" yaml:"namespace,omitempty"`
	Buckets                 []float64             `json:"buckets,omitempty" yaml:"buckets,omitempty"`
	Subsystem               string                `json:"subsystem,omitempty" yaml:"subsystem,omitempty"`
	NormalizeRequestPath    bool                  `json:"normalize_request_path,omitempty" yaml:"normalize_request_path,omitempty"`
	NormalizeResponseStatus bool                  `json:"normalize_response_status,omitempty" yaml:"normalize_response_status,omitempty"`
}

type RequestTracerConfig

type RequestTracerConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper           Skipper                       `json:"-" yaml:"-"`
	TracerProvider    oteltrace.TracerProvider      `json:"-" yaml:"-"`
	TextMapPropagator propagation.TextMapPropagator `json:"-" yaml:"-"`
	ServiceName       string                        `json:"service_name,omitempty" yaml:"service_name,omitempty"`
}

type SameSiteType

type SameSiteType string
const (
	SameSiteDefault SameSiteType = "default"
	SameSiteLax     SameSiteType = "lax"
	SameSiteStrict  SameSiteType = "strict"
	SameSiteNone    SameSiteType = "none"
)

func (SameSiteType) HTTP

func (s SameSiteType) HTTP() http.SameSite

type SecureConfig

type SecureConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// XSSProtection provides protection against cross-site scripting attack (XSS)
	// by setting the `X-XSS-Protection` header.
	// Optional. Default value "1; mode=block".
	XSSProtection string `json:"xss_protection,omitempty" yaml:"xss_protection,omitempty"`

	// ContentTypeNosniff provides protection against overriding Content-Type
	// header by setting the `X-Content-Type-Options` header.
	// Optional. Default value "nosniff".
	ContentTypeNosniff string `json:"content_type_nosniff,omitempty" yaml:"content_type_nosniff,omitempty"`

	// XFrameOptions can be used to indicate whether or not a browser should
	// be allowed to render a page in a <frame>, <iframe> or <object> .
	// Sites can use this to avoid clickjacking attacks, by ensuring that their
	// content is not embedded into other sites.provides protection against
	// clickjacking.
	// Optional. Default value "SAMEORIGIN".
	// Possible values:
	// - "SAMEORIGIN" - The page can only be displayed in a frame on the same origin as the page itself.
	// - "DENY" - The page cannot be displayed in a frame, regardless of the site attempting to do so.
	// - "ALLOW-FROM uri" - The page can only be displayed in a frame on the specified origin.
	XFrameOptions string `json:"x_frame_options,omitempty" yaml:"x_frame_options,omitempty"`

	// HSTSMaxAge sets the `Strict-Transport-Security` header to indicate how
	// long (in seconds) browsers should remember that this site is only to
	// be accessed using HTTPS. This reduces your exposure to some SSL-stripping
	// man-in-the-middle (MITM) attacks.
	// Optional. Default value 0.
	HSTSMaxAge int `json:"hsts_max_age,omitempty" yaml:"hsts_max_age,omitempty"`

	// HSTSExcludeSubdomains won't include subdomains tag in the `Strict Transport Security`
	// header, excluding all subdomains from security policy. It has no effect
	// unless HSTSMaxAge is set to a non-zero value.
	// Optional. Default value false.
	HSTSExcludeSubdomains bool `json:"hsts_exclude_subdomains,omitempty" yaml:"hsts_exclude_subdomains,omitempty"`

	// ContentSecurityPolicy sets the `Content-Security-Policy` header providing
	// security against cross-site scripting (XSS), clickjacking and other code
	// injection attacks resulting from execution of malicious content in the
	// trusted web page context.
	// Optional. Default value "".
	ContentSecurityPolicy string `json:"content_security_policy,omitempty" yaml:"content_security_policy,omitempty"`

	// CSPReportOnly would use the `Content-Security-Policy-Report-Only` header instead
	// of the `Content-Security-Policy` header. This allows iterative updates of the
	// content security policy by only reporting the violations that would
	// have occurred instead of blocking the resource.
	// Optional. Default value false.
	CSPReportOnly bool `json:"csp_report_only,omitempty" yaml:"csp_report_only,omitempty"`

	// HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security`
	// header, which enables the domain to be included in the HSTS preload list
	// maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
	// Optional.  Default value false.
	HSTSPreloadEnabled bool `json:"hsts_preload_enabled,omitempty" yaml:"hsts_preload_enabled,omitempty"`

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

SecureConfig defines the config for Secure middleware.

type SessionConfig

type SessionConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper `json:"-" yaml:"-"`

	// SessionManager defines a session manager
	SessionManager *scs.SessionManager `json:"-" yaml:"-"`
}

type Skipper

type Skipper func(r *http.Request) bool

func ChainSkipper

func ChainSkipper(skippers ...Skipper) Skipper

func EqualPathSkipper

func EqualPathSkipper(paths ...string) Skipper

func PrefixPathSkipper

func PrefixPathSkipper(prefixes ...string) Skipper

func SuffixPathSkipper

func SuffixPathSkipper(suffixes ...string) Skipper

type ValueExtractorError

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

ValueExtractorError is error type when middleware extractor is unable to extract value from lookups

func (*ValueExtractorError) Error

func (e *ValueExtractorError) Error() string

Error returns errors text

type ValuesExtractor

type ValuesExtractor func(r *http.Request) ([]string, ExtractorSource, error)

ValuesExtractor defines a function for extracting values (keys/tokens) from the given context.

func CreateExtractors

func CreateExtractors(lookups string) ([]ValuesExtractor, error)

CreateExtractors creates ValuesExtractors from given lookups. Lookups is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used to extract key from the request. Possible values:

  • "header:<name>" or "header:<name>:<cut-prefix>" `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to cut is `<auth-scheme> ` note the space at the end. In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `.
  • "query:<name>"
  • "param:<name>"
  • "form:<name>"
  • "cookie:<name>"

Multiple sources example: - "header:Authorization,header:X-Api-Key"

type Visitor

type Visitor struct {
	*rate.Limiter
	// contains filtered or unexported fields
}

Visitor signifies a unique user's limiter details

Jump to

Keyboard shortcuts

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