middleware

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 19 Imported by: 2

README

middleware-kit

Go Reference Go Report Card License codecov

中文文档

A comprehensive HTTP middleware toolkit for Go services. This package provides authentication (API Key, HMAC, mTLS), rate limiting, security headers, request logging, compression, and body limiting middleware for both Fiber and standard net/http.

Features

  • Authentication Middleware

    • API Key authentication with multiple sources (header, query, Authorization)
    • HMAC signature verification with key rotation support
    • mTLS client certificate authentication with CN/OU/SAN filtering
    • Combined authentication with priority: mTLS > HMAC > API Key
  • Security Middleware

    • Security headers (XSS, clickjacking, MIME sniffing protection)
    • Configurable Content-Security-Policy
    • HSTS support
  • Traffic Control

    • In-memory rate limiting with sliding window
    • IP whitelist support
    • Configurable limits per client
  • Request Processing

    • Request body size limiting
    • Gzip compression with configurable thresholds
    • Request/response logging with sensitive data masking
  • Utilities

    • Client IP detection with trusted proxy support
    • Sensitive data masking (email, phone)

Installation

go get github.com/soulteary/middleware-kit

Usage

API Key Authentication
import (
    "github.com/gofiber/fiber/v2"
    middleware "github.com/soulteary/middleware-kit"
)

app := fiber.New()

// Simple API key authentication
app.Use(middleware.APIKeyAuth(middleware.APIKeyConfig{
    APIKey: "your-secret-api-key",
}))

// With multiple sources
app.Use(middleware.APIKeyAuth(middleware.APIKeyConfig{
    APIKey:         "your-secret-api-key",
    HeaderName:     "X-API-Key",           // Check this header
    AuthScheme:     "Bearer",               // Also check Authorization: Bearer <key>
    QueryParamName: "api_key",              // Also check ?api_key=<key>
}))
HMAC Signature Authentication
// Basic HMAC authentication
app.Use(middleware.HMACAuth(middleware.HMACConfig{
    Secret: "your-hmac-secret",
}))

// With key rotation support
keys := map[string]string{
    "key-v1": "secret-v1",
    "key-v2": "secret-v2",
}
app.Use(middleware.HMACAuth(middleware.HMACConfig{
    KeyProvider: func(keyID string) string {
        return keys[keyID]
    },
    MaxTimeDrift: 5 * time.Minute,
}))

// Computing HMAC signature on client side
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
signature := middleware.ComputeHMAC(timestamp, "service-name", requestBody, secret)
// Set headers: X-Signature, X-Timestamp, X-Service, X-Key-Id (optional)
mTLS Client Certificate Authentication
// Basic mTLS
app.Use(middleware.MTLSAuth(middleware.MTLSConfig{
    RequireCert: true,
}))

// With CN/OU restrictions
app.Use(middleware.MTLSAuth(middleware.MTLSConfig{
    RequireCert: true,
    AllowedCNs:  []string{"service-a", "service-b"},
    AllowedOUs:  []string{"engineering"},
}))

// With custom validator
app.Use(middleware.MTLSAuth(middleware.MTLSConfig{
    RequireCert: true,
    CertValidator: func(cert *x509.Certificate) error {
        // Custom validation logic
        if cert.NotAfter.Before(time.Now().Add(24 * time.Hour)) {
            return errors.New("certificate expires too soon")
        }
        return nil
    },
}))
Combined Authentication
// Try multiple authentication methods in order: mTLS > HMAC > API Key
app.Use(middleware.CombinedAuth(middleware.AuthConfig{
    MTLSConfig: &middleware.MTLSConfig{
        RequireCert: false, // Optional mTLS
    },
    HMACConfig: &middleware.HMACConfig{
        Secret: "hmac-secret",
    },
    APIKeyConfig: &middleware.APIKeyConfig{
        APIKey: "api-key",
    },
}))
Rate Limiting
// Create rate limiter
limiter := middleware.NewRateLimiter(middleware.RateLimiterConfig{
    Rate:   100,              // 100 requests
    Window: time.Minute,      // per minute
})
defer limiter.Stop()

// Add to middleware
app.Use(middleware.RateLimit(middleware.RateLimitConfig{
    Limiter:   limiter,
    SkipPaths: []string{"/health", "/metrics"},
}))

