middleware

package
v0.17.3 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2024 License: AGPL-3.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddRequestID added in v0.7.1

func AddRequestID(header string) gin.HandlerFunc

AddRequestID returns a gin middleware which adds a unique ID to each request (both response header and context).

func BuildContentSecurityPolicy added in v0.11.0

func BuildContentSecurityPolicy(extraURIs ...string) string

func CORS

func CORS() gin.HandlerFunc

CORS returns a new gin middleware which allows CORS requests to be processed. This is necessary in order for web/browser-based clients like Semaphore to work.

func CacheControl

func CacheControl(config CacheControlConfig) gin.HandlerFunc

CacheControl returns a new gin middleware which allows routes to control cache settings on response headers.

func ContentSecurityPolicy added in v0.11.1

func ContentSecurityPolicy(extraURIs ...string) gin.HandlerFunc

func ExtraHeaders

func ExtraHeaders() gin.HandlerFunc

ExtraHeaders returns a new gin middleware which adds various extra headers to the response.

func Gzip

func Gzip() gin.HandlerFunc

Gzip returns a gzip gin middleware using default compression.

func HeaderFilter added in v0.14.0

func HeaderFilter(state *state.State) gin.HandlerFunc

HeaderFilter returns a gin middleware handler that provides HTTP request blocking (filtering) based on database allow / block filters.

func Logger

func Logger(logClientIP bool) gin.HandlerFunc

Logger returns a gin middleware which provides request logging and panic recovery.

func NewRequestID added in v0.11.1

func NewRequestID() string

NewRequestID generates a new request ID string.

func RateLimit

func RateLimit(limit int, exceptions []string) gin.HandlerFunc

RateLimit returns a gin middleware that will automatically rate limit caller (by IP address), and enrich the response header with the following headers:

  • `X-Ratelimit-Limit` - max requests allowed per time period (fixed).
  • `X-Ratelimit-Remaining` - requests remaining for this IP before reset.
  • `X-Ratelimit-Reset` - ISO8601 timestamp when the rate limit will reset.

If `X-Ratelimit-Limit` is exceeded, the request is aborted and an HTTP 429 TooManyRequests status is returned.

If the config AdvancedRateLimitRequests value is <= 0, then a noop handler will be returned, which performs no rate limiting.

func Session

func Session(sessionName string, auth []byte, crypt []byte) gin.HandlerFunc

Session returns a new gin middleware that implements session cookies using the given sessionName, authentication key, and encryption key. Session name can be derived from the SessionName utility function in this package.

func SessionName

func SessionName() (string, error)

SessionName is a utility function that derives an appropriate session name from the hostname.

func SessionOptions

func SessionOptions() sessions.Options

SessionOptions returns the standard set of options to use for each session.

func SignatureCheck

func SignatureCheck(uriBlocked func(context.Context, *url.URL) (bool, error)) func(*gin.Context)

SignatureCheck returns a gin middleware for checking http signatures.

The middleware first checks whether an incoming http request has been http-signed with a well-formed signature. If so, it will check if the domain that signed the request is permitted to access the server, using the provided uriBlocked function. If the domain is blocked, the middleware will abort the request chain with http code 403 forbidden. If it is not blocked, the handler will set the key verifier and the signature in the context for use down the line.

In case of an error, the request will be aborted with http code 500.

func Throttle

func Throttle(cpuMultiplier int, retryAfter time.Duration) gin.HandlerFunc

Throttle returns a gin middleware that performs throttling of incoming requests, ensuring that only a certain number of requests are handled concurrently, to reduce congestion of the server.

Limits are configured using available CPUs and the given cpuMultiplier value. Open request limit is available CPUs * multiplier; backlog limit is limit * multiplier.

Example values for multiplier 8:

1 cpu = 08 open, 064 backlog
2 cpu = 16 open, 128 backlog
4 cpu = 32 open, 256 backlog

Example values for multiplier 4:

1 cpu = 04 open, 016 backlog
2 cpu = 08 open, 032 backlog
4 cpu = 16 open, 064 backlog

Callers will first attempt to get a backlog token. Once they have that, they will wait in the backlog queue until they can get a token to allow their request to be processed.

If the backlog queue is full, the request context is closed, or the caller has been waiting in the backlog for too long, this function will abort the request chain, write a JSON error into the response, set an appropriate Retry-After value, and set the HTTP response code to 503: Service Unavailable.

If the multiplier is <= 0, a noop middleware will be returned instead.

RetryAfter determines the Retry-After header value to be sent to throttled requests.

Useful links:

func TokenCheck

func TokenCheck(dbConn db.DB, validateBearerToken func(r *http.Request) (oauth2.TokenInfo, error)) func(*gin.Context)

TokenCheck returns a new gin middleware for validating oauth tokens in requests.

The middleware checks the request Authorization header for a valid oauth Bearer token.

If no token was set in the Authorization header, or the token was invalid, the handler will return.

If a valid oauth Bearer token was provided, it will be set on the gin context for further use.

Then, it will check which *gtsmodel.User the token belongs to. If the user is not confirmed, not approved, or has been disabled, then the middleware will return early. Otherwise, the User will be set on the gin context for further processing by other functions.

Next, it will look up the *gtsmodel.Account for the User. If the Account has been suspended, then the middleware will return early. Otherwise, it will set the Account on the gin context too.

Finally, it will check the client ID of the token to see if a *gtsmodel.Application can be retrieved for that client ID. This will also be set on the gin context.

If an invalid token is presented, or a user/account/application can't be found, then this middleware won't abort the request, since the server might want to still allow public requests that don't have a Bearer token set (eg., for public instance information and so on).

func UserAgent

func UserAgent() gin.HandlerFunc

UserAgent returns a gin middleware which aborts requests with empty user agent strings, returning code 418 - I'm a teapot.

Types

type CacheControlConfig added in v0.10.0

type CacheControlConfig struct {
	// Slice of Cache-Control directives, which will be
	// joined comma-separated and served as the value of
	// the Cache-Control header.
	//
	// If no directives are set, the Cache-Control header
	// will not be sent in the response at all.
	//
	// For possible Cache-Control directive values, see:
	// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
	Directives []string

	// Slice of Vary header values, which will be joined
	// comma-separated and served as the value of the Vary
	// header in the response.
	//
	// If no Vary header values are supplied, then the
	// Vary header will be omitted in the response.
	//
	// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
	Vary []string
}

Jump to

Keyboard shortcuts

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