middleware

package
v0.0.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	ExtractorMethodQuery  = "query"
	ExtractorMethodParam  = "param"
	ExtractorMethodCookie = "cookie"
	ExtractorMethodForm   = "form"
	ExtractorMethodHeader = "header"
)
View Source
const (
	// ContextKeyHeaderAllow is set by Router for getting value for `Allow` header in later stages of handler call chain.
	// Allow header is mandatory for status 405 (method not found) and useful for OPTIONS method requests.
	// It is added to context only when Router does not find matching method handler for request.
	ContextKeyHeaderAllow = "gin_header_allow"
)

Variables

View Source
var (
	CSRFContextKey = "csrf"

	ErrCSRFInvalid = xerror.NewHTTPError(http.StatusForbidden, "invalid csrf token")
)
View Source
var ErrCookieExtractorValueMissing = errors.New("missing value in cookies")
View Source
var ErrFormExtractorValueMissing = errors.New("missing value in the form")
View Source
var ErrHeaderExtractorValueInvalid = errors.New("invalid value in request header")
View Source
var ErrHeaderExtractorValueMissing = errors.New("missing value in request header")
View Source
var ErrParamExtractorValueMissing = errors.New("missing value in path params")
View Source
var ErrQueryExtractorValueMissing = errors.New("missing value in the query string")

Functions

func BasicAuthNext

func BasicAuthNext(fn BasicAuthValidator) gin.HandlerFunc

BasicAuthNext returns an BasicAuth middleware.

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

func BasicAuthNextWithConfig

func BasicAuthNextWithConfig(config BasicAuthConfig) gin.HandlerFunc

func CORSForceNext

func CORSForceNext(inputExposeHeaders ...string) gin.HandlerFunc

CORSForceNext 暴力跨域设置

func CORSNext

func CORSNext() gin.HandlerFunc

func CORSNextWithConfig

func CORSNextWithConfig(config CORSConfig) gin.HandlerFunc

func CSRFFormHTML

func CSRFFormHTML(c *gin.Context, inputTypes ...string) template.HTML

CSRFFormHTML html builder

func CSRFNext

func CSRFNext() gin.HandlerFunc

CSRFNext returns a Cross-Site Request Forgery (CSRF) middleware. See: https://en.wikipedia.org/wiki/Cross-site_request_forgery

func CSRFNextWithConfig

func CSRFNextWithConfig(config CSRFConfig) gin.HandlerFunc

CSRFNextWithConfig returns a CSRF middleware with config. See `CSRF()`.

func DefaultErrorHandler

func DefaultErrorHandler(c *gin.Context, err error, statusCodes ...int)

DefaultErrorHandler 默认错误返回响应

func DefaultSkipper

func DefaultSkipper(ctx *gin.Context) bool

DefaultSkipper returns false which processes the middleware.

func ErrorsNext

func ErrorsNext(errorHandlers ...ErrorHandler) gin.HandlerFunc

ErrorsNext igin.AddStatusError(context, igin.NewHTTPError(201, "test error")) 预期:status:201;error:code=201, message=test error"

igin.AddStatusError(context, fmt.Errorf("test error")) 预期:status:500;error:test error

igin.AddStatusError(context, fmt.Errorf("test error"), 201) 预期:status:201;error:test error

func GzipNext

func GzipNext() gin.HandlerFunc

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

func GzipNextWithConfig

func GzipNextWithConfig(config GzipConfig) gin.HandlerFunc

func KeyAuthNext

func KeyAuthNext(fn KeyAuthValidator) gin.HandlerFunc

KeyAuthNext returns an KeyAuth middleware.

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

func KeyAuthNextWithConfig

func KeyAuthNextWithConfig(config KeyAuthConfig) gin.HandlerFunc

func MatchScheme

func MatchScheme(domain, pattern string) bool

func MatchSubdomain

func MatchSubdomain(domain, pattern string) bool

MatchSubdomain compares authority with wildcard

func RequestIdNext

func RequestIdNext() gin.HandlerFunc

RequestIdNext returns a X-Request-ID middleware.

func RequestIdNextWithConfig

func RequestIdNextWithConfig(config RequestIDConfig) gin.HandlerFunc

func SecureNext

func SecureNext() gin.HandlerFunc

func SecureNextWithConfig

func SecureNextWithConfig(config SecureConfig) gin.HandlerFunc

Types

type BasicAuthConfig

type BasicAuthConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// Validator is a function to validate BasicAuth credentials.
	// Required.
	Validator BasicAuthValidator
	// Realm is a string to define realm attribute of BasicAuth.
	// Default value "Restricted".
	Realm string
}

