Documentation
¶
Index ¶
- func APIKeyAuth(apiKeyService *auth.APIKeyService) fiber.Handler
- func APIKeyLimiter(maxRequests int, duration time.Duration) fiber.Handler
- func AdminLoginLimiter() fiber.Handler
- func AdminSetupLimiter() fiber.Handler
- func AdminUISecurityHeaders() fiber.Handler
- func AuthEmailBasedLimiter(prefix string, max int, expiration time.Duration) fiber.Handler
- func AuthLoginLimiter() fiber.Handler
- func AuthMagicLinkLimiter() fiber.Handler
- func AuthPasswordResetLimiter() fiber.Handler
- func AuthRefreshLimiter() fiber.Handler
- func AuthSignupLimiter() fiber.Handler
- func AuthenticatedUserLimiter() fiber.Handler
- func CSRF(config ...CSRFConfig) fiber.Handler
- func DefaultAPIKeyLimiter() fiber.Handler
- func GetCSRFToken(c *fiber.Ctx) string
- func GlobalAPILimiter() fiber.Handler
- func NewRateLimiter(config RateLimiterConfig) fiber.Handler
- func OptionalAPIKeyAuth(authService *auth.Service, apiKeyService *auth.APIKeyService) fiber.Handler
- func OptionalAuthOrServiceKey(authService *auth.Service, apiKeyService *auth.APIKeyService, db *pgxpool.Pool) fiber.Handler
- func PerUserOrIPLimiter(anonMax, userMax, apiKeyMax int, duration time.Duration) fiber.Handler
- func RLSMiddleware(config RLSConfig) fiber.Handler
- func RequireAuthOrServiceKey(authService *auth.Service, apiKeyService *auth.APIKeyService, db *pgxpool.Pool, ...) fiber.Handler
- func RequireEitherAuth(authService *auth.Service, apiKeyService *auth.APIKeyService) fiber.Handler
- func RequireScope(requiredScopes ...string) fiber.Handler
- func SecurityHeaders(config ...SecurityHeadersConfig) fiber.Handler
- func SetRLSContext(ctx context.Context, tx pgx.Tx, userID interface{}, role string) error
- func SlowQueryLogger(threshold time.Duration) func(query string, duration time.Duration, err error)
- func StructuredLogger(config ...StructuredLoggerConfig) fiber.Handler
- func WrapWithRLS(ctx context.Context, conn *database.Connection, c *fiber.Ctx, ...) error
- type AuditLogger
- func (al *AuditLogger) LogAPIKeyOperation(c *fiber.Ctx, action, keyID, keyName, performedBy string)
- func (al *AuditLogger) LogAuth(c *fiber.Ctx, event, userID, email string, success bool)
- func (al *AuditLogger) LogConfigChange(c *fiber.Ctx, setting, oldValue, newValue, performedBy string)
- func (al *AuditLogger) LogSecurityEvent(c *fiber.Ctx, event, description, severity string)
- func (al *AuditLogger) LogUserManagement(c *fiber.Ctx, action, targetUserID, performedBy string)
- type CSRFConfig
- type RLSConfig
- type RLSContext
- type RateLimiterConfig
- type SecurityHeadersConfig
- type StructuredLoggerConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIKeyAuth ¶
func APIKeyAuth(apiKeyService *auth.APIKeyService) fiber.Handler
APIKeyAuth creates middleware that authenticates requests using API keys Checks for API key in X-API-Key header or apikey query parameter
func APIKeyLimiter ¶
APIKeyLimiter limits requests per API key with configurable limits Should be applied AFTER API key authentication middleware
func AdminLoginLimiter ¶
AdminLoginLimiter limits admin login attempts per IP
func AdminSetupLimiter ¶
AdminSetupLimiter limits admin setup attempts per IP Very strict since this is a one-time operation
func AdminUISecurityHeaders ¶
AdminUISecurityHeaders returns relaxed security headers for Admin UI Admin UI needs 'unsafe-inline' and 'unsafe-eval' for React Also allows Google Fonts from googleapis.com and gstatic.com
func AuthEmailBasedLimiter ¶
AuthEmailBasedLimiter limits requests per email address (for sensitive operations)
func AuthLoginLimiter ¶
AuthLoginLimiter limits login attempts per IP
func AuthMagicLinkLimiter ¶
AuthMagicLinkLimiter limits magic link requests per IP
func AuthPasswordResetLimiter ¶
AuthPasswordResetLimiter limits password reset requests per IP
func AuthRefreshLimiter ¶
AuthRefreshLimiter limits token refresh attempts per token
func AuthSignupLimiter ¶
AuthSignupLimiter limits signup attempts per IP
func AuthenticatedUserLimiter ¶
AuthenticatedUserLimiter limits requests per authenticated user (higher limits than IP-based) Should be applied AFTER authentication middleware
func CSRF ¶
func CSRF(config ...CSRFConfig) fiber.Handler
CSRF returns a middleware that protects against Cross-Site Request Forgery attacks
func DefaultAPIKeyLimiter ¶
DefaultAPIKeyLimiter returns an API key limiter with default limits (1000 req/min)
func GetCSRFToken ¶
GetCSRFToken is a helper to retrieve the CSRF token for the current request
func GlobalAPILimiter ¶
GlobalAPILimiter is a general rate limiter for all API endpoints
func NewRateLimiter ¶
func NewRateLimiter(config RateLimiterConfig) fiber.Handler
NewRateLimiter creates a new rate limiter middleware with custom configuration
func OptionalAPIKeyAuth ¶
OptionalAPIKeyAuth allows both JWT and API key authentication Tries JWT first, then API key
func OptionalAuthOrServiceKey ¶
func OptionalAuthOrServiceKey(authService *auth.Service, apiKeyService *auth.APIKeyService, db *pgxpool.Pool) fiber.Handler
OptionalAuthOrServiceKey allows either JWT, API key, OR service key authentication If no authentication is provided, the request continues (for anonymous access with RLS) IMPORTANT: If invalid credentials are provided, returns 401 (does not fall back to anonymous)
func PerUserOrIPLimiter ¶
PerUserOrIPLimiter implements tiered rate limiting: - Authenticated users: higher limit - API keys: configurable limit - Anonymous (IP): lower limit
func RLSMiddleware ¶
RLSMiddleware enforces Row Level Security by setting PostgreSQL session variables based on the authenticated user context
func RequireAuthOrServiceKey ¶
func RequireAuthOrServiceKey(authService *auth.Service, apiKeyService *auth.APIKeyService, db *pgxpool.Pool, jwtManager ...*auth.JWTManager) fiber.Handler
RequireAuthOrServiceKey requires either JWT, API key, OR service key authentication This is the most comprehensive auth middleware that accepts all authentication methods
func RequireEitherAuth ¶
RequireEitherAuth requires either JWT or API key authentication This is the recommended middleware for protecting API endpoints
func RequireScope ¶
RequireScope checks if the authenticated user/API key has required scopes
func SecurityHeaders ¶
func SecurityHeaders(config ...SecurityHeadersConfig) fiber.Handler
SecurityHeaders returns a middleware that adds security headers to all responses
func SetRLSContext ¶
SetRLSContext sets PostgreSQL session variables for RLS enforcement This should be called at the beginning of each database transaction
func SlowQueryLogger ¶
SlowQueryLogger logs slow database queries
func StructuredLogger ¶
func StructuredLogger(config ...StructuredLoggerConfig) fiber.Handler
StructuredLogger returns a middleware that logs requests with structured logging
Types ¶
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger logs security-sensitive events (auth, user management, config changes)
func NewAuditLogger ¶
func NewAuditLogger(logger zerolog.Logger) *AuditLogger
NewAuditLogger creates a new audit logger
func (*AuditLogger) LogAPIKeyOperation ¶
func (al *AuditLogger) LogAPIKeyOperation(c *fiber.Ctx, action, keyID, keyName, performedBy string)
LogAPIKeyOperation logs API key operations
func (*AuditLogger) LogAuth ¶
func (al *AuditLogger) LogAuth(c *fiber.Ctx, event, userID, email string, success bool)
LogAuth logs authentication events
func (*AuditLogger) LogConfigChange ¶
func (al *AuditLogger) LogConfigChange(c *fiber.Ctx, setting, oldValue, newValue, performedBy string)
LogConfigChange logs configuration changes
func (*AuditLogger) LogSecurityEvent ¶
func (al *AuditLogger) LogSecurityEvent(c *fiber.Ctx, event, description, severity string)
LogSecurityEvent logs security-related events
func (*AuditLogger) LogUserManagement ¶
func (al *AuditLogger) LogUserManagement(c *fiber.Ctx, action, targetUserID, performedBy string)
LogUserManagement logs user management events
type CSRFConfig ¶
type CSRFConfig struct {
// TokenLength is the length of the CSRF token in bytes
TokenLength int
// TokenLookup defines where to find the token (header:X-CSRF-Token or form:_csrf)
TokenLookup string
// CookieName is the name of the CSRF cookie
CookieName string
// CookieDomain is the domain of the CSRF cookie
CookieDomain string
// CookiePath is the path of the CSRF cookie
CookiePath string
// CookieSecure marks the cookie as secure (HTTPS only)
CookieSecure bool
// CookieHTTPOnly marks the cookie as HTTP only
CookieHTTPOnly bool
// CookieSameSite defines the SameSite attribute
CookieSameSite string
// Expiration is how long tokens are valid
Expiration time.Duration
// Storage is used to store tokens (default: in-memory)
Storage fiber.Storage
}
CSRFConfig holds configuration for CSRF protection
func DefaultCSRFConfig ¶
func DefaultCSRFConfig() CSRFConfig
DefaultCSRFConfig returns default CSRF configuration
type RLSConfig ¶
type RLSConfig struct {
// DB is the database connection pool
DB *database.Connection
// Enabled controls whether RLS enforcement is active
Enabled bool
// SessionVarPrefix is the prefix for PostgreSQL session variables
// Default: "app"
SessionVarPrefix string
}
RLSConfig holds configuration for RLS middleware
type RLSContext ¶
type RLSContext struct {
UserID interface{}
Role string
}
GetRLSContext extracts RLS context from Fiber context
func GetRLSContext ¶
func GetRLSContext(c *fiber.Ctx) RLSContext
type RateLimiterConfig ¶
type RateLimiterConfig struct {
Max int // Maximum number of requests
Expiration time.Duration // Time window for the rate limit
KeyFunc func(*fiber.Ctx) string // Function to generate the key for rate limiting
Message string // Custom error message
}
RateLimiterConfig holds configuration for rate limiting
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
// Content Security Policy
ContentSecurityPolicy string
// X-Frame-Options
XFrameOptions string
// X-Content-Type-Options
XContentTypeOptions string
// X-XSS-Protection
XXSSProtection string
// Strict-Transport-Security (HSTS)
StrictTransportSecurity string
// Referrer-Policy
ReferrerPolicy string
// Permissions-Policy
PermissionsPolicy string
}
SecurityHeadersConfig holds configuration for security headers
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns secure default configuration
type StructuredLoggerConfig ¶
type StructuredLoggerConfig struct {
// SkipPaths are paths that should not be logged (e.g., health checks)
SkipPaths []string
// SkipSuccessfulRequests skips logging successful requests (2xx status codes)
SkipSuccessfulRequests bool
// Logger is the zerolog logger to use (defaults to global log)
Logger *zerolog.Logger
// LogRequestBody logs the request body (be careful with sensitive data)
LogRequestBody bool
// LogResponseBody logs the response body (be careful with sensitive data)
LogResponseBody bool
// SlowRequestThreshold logs slow requests with WARN level (0 = disabled)
SlowRequestThreshold time.Duration
}
StructuredLoggerConfig holds configuration for structured logging
func DefaultStructuredLoggerConfig ¶
func DefaultStructuredLoggerConfig() StructuredLoggerConfig
DefaultStructuredLoggerConfig returns default configuration