// Whitelist IPs
limiter.AddToWhitelist("10.0.0.1")

// Custom key function (e.g., rate limit by user ID)
app.Use(middleware.RateLimit(middleware.RateLimitConfig{
    Limiter: limiter,
    KeyFunc: func(c *fiber.Ctx) string {
        return c.Get("X-User-ID")
    },
}))
Security Headers
// Default security headers
app.Use(middleware.SecurityHeaders(middleware.DefaultSecurityHeadersConfig()))

// Strict security headers (recommended for production)
app.Use(middleware.SecurityHeaders(middleware.StrictSecurityHeadersConfig()))

// Custom configuration
app.Use(middleware.SecurityHeaders(middleware.SecurityHeadersConfig{
    XContentTypeOptions:     "nosniff",
    XFrameOptions:           "DENY",
    ContentSecurityPolicy:   "default-src 'self'",
    StrictTransportSecurity: "max-age=31536000; includeSubDomains",
}))

// No-cache headers for sensitive endpoints
app.Use("/api/sensitive", middleware.NoCacheHeaders())
Request Body Limiting
app.Use(middleware.BodyLimit(middleware.BodyLimitConfig{
    MaxSize:     4 * 1024 * 1024, // 4MB
    SkipMethods: []string{"GET", "HEAD"},
    SkipPaths:   []string{"/upload"}, // Allow larger uploads
}))
Gzip Compression (Standard HTTP)
import "net/http"

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!"))
})

compressed := middleware.CompressStd(middleware.DefaultCompressConfig())(handler)
http.ListenAndServe(":8080", compressed)
Request Logging
import "github.com/rs/zerolog"

logger := zerolog.New(os.Stdout)

app.Use(middleware.RequestLogging(middleware.LoggingConfig{
    Logger:     &logger,
    SkipPaths:  []string{"/health", "/metrics"},
    LogHeaders: true,
    SensitiveHeaders: []string{
        "Authorization",
        "X-API-Key",
        "Cookie",
    },
}))
Client IP Detection
// With trusted proxy configuration
trustedProxies := middleware.NewTrustedProxyConfig([]string{
    "10.0.0.0/8",
    "192.168.1.1",
})

// In Fiber handler
app.Get("/", func(c *fiber.Ctx) error {
    clientIP := middleware.GetClientIPFiber(c, trustedProxies)
    return c.SendString("Your IP: " + clientIP)
})

// In standard HTTP handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    clientIP := middleware.GetClientIP(r, trustedProxies)
    fmt.Fprintf(w, "Your IP: %s", clientIP)
})
Data Masking Utilities
// Mask email for logging
masked := middleware.MaskEmail("john.doe@example.com")
// Output: jo***@example.com

// Mask phone for logging
masked := middleware.MaskPhone("+1234567890")
// Output: +12***7890

Standard net/http Support

All middleware support both Fiber and standard net/http:

import (
    "net/http"
    middleware "github.com/soulteary/middleware-kit"
)

// API Key authentication
handler := middleware.APIKeyAuthStd(middleware.APIKeyConfig{
    APIKey: "your-api-key",
})(yourHandler)

// HMAC authentication
handler = middleware.HMACAuthStd(middleware.HMACConfig{
    Secret: "your-secret",
})(handler)

// Rate limiting
limiter := middleware.NewRateLimiter(middleware.DefaultRateLimiterConfig())
handler = middleware.RateLimitStd(middleware.RateLimitConfig{
    Limiter: limiter,
})(handler)

// Security headers
handler = middleware.SecurityHeadersStd(middleware.DefaultSecurityHeadersConfig())(handler)

// Body limit
handler = middleware.BodyLimitStd(middleware.BodyLimitConfig{
    MaxSize: 4 * 1024 * 1024,
})(handler)

// Compression
handler = middleware.CompressStd(middleware.DefaultCompressConfig())(handler)

// Logging
handler = middleware.RequestLoggingStd(middleware.LoggingConfig{
    Logger: &logger,
})(handler)

http.ListenAndServe(":8080", handler)

Project Structure

