middleware

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware functionality. Includes rate limiting, compression, request body limiting, metrics collection and other middleware.

Package middleware provides HMAC signature verification for service-to-service auth.

Package middleware provides HTTP middleware functionality. Includes internationalization language detection middleware.

Package middleware provides HTTP middleware functionality. Includes rate limiting, compression, request body limiting, metrics collection and other middleware.

Package middleware provides HTTP middleware functionality. Includes rate limiting, compression, request body limiting, metrics collection and other middleware.

Index

Constants

View Source
const (
	RateLimitScopeIP         = "ip"
	RateLimitScopeCredential = "credential"
)

Rate-limit scopes. They are the only values passed to RateLimitConfig.OnLimited, so they are safe to use as a metric label.

Variables

This section is empty.

Functions

func AuditLogLevel added in v1.8.0

func AuditLogLevel(log *loggerkit.Logger, next http.Handler) http.Handler

AuditLogLevel records every request that tries to change the log level in the audit trail: who asked (the authenticated principal and client address), the level before and after, and whether the change was accepted. Reads (GET) are not recorded. It must run inside the authentication middleware so the principal is known.

func ClientIP added in v1.8.0

func ClientIP(r *http.Request) string

ClientIP returns the client address the rate limiter resolved for r: the forwarded address when the TCP peer is a trusted proxy, the peer otherwise. A request that did not pass through the limiter yields the TCP peer address without its port, so forwarded headers are never trusted implicitly.

func ErrorHandlerMiddleware

func ErrorHandlerMiddleware(environment string) func(http.Handler) http.Handler

ErrorHandlerMiddleware creates error handling middleware

This middleware hides detailed error information in production environment, only returning generic error messages. Detailed error information is only recorded in logs, not returned to clients.

Parameters:

  • environment: deployment environment ("production" or "prod" indicates production)

Returns:

  • func(http.Handler) http.Handler: HTTP middleware function

func GetLanguage added in v0.2.0

func GetLanguage(r *http.Request) i18n.Language

GetLanguage gets language from request (helper function).

func HMACAuth added in v0.11.0

func HMACAuth(cfg HMACConfig) func(http.Handler) http.Handler

HMACAuth verifies complete signature, timestamp and key-ID headers. Missing any required header passes to the next handler, which must enforce any other authentication policy. A complete but invalid signature returns 401, including an unknown or unconfigured key. V2 binds a nonce and rejects replays; v3 also binds the name of the receiving instance; legacy v1 is accepted only when AllowV1 is enabled. Server routes use ServiceAuthChain for their combined credential and service-policy selection.

func I18nMiddleware added in v0.2.0

func I18nMiddleware() func(http.Handler) http.Handler

I18nMiddleware creates internationalization language detection middleware.

This middleware detects user language from HTTP requests with the following priority: 1. Query parameter ?lang=xx 2. Cookie 3. Accept-Language request header 4. Default language (English)

Detected language will be stored in request context for subsequent processing.

Returns:

  • func(http.Handler) http.Handler: HTTP middleware function

func IPWhitelistMiddleware

func IPWhitelistMiddleware(whitelist string) func(http.Handler) http.Handler

IPWhitelistMiddleware creates IP whitelist middleware.

This middleware only allows IP addresses in the whitelist to access protected endpoints. Whitelist is taken from the whitelist argument, or from environment variable IP_WHITELIST when whitelist is empty. Supports comma-separated multiple IPs or CIDR networks. Uses middleware-kit IPAllowlistMiddleware under the hood. Client IP is resolved via TrustedProxyConfig from TRUSTED_PROXY_IPS so behaviour matches other middleware-kit usage.

Parameters:

  • whitelist: IP whitelist (comma-separated IP addresses or CIDR networks). Empty means use IP_WHITELIST env.

Returns:

  • func(http.Handler) http.Handler: HTTP middleware function

func MetricsMiddleware

func MetricsMiddleware(next http.Handler) http.Handler

MetricsMiddleware creates Prometheus metrics collection middleware

func NewMemoryReplayGuard added in v0.14.0

func NewMemoryReplayGuard(maxSize int) *memoryReplayGuard

NewMemoryReplayGuard returns a single-node in-memory ReplayGuard. maxSize caps the number of tracked keys to bound memory under abuse; when exceeded the guard fails safe by treating new keys as replays (rejecting) until the sweep drains expired entries. A non-positive maxSize disables the cap.

func NewTrustedProxyConfig added in v1.8.0

func NewTrustedProxyConfig(raw string) *middlewarekit.TrustedProxyConfig

