middleware

package
v0.1.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: GPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

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

func APIKeyLimiter(maxRequests int, duration time.Duration) fiber.Handler

APIKeyLimiter limits requests per API key with configurable limits Should be applied AFTER API key authentication middleware

func AdminLoginLimiter

func AdminLoginLimiter() fiber.Handler

AdminLoginLimiter limits admin login attempts per IP

func AdminSetupLimiter

func AdminSetupLimiter() fiber.Handler

AdminSetupLimiter limits admin setup attempts per IP Very strict since this is a one-time operation

func AdminUISecurityHeaders

func AdminUISecurityHeaders() fiber.Handler

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

func AuthEmailBasedLimiter(prefix string, max int, expiration time.Duration) fiber.Handler

AuthEmailBasedLimiter limits requests per email address (for sensitive operations)

func AuthLoginLimiter

func AuthLoginLimiter() fiber.Handler

AuthLoginLimiter limits login attempts per IP

func AuthMagicLinkLimiter

func AuthMagicLinkLimiter() fiber.Handler

AuthMagicLinkLimiter limits magic link requests per IP

func AuthPasswordResetLimiter

func AuthPasswordResetLimiter() fiber.Handler

AuthPasswordResetLimiter limits password reset requests per IP

func AuthRefreshLimiter

func AuthRefreshLimiter() fiber.Handler

AuthRefreshLimiter limits token refresh attempts per token

func AuthSignupLimiter

func AuthSignupLimiter() fiber.Handler

AuthSignupLimiter limits signup attempts per IP

func AuthenticatedUserLimiter

func AuthenticatedUserLimiter() fiber.Handler

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

func DefaultAPIKeyLimiter() fiber.Handler

DefaultAPIKeyLimiter returns an API key limiter with default limits (1000 req/min)

func GetCSRFToken

func GetCSRFToken(c *fiber.Ctx) string

GetCSRFToken is a helper to retrieve the CSRF token for the current request

func GlobalAPILimiter

func GlobalAPILimiter() fiber.Handler

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

func OptionalAPIKeyAuth(authService *auth.Service, apiKeyService *auth.APIKeyService) fiber.Handler

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

func PerUserOrIPLimiter(anonMax, userMax, apiKeyMax int, duration time.Duration) fiber.Handler

PerUserOrIPLimiter implements tiered rate limiting: - Authenticated users: higher limit - API keys: configurable limit - Anonymous (IP): lower limit

func RLSMiddleware

func RLSMiddleware(config RLSConfig) fiber.Handler

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

func RequireEitherAuth(authService *auth.Service, apiKeyService *auth.APIKeyService) fiber.Handler

RequireEitherAuth requires either JWT or API key authentication This is the recommended middleware for protecting API endpoints

func RequireScope

func RequireScope(requiredScopes ...string) fiber.Handler

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

func SetRLSContext(ctx context.Context, tx pgx.Tx, userID interface{}, role string) error

SetRLSContext sets PostgreSQL session variables for RLS enforcement This should be called at the beginning of each database transaction

func SlowQueryLogger

func SlowQueryLogger(threshold time.Duration) func(query string, duration time.Duration, err error)

SlowQueryLogger logs slow database queries

func StructuredLogger

func StructuredLogger(config ...StructuredLoggerConfig) fiber.Handler

StructuredLogger returns a middleware that logs requests with structured logging

func WrapWithRLS

func WrapWithRLS(ctx context.Context, conn *database.Connection, c *fiber.Ctx, fn func(tx pgx.Tx) error) error

WrapWithRLS wraps a database operation with RLS context This is a helper function for setting RLS context in queries

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

Jump to

Keyboard shortcuts

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