Documentation
¶
Overview ¶
Package middleware provides HTTP middleware functionality for Go services. Includes authentication (API Key, HMAC, mTLS), rate limiting, compression, request body limiting, security headers, and logging middleware.
Index ¶
- Variables
- func APIKeyAuth(cfg APIKeyConfig) fiber.Handler
- func APIKeyAuthStd(cfg APIKeyConfig) func(http.Handler) http.Handler
- func BodyLimit(cfg BodyLimitConfig) fiber.Handler
- func BodyLimitStd(cfg BodyLimitConfig) func(http.Handler) http.Handler
- func CombinedAuth(cfg AuthConfig) fiber.Handler
- func CompressStd(cfg CompressConfig) func(http.Handler) http.Handler
- func ComputeHMAC(timestamp, service, body, secret string) string
- func GetClientIP(r *http.Request, trustedConfig *TrustedProxyConfig) string
- func GetClientIPFiber(c *fiber.Ctx, trustedConfig *TrustedProxyConfig) string
- func HMACAuth(cfg HMACConfig) fiber.Handler
- func HMACAuthStd(cfg HMACConfig) func(http.Handler) http.Handler
- func IsPrivateIP(ip net.IP) bool
- func MTLSAuth(cfg MTLSConfig) fiber.Handler
- func MTLSAuthStd(cfg MTLSConfig) func(http.Handler) http.Handler
- func MaskEmail(email string) string
- func MaskPhone(phone string) string
- func NoCacheHeaders() fiber.Handler
- func NoCacheHeadersStd() func(http.Handler) http.Handler
- func RateLimit(cfg RateLimitConfig) fiber.Handler
- func RateLimitStd(cfg RateLimitConfig) func(http.Handler) http.Handler
- func RequestLogging(cfg LoggingConfig) fiber.Handler
- func RequestLoggingStd(cfg LoggingConfig) func(http.Handler) http.Handler
- func SecurityHeaders(cfg SecurityHeadersConfig) fiber.Handler
- func SecurityHeadersStd(cfg SecurityHeadersConfig) func(http.Handler) http.Handler
- type APIKeyConfig
- type AuthConfig
- type BodyLimitConfig
- type CompressConfig
- type HMACConfig
- type LoggingConfig
- type MTLSConfig
- type RateLimitConfig
- type RateLimiter
- type RateLimiterConfig
- type SecurityHeadersConfig
- type TrustedProxyConfig
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAPIKeyNotConfigured indicates no API key was configured on the server. ErrAPIKeyNotConfigured = errors.New("API key not configured") // ErrAPIKeyMissing indicates no API key was provided in the request. ErrAPIKeyMissing = errors.New("API key missing") // ErrAPIKeyInvalid indicates the provided API key is invalid. ErrAPIKeyInvalid = errors.New("API key invalid") // ErrHMACSecretNotConfigured indicates no HMAC secret was configured. ErrHMACSecretNotConfigured = errors.New("HMAC secret not configured") // ErrHMACSignatureMissing indicates no HMAC signature was provided. ErrHMACSignatureMissing = errors.New("HMAC signature missing") // ErrHMACSignatureInvalid indicates the HMAC signature is invalid. ErrHMACSignatureInvalid = errors.New("HMAC signature invalid") // ErrHMACTimestampMissing indicates no timestamp was provided for HMAC. ErrHMACTimestampMissing = errors.New("HMAC timestamp missing") // ErrHMACTimestampInvalid indicates the timestamp format is invalid. ErrHMACTimestampInvalid = errors.New("HMAC timestamp invalid") // ErrHMACTimestampExpired indicates the timestamp has expired. ErrHMACTimestampExpired = errors.New("HMAC timestamp expired") // ErrHMACKeyIDInvalid indicates the key ID is invalid or not found. ErrHMACKeyIDInvalid = errors.New("HMAC key ID invalid") // ErrMTLSCertificateMissing indicates no client certificate was provided. ErrMTLSCertificateMissing = errors.New("mTLS client certificate missing") // ErrMTLSCertificateInvalid indicates the client certificate is invalid. ErrMTLSCertificateInvalid = errors.New("mTLS client certificate invalid") ErrUnauthorized = errors.New("unauthorized") )
Authentication errors
var ( // ErrRateLimitExceeded indicates the rate limit has been exceeded. ErrRateLimitExceeded = errors.New("rate limit exceeded") )
Rate limiting errors
var ( // ErrRequestBodyTooLarge indicates the request body exceeds the size limit. ErrRequestBodyTooLarge = errors.New("request body too large") )
Request errors
Functions ¶
func APIKeyAuth ¶
func APIKeyAuth(cfg APIKeyConfig) fiber.Handler
APIKeyAuth creates a Fiber middleware for API key authentication.
func APIKeyAuthStd ¶
func APIKeyAuthStd(cfg APIKeyConfig) func(http.Handler) http.Handler
APIKeyAuthStd creates a standard net/http middleware for API key authentication.
func BodyLimit ¶
func BodyLimit(cfg BodyLimitConfig) fiber.Handler
BodyLimit creates a Fiber middleware that limits request body size.
func BodyLimitStd ¶
func BodyLimitStd(cfg BodyLimitConfig) func(http.Handler) http.Handler
BodyLimitStd creates a standard net/http middleware that limits request body size.
func CombinedAuth ¶
func CombinedAuth(cfg AuthConfig) fiber.Handler
CombinedAuth creates a Fiber middleware that tries multiple authentication methods. Authentication methods are tried in order: mTLS > HMAC > API Key. The first successful authentication allows the request through.
func CompressStd ¶
func CompressStd(cfg CompressConfig) func(http.Handler) http.Handler
CompressStd creates a standard net/http middleware for gzip compression.
func ComputeHMAC ¶
ComputeHMAC computes an HMAC-SHA256 signature. The message format is: timestamp:service:body
func GetClientIP ¶
func GetClientIP(r *http.Request, trustedConfig *TrustedProxyConfig) string
GetClientIP extracts the real client IP address from an HTTP request. It checks X-Real-IP and X-Forwarded-For headers if the request is from a trusted proxy.
func GetClientIPFiber ¶
func GetClientIPFiber(c *fiber.Ctx, trustedConfig *TrustedProxyConfig) string
GetClientIPFiber extracts the real client IP address from a Fiber context.
func HMACAuth ¶
func HMACAuth(cfg HMACConfig) fiber.Handler
HMACAuth creates a Fiber middleware for HMAC signature authentication.
func HMACAuthStd ¶
func HMACAuthStd(cfg HMACConfig) func(http.Handler) http.Handler
HMACAuthStd creates a standard net/http middleware for HMAC signature authentication.
func IsPrivateIP ¶
IsPrivateIP checks if an IP address is a private IP address.
func MTLSAuth ¶
func MTLSAuth(cfg MTLSConfig) fiber.Handler
MTLSAuth creates a Fiber middleware for mTLS client certificate authentication. Note: This middleware requires TLS to be properly configured with ClientAuth.
func MTLSAuthStd ¶
func MTLSAuthStd(cfg MTLSConfig) func(http.Handler) http.Handler
MTLSAuthStd creates a standard net/http middleware for mTLS authentication.
func MaskEmail ¶
MaskEmail masks an email address for logging. Example: john.doe@example.com -> jo***@example.com
func NoCacheHeaders ¶
NoCacheHeaders creates a middleware that sets cache-control headers to prevent caching.
func NoCacheHeadersStd ¶
NoCacheHeadersStd creates a standard net/http middleware that prevents caching.
func RateLimit ¶
func RateLimit(cfg RateLimitConfig) fiber.Handler
RateLimit creates a Fiber middleware for rate limiting.
func RateLimitStd ¶
func RateLimitStd(cfg RateLimitConfig) func(http.Handler) http.Handler
RateLimitStd creates a standard net/http middleware for rate limiting.
func RequestLogging ¶
func RequestLogging(cfg LoggingConfig) fiber.Handler
RequestLogging creates a Fiber middleware for request logging.
func RequestLoggingStd ¶
func RequestLoggingStd(cfg LoggingConfig) func(http.Handler) http.Handler
RequestLoggingStd creates a standard net/http middleware for request logging.
func SecurityHeaders ¶
func SecurityHeaders(cfg SecurityHeadersConfig) fiber.Handler
SecurityHeaders creates a Fiber middleware that adds security headers.
func SecurityHeadersStd ¶
func SecurityHeadersStd(cfg SecurityHeadersConfig) func(http.Handler) http.Handler
SecurityHeadersStd creates a standard net/http middleware that adds security headers.
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
// APIKey is the expected API key value.
// If empty, authentication will fail for all requests (secure by default).
APIKey string
// HeaderName is the header name to look for the API key.
// Default: "X-API-Key"
HeaderName string
// QueryParamName is the query parameter name to look for the API key.
// If set, the middleware will also check query parameters.
// Default: "" (disabled)
QueryParamName string
// AuthScheme is the Authorization header scheme (e.g., "Bearer", "ApiKey").
// If set, the middleware will also check Authorization header.
// Default: "" (disabled)
AuthScheme string
// AllowEmptyKey allows requests when no API key is configured.
// This is useful for development mode but NOT recommended for production.
// Default: false
AllowEmptyKey bool
// ErrorHandler is called when authentication fails.
// If nil, returns 401 Unauthorized with a generic message.
ErrorHandler func(c *fiber.Ctx, err error) error
// SuccessHandler is called when authentication succeeds.
// Useful for setting context values or logging.
SuccessHandler func(c *fiber.Ctx)
// Logger for logging authentication events.
// If nil, no logging is performed.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
APIKeyConfig configures the API Key authentication middleware.
func DefaultAPIKeyConfig ¶
func DefaultAPIKeyConfig() APIKeyConfig
DefaultAPIKeyConfig returns the default API key configuration.
type AuthConfig ¶
type AuthConfig struct {
// MTLSConfig for mTLS authentication (highest priority)
MTLSConfig *MTLSConfig
// HMACConfig for HMAC signature authentication
HMACConfig *HMACConfig
// APIKeyConfig for API key authentication (lowest priority)
APIKeyConfig *APIKeyConfig
// AllowNoAuth allows requests when no authentication method is configured.
// This is useful for development mode but NOT recommended for production.
// Default: false
AllowNoAuth bool
// ErrorHandler is called when all authentication methods fail.
ErrorHandler func(c *fiber.Ctx, err error) error
// Logger for logging authentication events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection.
TrustedProxyConfig *TrustedProxyConfig
}
AuthConfig configures the combined authentication middleware. It supports multiple authentication methods with priority: mTLS > HMAC > API Key
type BodyLimitConfig ¶
type BodyLimitConfig struct {
// MaxSize is the maximum allowed request body size in bytes.
// Default: 4MB (4 * 1024 * 1024)
MaxSize int64
// SkipMethods is a list of HTTP methods to skip body limit check.
// Default: ["GET", "HEAD", "OPTIONS"]
SkipMethods []string
// SkipPaths is a list of paths to skip body limit check.
SkipPaths []string
// ErrorHandler is called when the body size exceeds the limit.
ErrorHandler func(c *fiber.Ctx) error
// Logger for logging body limit events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
BodyLimitConfig configures the body limit middleware.
func DefaultBodyLimitConfig ¶
func DefaultBodyLimitConfig() BodyLimitConfig
DefaultBodyLimitConfig returns the default body limit configuration.
type CompressConfig ¶
type CompressConfig struct {
// Level is the gzip compression level.
// Valid values: gzip.NoCompression (0) to gzip.BestCompression (9)
// Default: gzip.DefaultCompression (-1)
Level int
// MinSize is the minimum response size to trigger compression.
// Responses smaller than this are not compressed.
// Default: 1024 (1KB)
MinSize int
// SkipPaths is a list of paths to skip compression.
SkipPaths []string
// ContentTypes is a list of content types to compress.
// If empty, all text-based content types are compressed.
// Example: ["application/json", "text/html", "text/plain"]
ContentTypes []string
}
CompressConfig configures the compression middleware.
func DefaultCompressConfig ¶
func DefaultCompressConfig() CompressConfig
DefaultCompressConfig returns the default compression configuration.
type HMACConfig ¶
type HMACConfig struct {
// Secret is the shared secret for HMAC signature verification.
// Required if KeyProvider is not set.
Secret string
// KeyProvider provides HMAC secrets by key ID.
// This allows for key rotation support.
// If set, takes precedence over Secret.
KeyProvider func(keyID string) string
// SignatureHeader is the header name for the HMAC signature.
// Default: "X-Signature"
SignatureHeader string
// TimestampHeader is the header name for the request timestamp.
// Default: "X-Timestamp"
TimestampHeader string
// KeyIDHeader is the header name for the key ID (for key rotation).
// Default: "X-Key-Id"
KeyIDHeader string
// ServiceHeader is the header name for the service identifier.
// Default: "X-Service"
ServiceHeader string
// MaxTimeDrift is the maximum allowed time difference between
// the request timestamp and server time.
// Default: 5 minutes
MaxTimeDrift time.Duration
// AllowEmptySecret allows requests when no secret is configured.
// This is useful for development mode but NOT recommended for production.
// Default: false
AllowEmptySecret bool
// SignatureFunc is a custom function to compute the expected signature.
// If nil, the default signature function is used:
// HMAC-SHA256(secret, timestamp:service:body)
SignatureFunc func(timestamp, service, body, secret string) string
// ErrorHandler is called when authentication fails.
ErrorHandler func(c *fiber.Ctx, err error) error
// SuccessHandler is called when authentication succeeds.
SuccessHandler func(c *fiber.Ctx)
// Logger for logging authentication events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
HMACConfig configures the HMAC signature authentication middleware.
func DefaultHMACConfig ¶
func DefaultHMACConfig() HMACConfig
DefaultHMACConfig returns the default HMAC configuration.
type LoggingConfig ¶
type LoggingConfig struct {
// Logger is the zerolog logger to use.
// If nil, logging is disabled.
Logger *zerolog.Logger
// SkipPaths is a list of paths to skip logging.
// Useful for health check endpoints.
SkipPaths []string
// LogRequestBody enables logging of request body.
// Warning: This may log sensitive data.
// Default: false
LogRequestBody bool
// LogResponseBody enables logging of response body.
// Warning: This may log sensitive data and impact performance.
// Default: false
LogResponseBody bool
// MaxBodyLogSize is the maximum body size to log (in bytes).
// Bodies larger than this are truncated.
// Default: 1024
MaxBodyLogSize int
// LogHeaders enables logging of request headers.
// Default: false
LogHeaders bool
// SensitiveHeaders is a list of header names to mask in logs.
// Default: ["Authorization", "X-API-Key", "Cookie", "Set-Cookie"]
SensitiveHeaders []string
// LogLevel is the log level for successful requests.
// Default: zerolog.InfoLevel
LogLevel zerolog.Level
// ErrorLogLevel is the log level for failed requests (status >= 400).
// Default: zerolog.WarnLevel
ErrorLogLevel zerolog.Level
// IncludeLatency includes request latency in logs.
// Default: true
IncludeLatency bool
// TrustedProxyConfig for client IP detection.
TrustedProxyConfig *TrustedProxyConfig
// CustomFields adds custom fields to each log entry.
CustomFields func(c *fiber.Ctx) map[string]interface{}
}
LoggingConfig configures the request logging middleware.
func DefaultLoggingConfig ¶
func DefaultLoggingConfig() LoggingConfig
DefaultLoggingConfig returns the default logging configuration.
type MTLSConfig ¶
type MTLSConfig struct {
// RequireCert requires a valid client certificate.
// If false, requests without certificates are allowed through.
// Default: true
RequireCert bool
// AllowedCNs is a list of allowed Common Names.
// If empty, any valid certificate is accepted.
AllowedCNs []string
// AllowedOUs is a list of allowed Organizational Units.
// If empty, any valid certificate is accepted.
AllowedOUs []string
// AllowedDNSSANs is a list of allowed DNS Subject Alternative Names.
// If empty, any valid certificate is accepted.
AllowedDNSSANs []string
// CertValidator is a custom function to validate the client certificate.
// If set, it's called after the built-in validation.
// Return nil to accept the certificate, or an error to reject it.
CertValidator func(cert *x509.Certificate) error
// ErrorHandler is called when authentication fails.
ErrorHandler func(c *fiber.Ctx, err error) error
// SuccessHandler is called when authentication succeeds.
// The verified certificate is passed to this handler.
SuccessHandler func(c *fiber.Ctx, cert *x509.Certificate)
// Logger for logging authentication events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
MTLSConfig configures the mTLS (mutual TLS) authentication middleware.
func DefaultMTLSConfig ¶
func DefaultMTLSConfig() MTLSConfig
DefaultMTLSConfig returns the default mTLS configuration.
type RateLimitConfig ¶
type RateLimitConfig struct {
// Limiter is the rate limiter to use.
// If nil, a new one is created with default settings.
Limiter *RateLimiter
// KeyFunc extracts the key to use for rate limiting from the request.
// Default: uses client IP
KeyFunc func(c *fiber.Ctx) string
// ErrorHandler is called when the rate limit is exceeded.
ErrorHandler func(c *fiber.Ctx) error
// SkipPaths is a list of paths to skip rate limiting.
SkipPaths []string
// Logger for logging rate limit events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection.
TrustedProxyConfig *TrustedProxyConfig
// OnLimitReached is called when the rate limit is reached.
// Useful for recording metrics.
OnLimitReached func(key string)
}
RateLimitConfig configures the rate limit middleware.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements an in-memory rate limiter with sliding window.
func NewRateLimiter ¶
func NewRateLimiter(cfg RateLimiterConfig) *RateLimiter
NewRateLimiter creates a new rate limiter with the given configuration.
func (*RateLimiter) AddToWhitelist ¶
func (rl *RateLimiter) AddToWhitelist(key string) bool
AddToWhitelist adds a key to the whitelist.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string) bool
Allow checks if a request from the given key should be allowed.
func (*RateLimiter) IsWhitelisted ¶
func (rl *RateLimiter) IsWhitelisted(key string) bool
IsWhitelisted checks if a key is in the whitelist.
func (*RateLimiter) RemoveFromWhitelist ¶
func (rl *RateLimiter) RemoveFromWhitelist(key string)
RemoveFromWhitelist removes a key from the whitelist.
func (*RateLimiter) Reset ¶
func (rl *RateLimiter) Reset()
Reset clears all visitor data and whitelist.
func (*RateLimiter) Stop ¶
func (rl *RateLimiter) Stop()
Stop stops the rate limiter and its cleanup goroutine.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
// Rate is the maximum number of requests allowed per window.
// Default: 100
Rate int
// Window is the time window for rate limiting.
// Default: 1 minute
Window time.Duration
// MaxVisitors is the maximum number of unique visitors to track.
// Oldest entries are evicted when this limit is reached.
// Default: 10000
MaxVisitors int
// MaxWhitelist is the maximum number of whitelisted IPs.
// Default: 100
MaxWhitelist int
// CleanupInterval is how often to clean up expired entries.
// Default: 1 minute
CleanupInterval time.Duration
}
RateLimiterConfig configures the rate limiter.
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig() RateLimiterConfig
DefaultRateLimiterConfig returns the default rate limiter configuration.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
// XContentTypeOptions sets X-Content-Type-Options header.
// Prevents MIME type sniffing.
// Default: "nosniff"
XContentTypeOptions string
// XFrameOptions sets X-Frame-Options header.
// Prevents clickjacking.
// Default: "DENY"
XFrameOptions string
// XXSSProtection sets X-XSS-Protection header.
// Enables browser XSS filter.
// Default: "1; mode=block"
XXSSProtection string
// ReferrerPolicy sets Referrer-Policy header.
// Controls referrer information.
// Default: "strict-origin-when-cross-origin"
ReferrerPolicy string
// ContentSecurityPolicy sets Content-Security-Policy header.
// Controls resource loading policy.
// Default: "" (not set)
ContentSecurityPolicy string
// StrictTransportSecurity sets Strict-Transport-Security header.
// Enforces HTTPS connections.
// Default: "" (not set, set to "max-age=31536000; includeSubDomains" for production)
StrictTransportSecurity string
// PermissionsPolicy sets Permissions-Policy header.
// Controls browser features.
// Default: "" (not set)
PermissionsPolicy string
// CrossOriginOpenerPolicy sets Cross-Origin-Opener-Policy header.
// Default: "" (not set)
CrossOriginOpenerPolicy string
// CrossOriginResourcePolicy sets Cross-Origin-Resource-Policy header.
// Default: "" (not set)
CrossOriginResourcePolicy string
// CrossOriginEmbedderPolicy sets Cross-Origin-Embedder-Policy header.
// Default: "" (not set)
CrossOriginEmbedderPolicy string
// CacheControl sets Cache-Control header.
// Default: "" (not set)
CacheControl string
// Pragma sets Pragma header.
// Default: "" (not set)
Pragma string
// CustomHeaders allows setting additional custom headers.
CustomHeaders map[string]string
}
SecurityHeadersConfig configures security headers middleware.
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns the default security headers configuration.
func StrictSecurityHeadersConfig ¶
func StrictSecurityHeadersConfig() SecurityHeadersConfig
StrictSecurityHeadersConfig returns a stricter security headers configuration. Suitable for production API servers.
type TrustedProxyConfig ¶
type TrustedProxyConfig struct {
// TrustedProxies is a list of trusted proxy IP addresses or CIDR ranges.
// If empty, private IP addresses are trusted by default.
TrustedProxies []string
// TrustAllProxies trusts all proxies (not recommended for production).
TrustAllProxies bool
// contains filtered or unexported fields
}
TrustedProxyConfig configures trusted proxy settings for client IP detection.
func DefaultTrustedProxyConfig ¶
func DefaultTrustedProxyConfig() *TrustedProxyConfig
DefaultTrustedProxyConfig returns a default configuration that trusts private IPs.
func NewTrustedProxyConfig ¶
func NewTrustedProxyConfig(proxies []string) *TrustedProxyConfig
NewTrustedProxyConfig creates a TrustedProxyConfig from a list of IP addresses or CIDR ranges.