middleware-kit/
├── apikey.go           # API Key authentication
├── hmac.go             # HMAC signature authentication
├── mtls.go             # mTLS client certificate authentication
├── auth.go             # Combined authentication middleware
├── ratelimit.go        # Rate limiting
├── security.go         # Security headers
├── bodylimit.go        # Request body size limiting
├── compress.go         # Gzip compression
├── logging.go          # Request logging
├── clientip.go         # Client IP detection
├── helpers.go          # Utility functions
├── errors.go           # Error definitions
└── *_test.go           # Comprehensive tests

Requirements

  • Go 1.25 or later
  • github.com/gofiber/fiber/v2 v2.52.6+ (for Fiber middleware)
  • github.com/rs/zerolog v1.34.0+ (for logging)

Test Coverage

Run tests:

go test ./... -v

# With coverage
go test ./... -coverprofile=coverage.out -covermode=atomic
go tool cover -html=coverage.out -o coverage.html
go tool cover -func=coverage.out

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

See LICENSE file for details.

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.

Package middleware provides IP allowlist middleware for net/http. Only requests whose client IP is in the allowlist are permitted; others receive 403 Forbidden.

Index

Constants

This section is empty.

Variables

View Source
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 is a generic unauthorized error.
	ErrUnauthorized = errors.New("unauthorized")
)

Authentication errors

View Source
var (
	// ErrRateLimitExceeded indicates the rate limit has been exceeded.
	ErrRateLimitExceeded = errors.New("rate limit exceeded")
)

Rate limiting errors

View Source
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

func ComputeHMAC(timestamp, service, body, secret string) string

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 IPAllowlistMiddleware added in v1.1.0

func IPAllowlistMiddleware(allowlist string) func(http.Handler) http.Handler

IPAllowlistMiddleware returns an http.Handler that allows only requests from IPs or CIDR ranges in allowlist. allowlist is comma-separated (e.g. "127.0.0.1,10.0.0.0/8,192.168.1.1"). If allowlist is empty, the returned handler is a pass-through (all requests allowed). Client IP is resolved via GetClientIP(r, nil); use IPAllowlistMiddlewareFromConfig when you need OnDenied or TrustedProxyConfig.

func IPAllowlistMiddlewareFromConfig added in v1.1.0

func IPAllowlistMiddlewareFromConfig(cfg IPAllowlistConfig) func(http.Handler) http.Handler

IPAllowlistMiddlewareFromConfig returns an http.Handler that allows only requests from IPs or CIDR ranges in cfg.Allowlist. If cfg.Allowlist is empty, the returned handler is a pass-through. When access is denied, cfg.OnDenied is called if set, otherwise http.Error(w, "Forbidden", 403) is used. Client IP is resolved via GetClientIP(r, cfg.TrustedProxyConfig).

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

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

func MaskEmail(email string) string

MaskEmail masks an email address for logging. Example: john.doe@example.com -> jo***@example.com

func MaskPhone

func MaskPhone(phone string) string

MaskPhone masks a phone number for logging. Example: +1234567890 -> +123***7890

func NoCacheHeaders

func NoCacheHeaders() fiber.Handler

NoCacheHeaders creates a middleware that sets cache-control headers to prevent caching.

func NoCacheHeadersStd

func NoCacheHeadersStd() func(http.Handler) http.Handler

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 IPAllowlistConfig added in v1.1.0

type IPAllowlistConfig struct {
	// Allowlist is a comma-separated list of IP addresses and/or CIDR networks (e.g. "127.0.0.1,10.0.0.0/8").
	// If empty, all requests are allowed (pass-through).
	Allowlist string
	// OnDenied is called when the client IP is not in the allowlist. If nil, http.Error(w, "Forbidden", 403) is used.
	// Use this to log and then respond (e.g. log and http.Error).
	OnDenied func(w http.ResponseWriter, r *http.Request)
	// TrustedProxyConfig for client IP resolution. If nil, DefaultTrustedProxyConfig() is used.
	TrustedProxyConfig *TrustedProxyConfig
}

IPAllowlistConfig configures IP allowlist middleware.

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.

func (*TrustedProxyConfig) IsTrusted

func (c *TrustedProxyConfig) IsTrusted(ip net.IP) bool

IsTrusted checks if an IP address is from a trusted proxy.

Jump to

Keyboard shortcuts

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