NewTrustedProxyConfig builds the client-address policy from a TRUSTED_PROXY_IPS value. An empty value keeps the middleware-kit default of trusting forwarded headers from private and loopback peers; "none" trusts no peer.

func PrincipalFromContext added in v1.8.0

func PrincipalFromContext(ctx context.Context) string

PrincipalFromContext returns the identifier set by WithPrincipal, or "" when the request did not authenticate with an identifiable credential.

func RateLimitAuthenticated added in v1.8.0

func RateLimitAuthenticated(cfg RateLimitConfig, auth func(http.Handler) http.Handler) func(http.Handler) http.Handler

RateLimitAuthenticated wraps an authentication middleware so that failed and successful requests are counted separately.

A request first takes one unit of its client address's budget; an address with no budget left is refused with 429 before auth runs. When auth passes the request on with a principal (see WithPrincipal), the unit is returned and the request is counted against that principal instead (per client address for the shared API key). When auth rejects the request, or passes it on without a principal, the unit stays spent.

Taking the unit before auth, not after a failure, keeps the bound strict under concurrency: at most the per-address rate of credential checks can fail or be in flight per window, however many connections an address opens.

func RateLimitByIP added in v1.8.0

func RateLimitByIP(cfg RateLimitConfig) func(http.Handler) http.Handler

RateLimitByIP limits every request per client address. It is for routes that do not authenticate.

func SafeError

func SafeError(w http.ResponseWriter, r *http.Request, statusCode int, err error, detailMessage string)

SafeError safely returns error response (decides whether to hide detailed information based on environment)

func ServiceAuthChain added in v0.11.0

func ServiceAuthChain(hmacCfg HMACConfig, apiKeyMiddleware func(http.Handler) http.Handler) func(http.Handler) http.Handler

ServiceAuthChain selects authentication per request. Without ServicePolicies, a TLS peer certificate accepted by the configured server TLS policy bypasses header authentication. Otherwise complete HMAC headers with configured keys are verified; invalid signatures return 401 without API-key fallback. Requests outside that complete HMAC branch reach apiKeyMiddleware. Legacy v1 requires AllowV1. With ServicePolicies enabled, only authenticated HMAC v2 key IDs and their allowed actions are accepted; API keys and mTLS do not bypass policy.

An accepted request reaches next carrying its principal (PrincipalFromContext): the HMAC key ID, the client certificate fingerprint, or a constant for the API key.

func WithClientIP added in v1.8.0

func WithClientIP(r *http.Request, clientIP string) *http.Request

WithClientIP returns a copy of r that carries the client address resolved through the trusted-proxy configuration.

func WithPrincipal added in v1.8.0

func WithPrincipal(r *http.Request, principal string) *http.Request

WithPrincipal returns a copy of r that carries the identifier of the authenticated principal. The identifier must not be a secret: it is used as a rate-limit key and written to the log when that limit is reached.

Types

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
	Code    string `json:"code,omitempty"`
}

ErrorResponse error response structure

type HMACConfig added in v0.11.0

type HMACConfig struct {
	// ServicePolicies optionally requires HMAC v2 and authorizes each operation.
	ServicePolicies map[string]serviceauth.Policy
	// Keys maps key_id -> secret for verification.
	Keys map[string]string
	// TimestampToleranceSec is the allowed clock skew in seconds (default 60). It is
	// clamped to MaxTimestampToleranceSec.
	TimestampToleranceSec int
	// MaxTimestampToleranceSec is the hard upper bound on the tolerance (default 300).
	MaxTimestampToleranceSec int
	// AllowV1 keeps the legacy v1 canonical form acceptable during migration. Nil
	// defaults to false; callers must explicitly opt in to the deprecated protocol.
	AllowV1 *bool
	// Audiences are the names of this instance that a v3 signature may be
	// bound to. A v3 request is accepted when its signature verifies with one
	// of them. Empty means v3 requests are rejected.
	Audiences []string
	// RequireAudience rejects the v1 and v2 forms, which are not bound to an
	// instance: a request signed for another instance that shares the key is
	// then refused even inside the timestamp window.
	RequireAudience bool
	// ReplayGuard rejects reused v2 nonces within the timestamp window. When nil a
	// process-local in-memory guard is used. See ReplayGuard docs for the multi-replica
	// limitation.
	ReplayGuard ReplayGuard
	// OnReplayRejected, when set, is called each time a v2 request is rejected as a replay.
	OnReplayRejected ReplayObserver
	// OnV1Used, when set, is called when a request is accepted via the legacy v1 form
	// (used to emit a deprecation metric).
	OnV1Used ReplayObserver
}

