middleware

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: Apache-2.0 Imports: 22 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

This section is empty.

Variables

This section is empty.

Functions

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 returns a middleware that verifies an HMAC-SHA256 request signature. It accepts both the legacy v1 canonical form and the authenticated v2 form (with per-request nonce + replay rejection). If Keys is empty or the required headers are absent, the middleware passes through without requiring HMAC (unchanged historical behavior — the API-Key layer enforces auth).

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 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 returns a middleware that implements: mTLS (client cert) > HMAC > API Key. If the request has a verified TLS client certificate, the inner handler is called directly. If HMAC headers are present and valid (v1 or v2), the inner handler is called (API Key skipped). Otherwise the request is passed to apiKeyMiddleware.

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

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

Jump to

Keyboard shortcuts

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