Documentation
¶
Index ¶
- Variables
- func CORSMiddleware(config SecurityConfig) func(next http.Handler) http.Handler
- func CSRFMiddleware(config CSRFConfig, logger interface{}) func(next http.Handler) http.Handler
- func CleanedInput(r *http.Request) (map[string][]string, bool)
- func ContentTypeMiddleware(allowedTypes map[string][]string) func(next http.Handler) http.Handler
- func DoubleSubmitCSRFMiddleware(config CSRFConfig) func(next http.Handler) http.Handler
- func EnhancedCSRFMiddleware(config CSRFConfig) func(next http.Handler) http.Handler
- func GetCleanedFormValue(r *http.Request, key string) string
- func IPBlacklistMiddleware(blockedIPs []string) func(next http.Handler) http.Handler
- func IPThrottleMiddleware(config ThrottleConfig) func(next http.Handler) http.Handler
- func IPWhitelistMiddleware(allowedIPs []string) func(next http.Handler) http.Handler
- func InputValidationMiddleware(config InputValidationConfig) func(next http.Handler) http.Handler
- func RequestSizeMiddleware(maxBytes int64) func(next http.Handler) http.Handler
- func SecureMiddleware(config SecurityConfig) func(next http.Handler) http.Handler
- func SecurityHeadersMiddleware(config SecurityConfig) func(next http.Handler) http.Handler
- func SecurityLoggerMiddleware(logger *SecurityLogger) func(next http.Handler) http.Handler
- func SecurityMonitorMiddleware(monitor *SecurityMonitor) func(next http.Handler) http.Handler
- func TimeoutMiddleware(timeout time.Duration) func(next http.Handler) http.Handler
- type CSRFConfig
- type CSRFTokenHelper
- type Config
- type IPThrottler
- type InputValidationConfig
- type InputValidator
- type RateLimitConfig
- type SecurityConfig
- type SecurityEvent
- type SecurityEventType
- type SecurityLogger
- func (sl *SecurityLogger) LogAuthFailure(r *http.Request, userID string, reason string)
- func (sl *SecurityLogger) LogCSRFFailure(r *http.Request, reason string)
- func (sl *SecurityLogger) LogEvent(event SecurityEvent)
- func (sl *SecurityLogger) LogIPBlocked(r *http.Request, reason string)
- func (sl *SecurityLogger) LogInvalidOrigin(r *http.Request, origin string)
- func (sl *SecurityLogger) LogPathTraversal(r *http.Request, path string)
- func (sl *SecurityLogger) LogRateLimitExceeded(r *http.Request, limit int, duration time.Duration)
- func (sl *SecurityLogger) LogSQLInjectionAttempt(r *http.Request, payload string)
- func (sl *SecurityLogger) LogSuspiciousRequest(r *http.Request, reason string, severity string)
- func (sl *SecurityLogger) LogXSSAttempt(r *http.Request, payload string)
- type SecurityMonitor
- type ThreatDetails
- type ThrottleConfig
- type ValidationResult
Constants ¶
This section is empty.
Variables ¶
var DefaultInputValidator = NewInputValidator(DefaultInputValidationConfig(), DefaultSecurityLogger)
Global input validator instance
var DefaultSecurityLogger = NewSecurityLogger(nil)
Global security logger instance (can be configured per application)
var DefaultSecurityMonitor = NewSecurityMonitor(DefaultSecurityLogger, 5, 10*time.Minute)
Global security monitor instance
Functions ¶
func CORSMiddleware ¶
func CORSMiddleware(config SecurityConfig) func(next http.Handler) http.Handler
CORSMiddleware handles Cross-Origin Resource Sharing
func CSRFMiddleware ¶
func CSRFMiddleware(config CSRFConfig, logger interface{}) func(next http.Handler) http.Handler
CSRFMiddleware creates CSRF protection middleware.
Built on the double-submit implementation below rather than on nosurf, which this package used until v0.9.0. nosurf's design predates Sec-Fetch-Site and its same-origin check compared r.URL.Scheme -- empty on a server-side request, so the check never ran (CVE-2025-46721).
The framework's own router does not use this. It uses the session-backed tokens in the root package, which need no masking because the token is never exposed to the client. This exists for applications wiring the security package up directly, where no session manager is available.
func CleanedInput ¶ added in v0.7.0
CleanedInput returns the sanitised values InputValidationMiddleware produced for this request, if it ran.
func ContentTypeMiddleware ¶
ContentTypeMiddleware enforces specific content types for endpoints
func DoubleSubmitCSRFMiddleware ¶
func DoubleSubmitCSRFMiddleware(config CSRFConfig) func(next http.Handler) http.Handler
DoubleSubmitCSRFMiddleware implements double submit cookie pattern
func EnhancedCSRFMiddleware ¶
func EnhancedCSRFMiddleware(config CSRFConfig) func(next http.Handler) http.Handler
EnhancedCSRFMiddleware adds referrer checking and a frame guard on top of CSRFMiddleware.
func GetCleanedFormValue ¶
GetCleanedFormValue safely retrieves a cleaned form value, preferring the value InputValidationMiddleware sanitised for this request.
func IPBlacklistMiddleware ¶
IPBlacklistMiddleware blocks specific IP addresses
func IPThrottleMiddleware ¶
func IPThrottleMiddleware(config ThrottleConfig) func(next http.Handler) http.Handler
IPThrottleMiddleware creates IP-based throttling middleware
func IPWhitelistMiddleware ¶
IPWhitelistMiddleware allows only specific IP addresses
func InputValidationMiddleware ¶
func InputValidationMiddleware(config InputValidationConfig) func(next http.Handler) http.Handler
InputValidationMiddleware creates middleware for input validation
func RequestSizeMiddleware ¶
RequestSizeMiddleware limits request body size
func SecureMiddleware ¶
func SecureMiddleware(config SecurityConfig) func(next http.Handler) http.Handler
SecureMiddleware combines multiple security middlewares
func SecurityHeadersMiddleware ¶
func SecurityHeadersMiddleware(config SecurityConfig) func(next http.Handler) http.Handler
SecurityHeadersMiddleware adds security headers to all responses
func SecurityLoggerMiddleware ¶
func SecurityLoggerMiddleware(logger *SecurityLogger) func(next http.Handler) http.Handler
SecurityLoggerMiddleware creates middleware that logs security events
func SecurityMonitorMiddleware ¶
func SecurityMonitorMiddleware(monitor *SecurityMonitor) func(next http.Handler) http.Handler
SecurityMonitorMiddleware creates middleware that integrates with security monitor
Types ¶
type CSRFConfig ¶
type CSRFConfig struct {
// Token length in bytes
TokenLength int
// Cookie settings
CookieName string
CookiePath string
CookieDomain string
CookieSecure bool
CookieHttpOnly bool
CookieSameSite http.SameSite
CookieMaxAge int
// Request header name for CSRF token
RequestHeader string
// Form field name for CSRF token
FormField string
// Paths to exempt from CSRF protection
ExemptPaths []string
// Path patterns to exempt (supports wildcards)
ExemptGlobs []string
// Methods to exempt from CSRF protection
ExemptMethods []string
// Custom failure handler
FailureHandler http.Handler
}
CSRFConfig holds CSRF protection configuration
func DefaultCSRFConfig ¶
func DefaultCSRFConfig() CSRFConfig
DefaultCSRFConfig returns secure defaults
func DevelopmentCSRFConfig ¶
func DevelopmentCSRFConfig() CSRFConfig
DevelopmentCSRFConfig returns more lenient settings for development
type CSRFTokenHelper ¶
type CSRFTokenHelper struct {
// contains filtered or unexported fields
}
CSRFTokenHelper provides utility functions for CSRF tokens
func NewCSRFTokenHelper ¶
func NewCSRFTokenHelper(config CSRFConfig) *CSRFTokenHelper
NewCSRFTokenHelper creates a new CSRF token helper
func (*CSRFTokenHelper) GetToken ¶
func (h *CSRFTokenHelper) GetToken(r *http.Request) string
GetToken extracts the CSRF token from the request's cookie.
func (*CSRFTokenHelper) SetTokenCookie ¶
func (h *CSRFTokenHelper) SetTokenCookie(w http.ResponseWriter, token string)
SetTokenCookie sets CSRF token cookie on response
func (*CSRFTokenHelper) ValidateToken ¶
func (h *CSRFTokenHelper) ValidateToken(r *http.Request, token string) bool
ValidateToken reports whether token matches the request's.
Constant time: a comparison that returns early on the first differing byte leaks the token one byte at a time to anyone willing to measure.
type Config ¶
type Config struct {
// Environment
Environment string // development, staging, production
// Rate limiting
RateLimit RateLimitConfig
// Security headers
Headers SecurityConfig
// CSRF protection
CSRF CSRFConfig
// IP throttling
Throttle ThrottleConfig
// General security settings
EnableRateLimit bool
EnableHeaders bool
EnableCSRF bool
EnableThrottling bool
EnableCORS bool
EnableIPFilter bool
// Request limits
MaxRequestSize int64 // Maximum request body size
RequestTimeout time.Duration // Request timeout
// IP filtering
TrustedProxies []string
BlockedIPs []string
AllowedIPs []string
// API security
APIKeyRequired bool
APIKeyHeader string
}
Config holds all security-related configuration
func DevelopmentConfig ¶
func DevelopmentConfig() Config
DevelopmentConfig returns security configuration optimized for development
func LoadFromEnv ¶
func LoadFromEnv() Config
LoadFromEnv loads security configuration from environment variables
func ProductionConfig ¶
func ProductionConfig() Config
ProductionConfig returns security configuration optimized for production
func StagingConfig ¶
func StagingConfig() Config
StagingConfig returns security configuration for staging environment
func (*Config) GetSecuritySummary ¶
GetSecuritySummary returns a summary of enabled security features
func (*Config) ValidateConfig ¶
ValidateConfig validates the security configuration
type IPThrottler ¶
type IPThrottler struct {
// contains filtered or unexported fields
}
IPThrottler manages IP-based request throttling
func NewIPThrottler ¶
func NewIPThrottler(config ThrottleConfig) *IPThrottler
NewIPThrottler creates a new IP throttler
func (*IPThrottler) Allow ¶
func (t *IPThrottler) Allow(r *http.Request) (bool, string)
Allow checks if a request from an IP should be allowed
func (*IPThrottler) GetStats ¶
func (t *IPThrottler) GetStats() map[string]interface{}
GetStats returns current throttling statistics
func (*IPThrottler) GetTopThrottledIPs ¶
func (t *IPThrottler) GetTopThrottledIPs(limit int) []map[string]interface{}
GetTopThrottledIPs returns most throttled IPs for monitoring
func (*IPThrottler) RecordFailure ¶
func (t *IPThrottler) RecordFailure(r *http.Request, statusCode int)
RecordFailure records a failed request for an IP
func (*IPThrottler) Stop ¶ added in v0.7.0
func (t *IPThrottler) Stop()
cleanup removes old statistics entries Stop ends the cleanup goroutine. Safe to call more than once.
type InputValidationConfig ¶
type InputValidationConfig struct {
MaxFieldLength int
MaxTotalLength int
AllowHTML bool
StrictMode bool
CustomPatterns map[string]*regexp.Regexp
BlockedPatterns []*regexp.Regexp
ExemptPaths []string
ExemptMethods []string
}
InputValidationConfig holds configuration for input validation
func DefaultInputValidationConfig ¶
func DefaultInputValidationConfig() InputValidationConfig
DefaultInputValidationConfig returns a secure default configuration DefaultInputValidationConfig returns the default blocklist.
This is a secondary control. It exists to catch and log obvious probes, not to be the thing standing between an application and SQL injection -- that is what the parameterised queries in the database package are for. Treat a blocklist as a tripwire; never as the reason a query is safe.
type InputValidator ¶
type InputValidator struct {
// contains filtered or unexported fields
}
InputValidator handles centralized input validation
func NewInputValidator ¶
func NewInputValidator(config InputValidationConfig, logger *SecurityLogger) *InputValidator
NewInputValidator creates a new input validator
func (*InputValidator) ValidateRequest ¶
func (iv *InputValidator) ValidateRequest(r *http.Request) *ValidationResult
ValidateRequest validates all input data in a request
type RateLimitConfig ¶
type RateLimitConfig struct {
RequestsPerMinute int // Number of requests per minute
BurstSize int // Burst allowance
WindowSize time.Duration // Time window for rate limiting
SkipSuccessful bool // Only count failed requests (4xx, 5xx)
SkipPaths []string // Paths to skip rate limiting
}
RateLimitConfig holds rate limiting configuration
func DefaultRateLimitConfig ¶
func DefaultRateLimitConfig() RateLimitConfig
DefaultRateLimitConfig returns sensible defaults
type SecurityConfig ¶
type SecurityConfig struct {
// Content Security Policy
ContentSecurityPolicy string
// HSTS settings
HSTSMaxAge int
HSTSIncludeSubdomains bool
HSTSPreload bool
// Frame options
FrameOptions string // DENY, SAMEORIGIN, or ALLOW-FROM uri
// Content type options
ContentTypeNosniff bool
// XSS Protection
XSSProtection bool
XSSProtectionMode string // block, report=uri
// Referrer Policy
ReferrerPolicy string
// Permissions Policy
PermissionsPolicy string
// CORS settings
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
AllowedCredentials bool
MaxAge int
// Custom headers
CustomHeaders map[string]string
}
SecurityConfig holds security header configuration
func DefaultSecurityConfig ¶
func DefaultSecurityConfig() SecurityConfig
DefaultSecurityConfig returns secure defaults
func DevelopmentSecurityConfig ¶
func DevelopmentSecurityConfig() SecurityConfig
DevelopmentSecurityConfig returns more lenient settings for development
func ProductionSecurityConfig ¶
func ProductionSecurityConfig() SecurityConfig
ProductionSecurityConfig returns strict settings for production
type SecurityEvent ¶
type SecurityEvent struct {
Timestamp time.Time `json:"timestamp"`
EventType SecurityEventType `json:"event_type"`
Severity string `json:"severity"` // low, medium, high, critical
ClientIP string `json:"client_ip"`
UserAgent string `json:"user_agent"`
RequestURI string `json:"request_uri"`
Method string `json:"method"`
Headers map[string]string `json:"headers,omitempty"`
UserID string `json:"user_id,omitempty"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
Action string `json:"action"` // blocked, allowed, monitored
}
SecurityEvent represents a security-related event
type SecurityEventType ¶
type SecurityEventType string
SecurityEventType represents different types of security events
const ( EventRateLimitExceeded SecurityEventType = "rate_limit_exceeded" EventCSRFFailure SecurityEventType = "csrf_failure" EventSuspiciousRequest SecurityEventType = "suspicious_request" EventInvalidOrigin SecurityEventType = "invalid_origin" EventIPBlocked SecurityEventType = "ip_blocked" EventAuthFailure SecurityEventType = "auth_failure" EventSQLInjectionAttempt SecurityEventType = "sql_injection_attempt" EventXSSAttempt SecurityEventType = "xss_attempt" EventPathTraversal SecurityEventType = "path_traversal_attempt" )
type SecurityLogger ¶
type SecurityLogger struct {
// contains filtered or unexported fields
}
SecurityLogger handles structured logging of security events
func NewSecurityLogger ¶
func NewSecurityLogger(logger *log.Logger) *SecurityLogger
NewSecurityLogger creates a new security logger
func (*SecurityLogger) LogAuthFailure ¶
func (sl *SecurityLogger) LogAuthFailure(r *http.Request, userID string, reason string)
LogAuthFailure logs authentication failures
func (*SecurityLogger) LogCSRFFailure ¶
func (sl *SecurityLogger) LogCSRFFailure(r *http.Request, reason string)
LogCSRFFailure logs CSRF token validation failures
func (*SecurityLogger) LogEvent ¶
func (sl *SecurityLogger) LogEvent(event SecurityEvent)
LogEvent logs a security event in structured format
func (*SecurityLogger) LogIPBlocked ¶
func (sl *SecurityLogger) LogIPBlocked(r *http.Request, reason string)
LogIPBlocked logs blocked IP addresses
func (*SecurityLogger) LogInvalidOrigin ¶
func (sl *SecurityLogger) LogInvalidOrigin(r *http.Request, origin string)
LogInvalidOrigin logs invalid CORS origins
func (*SecurityLogger) LogPathTraversal ¶
func (sl *SecurityLogger) LogPathTraversal(r *http.Request, path string)
LogPathTraversal logs potential path traversal attempts
func (*SecurityLogger) LogRateLimitExceeded ¶
LogRateLimitExceeded logs rate limit violations
func (*SecurityLogger) LogSQLInjectionAttempt ¶
func (sl *SecurityLogger) LogSQLInjectionAttempt(r *http.Request, payload string)
LogSQLInjectionAttempt logs potential SQL injection attempts
func (*SecurityLogger) LogSuspiciousRequest ¶
func (sl *SecurityLogger) LogSuspiciousRequest(r *http.Request, reason string, severity string)
LogSuspiciousRequest logs requests that match suspicious patterns
func (*SecurityLogger) LogXSSAttempt ¶
func (sl *SecurityLogger) LogXSSAttempt(r *http.Request, payload string)
LogXSSAttempt logs potential XSS attempts
type SecurityMonitor ¶
type SecurityMonitor struct {
// contains filtered or unexported fields
}
SecurityMonitor tracks security events and patterns
func NewSecurityMonitor ¶
func NewSecurityMonitor(logger *SecurityLogger, alertThreshold int, blockDuration time.Duration) *SecurityMonitor
NewSecurityMonitor creates a new security monitor
func (*SecurityMonitor) GetSecurityStats ¶
func (sm *SecurityMonitor) GetSecurityStats() map[string]interface{}
GetSecurityStats returns current security statistics
func (*SecurityMonitor) IsIPBlocked ¶
func (sm *SecurityMonitor) IsIPBlocked(ip string) bool
IsIPBlocked checks if an IP is currently blocked
func (*SecurityMonitor) RecordEvent ¶
func (sm *SecurityMonitor) RecordEvent(event SecurityEvent)
RecordEvent records a security event and checks for patterns
type ThreatDetails ¶
ThreatDetails contains information about detected threats
type ThrottleConfig ¶
type ThrottleConfig struct {
// Basic rate limiting
RequestsPerMinute int
BurstSize int
WindowSize time.Duration
// Progressive penalties
EnableProgressive bool
MaxPenaltyMinutes int
// Suspicious behavior detection
EnableSuspiciousDetection bool
SuspiciousThreshold int // Failed requests in window
SuspiciousPenaltyMinutes int
// Subnet-based limiting
EnableSubnetLimiting bool
SubnetRequestsPerMinute int
SubnetMask int // /24, /16, etc.
// Whitelist/Blacklist
WhitelistedIPs []string
BlacklistedIPs []string
// Custom headers to check for real IP
TrustedProxyHeaders []string
TrustedProxies []string
}
ThrottleConfig holds IP-based throttling configuration
func DefaultThrottleConfig ¶
func DefaultThrottleConfig() ThrottleConfig
DefaultThrottleConfig returns sensible defaults
type ValidationResult ¶
type ValidationResult struct {
Valid bool
Errors []string
CleanedInput map[string][]string
Threats []ThreatDetails
}
ValidationResult holds the result of input validation