HMACConfig holds HMAC verification settings.

type RateLimitConfig added in v1.8.0

type RateLimitConfig struct {
	Limits             *RateLimits
	TrustedProxyConfig *middlewarekit.TrustedProxyConfig
	// OnLimited, when set, is called with the scope of each refused request.
	OnLimited func(scope string)
}

RateLimitConfig configures the rate-limit middleware.

type RateLimiter

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

RateLimiter is an in-memory sliding-window limiter: no interval of one window contains more than rate accepted requests per key. It differs from the middleware-kit limiter in two ways the routes need: a reservation can be returned (Release), and a refusal reports when the next request will fit.

Memory is bounded: at most maxKeys keys are tracked, each holding at most rate timestamps. When the table is full the least recently seen keys are evicted.

func NewRateLimiter

func NewRateLimiter(rate int, window time.Duration, maxKeys int) *RateLimiter

NewRateLimiter creates a limiter that accepts rate requests per window for each key and tracks at most maxKeys keys. Non-positive arguments fall back to the defaults. Stop must be called to end its cleanup goroutine.

func (*RateLimiter) Allow

func (l *RateLimiter) Allow(key string) (allowed bool, retryAfter time.Duration)

Allow records a request for key when the window has room for it. Otherwise it records nothing and returns the time until the oldest recorded request leaves the window.

func (*RateLimiter) Release added in v1.8.0

func (l *RateLimiter) Release(key string, reservation Reservation)

Release returns the request recorded by the given reservation, so a request that was admitted provisionally does not count against the key. It removes that request's own record: requests complete in a different order than they were admitted, and removing the newest record instead could erase a later request that must stay counted. A reservation that has already left the window is ignored. Call Release at most once per reservation: two requests admitted at the same instant have equal records.

func (*RateLimiter) Reserve added in v1.8.0

func (l *RateLimiter) Reserve(key string) (reservation Reservation, allowed bool, retryAfter time.Duration)

Reserve is Allow that also returns a handle for Release.

func (*RateLimiter) Stop

func (l *RateLimiter) Stop()

Stop ends the cleanup goroutine. It is safe to call more than once.

type RateLimits added in v1.8.0

type RateLimits struct {
	IP         *RateLimiter
	Credential *RateLimiter
}

RateLimits holds the two limiters the routes use. IP is keyed by client address and counts requests that did not authenticate; Credential is keyed by the authenticated principal.

func NewRateLimits added in v1.8.0

func NewRateLimits(ipRate, credentialRate int, window time.Duration) *RateLimits

NewRateLimits creates both limiters with a shared window.

func (*RateLimits) Stop added in v1.8.0

func (s *RateLimits) Stop()

Stop stops both limiters. It is safe on a nil receiver.

type ReplayGuard added in v0.14.0

type ReplayGuard interface {
	// SeenBefore atomically records the key and reports whether it had already been
	// recorded within its TTL window. It returns true when the key is a replay and
	// returns an error when the backing store cannot determine replay state.
	// The ttl bounds how long the key must be remembered; callers pass the signature
	// timestamp tolerance so memory is bounded by the accepted skew window.
	SeenBefore(key string, ttl time.Duration) (bool, error)
}

ReplayGuard records recently-seen request nonces so a captured, still-in-window HMAC v2 request cannot be replayed. Implementations must be safe for concurrent use.

IMPORTANT (multi-replica limitation): the bundled in-memory implementation only protects a single process. When Warden runs as multiple replicas behind a load balancer, a replayed request routed to a *different* replica will NOT be caught unless a shared store is plugged in. Use NewRedisReplayGuard when multiple Warden replicas share Redis. The signature timestamp tolerance still bounds the replay window when the in-memory implementation is used.

func NewRedisReplayGuard added in v1.0.0

func NewRedisReplayGuard(client *redis.Client) ReplayGuard

NewRedisReplayGuard creates a distributed replay guard backed by Redis. A nil client returns a guard that rejects requests until a backend is available.

type ReplayObserver added in v0.14.0

type ReplayObserver func()

ReplayObserver is called when a v2 request is rejected as a replay. It lets the caller record a metric without this package importing prommetrics (avoids an import cycle and keeps the middleware dependency-light).

type Reservation added in v1.8.0

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

Reservation identifies one request recorded by Reserve, so that Release can return that request and no other.

Jump to

Keyboard shortcuts

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