Documentation
¶
Overview ¶
Package middleware provides HTTP middleware components for the GraphDB API server.
The middleware package is organized into separate files by concern:
- recovery.go: Panic recovery middleware
- logging.go: Request logging middleware
- cors.go: Cross-Origin Resource Sharing (CORS) middleware
- security_headers.go: Security headers middleware (XSS, clickjacking, etc.)
- body_limit.go: Request body size limiting middleware
- request_id.go: Request ID generation and tracking middleware
- ratelimit.go: Rate limiting middleware with token bucket algorithm
- input_validation.go: Input validation and sanitization middleware
- metrics.go: HTTP metrics collection middleware
All middleware follows the standard pattern: func(http.Handler) http.Handler This allows easy chaining: handler = middleware1(middleware2(handler))
Example usage:
mux := http.NewServeMux()
// ... register handlers ...
// Apply middleware chain
handler := middleware.PanicRecovery()(mux)
handler = middleware.RequestID()(handler)
handler = middleware.Logging(middleware.GetRequestID)(handler)
handler = middleware.CORS(middleware.DefaultCORSConfig())(handler)
http.ListenAndServe(":8080", handler)
Index ¶
- Constants
- func BodySizeLimit(maxBytes int64) func(http.Handler) http.Handler
- func CORS(config *CORSConfig) func(http.Handler) http.Handler
- func GetClientIP(r *http.Request) string
- func GetClientIPWithProxies(r *http.Request, trustedNetworks []*net.IPNet) string
- func GetRequestID(r *http.Request) string
- func InitTrustedProxiesFromEnv()
- func InputValidation(config *InputValidationConfig) func(http.Handler) http.Handler
- func IsTrustedProxy(remoteAddr string) bool
- func IsTrustedProxyIn(remoteAddr string, trustedNetworks []*net.IPNet) bool
- func Logging(getRequestID func(*http.Request) string) func(http.Handler) http.Handler
- func Metrics(recorder MetricsRecorder) func(http.Handler) http.Handler
- func PanicRecovery() func(http.Handler) http.Handler
- func ParseTrustedProxies(proxiesStr string) []*net.IPNet
- func RateLimit(limiter *RateLimiter, getClientID ClientIDFunc, ...) func(http.Handler) http.Handler
- func RequestID() func(http.Handler) http.Handler
- func SecurityHeaders(config *SecurityHeadersConfig) func(http.Handler) http.Handler
- type CORSConfig
- type ClientIDFunc
- type ContextKey
- type InputValidationConfig
- type MetricsRecorder
- type RateLimitConfig
- type RateLimiter
- type SecurityHeadersConfig
- type TrustedProxyConfig
Constants ¶
const RequestIDHeader = "X-Request-ID"
RequestIDHeader is the header name for request IDs
Variables ¶
This section is empty.
Functions ¶
func BodySizeLimit ¶
BodySizeLimit creates middleware that limits the size of incoming request bodies to prevent denial-of-service attacks via large payloads. The maxBytes parameter specifies the maximum allowed size in bytes.
func CORS ¶
func CORS(config *CORSConfig) func(http.Handler) http.Handler
CORS creates middleware that handles Cross-Origin Resource Sharing.
func GetClientIP ¶
GetClientIP extracts the client IP address from a request. SECURITY: Only trusts X-Forwarded-For and X-Real-IP headers when the request comes from a configured trusted proxy. This prevents IP spoofing attacks.
func GetClientIPWithProxies ¶
GetClientIPWithProxies extracts the client IP with custom trusted proxy list.
func GetRequestID ¶
GetRequestID extracts request ID from request context
func InitTrustedProxiesFromEnv ¶
func InitTrustedProxiesFromEnv()
InitTrustedProxiesFromEnv initializes trusted proxies from TRUSTED_PROXIES environment variable. Format: comma-separated CIDR ranges, e.g., "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16" This is called automatically on first use, but can be called explicitly during server init.
func InputValidation ¶
func InputValidation(config *InputValidationConfig) func(http.Handler) http.Handler
InputValidation creates middleware that validates input for security issues. This protects against injection attacks, XSS, path traversal, etc.
func IsTrustedProxy ¶
IsTrustedProxy checks if the given remote address is from a trusted proxy. Uses the global trusted proxies list initialized from environment.
func IsTrustedProxyIn ¶
IsTrustedProxyIn checks if the given remote address is in the provided networks.
func Logging ¶
Logging creates middleware that logs HTTP requests with timing information. It uses the request ID from context if available.
func Metrics ¶
func Metrics(recorder MetricsRecorder) func(http.Handler) http.Handler
Metrics creates middleware that tracks HTTP request metrics.
func PanicRecovery ¶
PanicRecovery creates middleware that recovers from panics in HTTP handlers. This prevents server crashes and returns a proper error response. Internal details are logged but not exposed to clients.
func ParseTrustedProxies ¶
ParseTrustedProxies parses a comma-separated list of CIDR ranges or IP addresses.
func RateLimit ¶
func RateLimit(limiter *RateLimiter, getClientID ClientIDFunc, onLimited func(w http.ResponseWriter, r *http.Request, clientID string)) func(http.Handler) http.Handler
RateLimit creates middleware that applies rate limiting per client. The getClientID function extracts the client identifier from the request. The onLimited function is called when a request is rate limited (optional).
func RequestID ¶
RequestID creates middleware that adds a unique request ID to each request. If the client provides X-Request-ID header, it will be used (after sanitization). Otherwise, a new ID is generated.
func SecurityHeaders ¶
func SecurityHeaders(config *SecurityHeadersConfig) func(http.Handler) http.Handler
SecurityHeaders creates middleware that adds security headers to responses. This protects against clickjacking, MIME sniffing, XSS, and other attacks.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins []string // List of allowed origins, or ["*"] for all (not recommended for production)
AllowedMethods []string // HTTP methods allowed
AllowedHeaders []string // Headers allowed in requests
AllowCredentials bool // Whether credentials (cookies, auth headers) are allowed
MaxAge int // Preflight cache duration in seconds
}
CORSConfig holds CORS configuration
func DefaultCORSConfig ¶
func DefaultCORSConfig() *CORSConfig
DefaultCORSConfig returns secure default CORS configuration
type ClientIDFunc ¶
ClientIDFunc is a function that extracts a client identifier from a request
type ContextKey ¶
type ContextKey string
ContextKey is a type for context keys to avoid collisions
const RequestIDContextKey ContextKey = "request_id"
RequestIDContextKey is the context key for storing request IDs
type InputValidationConfig ¶
type InputValidationConfig struct {
SkipPaths []string // Paths to skip validation for
MaxBodySize int // Maximum body size to validate (default: 10MB)
ValidateAll bool // If true, validate all methods (not just POST/PUT/PATCH)
}
InputValidationConfig configures input validation middleware
func DefaultInputValidationConfig ¶
func DefaultInputValidationConfig() *InputValidationConfig
DefaultInputValidationConfig returns default configuration
type MetricsRecorder ¶
type MetricsRecorder interface {
RecordHTTPRequest(method, path, status string, duration time.Duration)
RecordResponseSize(method, path string, size float64)
IncHTTPRequestsInFlight()
DecHTTPRequestsInFlight()
}
MetricsRecorder is an interface for recording HTTP metrics
type RateLimitConfig ¶
type RateLimitConfig struct {
RequestsPerSecond float64 // Rate of token replenishment
BurstSize int // Maximum burst size (bucket capacity)
CleanupInterval time.Duration // How often to clean up expired buckets
ClientExpiration time.Duration // How long to keep inactive client buckets
MaxClients int // Maximum number of tracked clients (prevents DoS via memory exhaustion)
}
RateLimitConfig configures rate limiting
func DefaultRateLimitConfig ¶
func DefaultRateLimitConfig() *RateLimitConfig
DefaultRateLimitConfig returns sensible defaults for rate limiting
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter manages rate limiting for multiple clients
func NewRateLimiter ¶
func NewRateLimiter(config *RateLimitConfig) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(clientID string) bool
Allow checks if a request from the given client should be allowed. Returns false if the client is rate limited or if max clients has been reached.
func (*RateLimiter) GetConfig ¶
func (rl *RateLimiter) GetConfig() *RateLimitConfig
GetConfig returns the rate limiter configuration (for header values)
func (*RateLimiter) GetStats ¶
func (rl *RateLimiter) GetStats() map[string]any
GetStats returns current rate limiter statistics
func (*RateLimiter) Stop ¶
func (rl *RateLimiter) Stop()
Stop stops the rate limiter cleanup goroutine
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
TLSEnabled bool // Whether TLS is enabled (for HSTS header)
}
SecurityHeadersConfig holds configuration for security headers
type TrustedProxyConfig ¶
type TrustedProxyConfig struct {
// TrustedNetworks holds the list of trusted proxy CIDR ranges.
// Only requests from these IPs will have X-Forwarded-For/X-Real-IP headers trusted.
TrustedNetworks []*net.IPNet
}
TrustedProxyConfig configures trusted proxy handling