BasicAuthConfig defines the config for BasicAuth middleware.

type BasicAuthValidator

type BasicAuthValidator func(s1, s2 string, c *gin.Context) bool

BasicAuthValidator defines a function to validate BasicAuth credentials.

type CORSConfig

type CORSConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// 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

	// 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)

	// 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.
	// If `allowMethods` is left empty, this middleware will fill for preflight
	// request `Access-Control-Allow-Methods` header value
	// from `Allow` header that Router set into context.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
	AllowMethods []string

	// 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

	// 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

	// 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)
	//
	// Optional. Default value is false.
	UnsafeWildcardOriginWithAllowCredentials bool

	// 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

	// 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

	ErrorHandler ErrorHandler
}

type CSRFConfig

type CSRFConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// TokenLength is the length of the generated token.
	TokenLength int
	// Optional. Default value 32.
	// 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
	// Context key to store generated CSRF token into context.
	// Optional. Default value "csrf".
	ContextKey string
	// Name of the CSRF cookie. This cookie will store CSRF token.
	// Optional. Default value "csrf".
	CookieName string
	// Domain of the CSRF cookie.
	// Optional. Default value none.
	CookieDomain string
	// Path of the CSRF cookie.
	// Optional. Default value none.
	CookiePath string
	// Max age (in seconds) of the CSRF cookie.
	// Optional. Default value 86400 (24hr).
	CookieMaxAge int
	// Indicates if CSRF cookie is secure.
	// Optional. Default value false.
	CookieSecure bool
	// Indicates if CSRF cookie is HTTP only.
	// Optional. Default value false.
	CookieHTTPOnly bool
	// Indicates SameSite mode of the CSRF cookie.
	// Optional. Default value SameSiteDefaultMode.
	CookieSameSite http.SameSite
	// ErrorHandler defines a function which is executed for returning custom errors.
	ErrorHandler ErrorHandler
}

CSRFConfig defines the config for CSRF middleware.

type ErrKeyAuthMissing

type ErrKeyAuthMissing struct {
	Err error
}

ErrKeyAuthMissing is error type when KeyAuth middleware is unable to extract value from lookups

func (*ErrKeyAuthMissing) Error

func (e *ErrKeyAuthMissing) Error() string

Error returns errors text

func (*ErrKeyAuthMissing) Unwrap

func (e *ErrKeyAuthMissing) Unwrap() error

Unwrap unwraps error

type ErrorHandler

type ErrorHandler func(c *gin.Context, err error, statusCodes ...int)

ErrorHandler middleware handler error

type GzipConfig

type GzipConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// Gzip compression level.
	// Optional. Default value -1.
	Level int
}

GzipConfig defines the config for Gzip middleware.

type KeyAuthConfig

type KeyAuthConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// 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

	// AuthScheme to be used in the Authorization header.
	// Optional. Default value "Bearer".
	AuthScheme string

	// Validator is a function to validate key.
	// Required.
	Validator KeyAuthValidator

	// ErrorHandler defines a function which is executed for an invalid key.
	// It may be used to define a custom error.
	ErrorHandler ErrorHandler

	// 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
}

KeyAuthConfig defines the config for KeyAuth middleware.

type KeyAuthValidator

type KeyAuthValidator func(auth string, c *gin.Context) (bool, error)

KeyAuthValidator defines a function to validate KeyAuth credentials.

type RequestIDConfig

type RequestIDConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// Generator defines a function to generate an ID.
	// Optional. Default value random.String(32).
	Generator func() string
	// RequestIDHandler defines a function which is executed for a request id.
	RequestIDHandler func(*gin.Context, string)
	// TargetHeader defines what header to look for to populate the id
	TargetHeader string
}

type SecureConfig

type SecureConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper
	// XSSProtection provides protection against cross-site scripting attack (XSS)
	// by setting the `X-XSS-Protection` header.
	// Optional. Default value "1; mode=block".
	XSSProtection string

	// ContentTypeNosniff provides protection against overriding Content-Type
	// header by setting the `X-Content-Type-Options` header.
	// Optional. Default value "nosniff".
	ContentTypeNosniff string

	// 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

	// 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

	// 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

	// 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

	// 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

	// 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

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

type Skipper

type Skipper func(c *gin.Context) bool

Skipper defines a function to skip middleware. Returning true skips processing the middleware.

type SuccessHandler

type SuccessHandler func(c *gin.Context)

SuccessHandler defines a function to Handler middleware

type ValuesExtractor

type ValuesExtractor func(c *gin.Context) ([]string, error)

func CreateExtractors

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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