Documentation
¶
Overview ¶
Package middleware provides common HTTP middleware for Nivo services.
Index ¶
- Constants
- func Auth(config AuthConfig) func(http.Handler) http.Handler
- func CSRFTokenFromRequest(r *http.Request) string
- func Chain(handler http.Handler, middleware ...Middleware) http.Handler
- func GetAccountType(ctx context.Context) (string, bool)
- func GetUserEmail(ctx context.Context) (string, bool)
- func GetUserID(ctx context.Context) (string, bool)
- func GetUserPermissions(ctx context.Context) ([]string, bool)
- func GetUserRoles(ctx context.Context) ([]string, bool)
- func GetUserStatus(ctx context.Context) (string, bool)
- func InternalAuth(config InternalAuthConfig) func(http.Handler) http.Handler
- func InternalAuthFunc(secret string, next http.HandlerFunc) http.HandlerFunc
- func RateLimit(config RateLimitConfig) func(http.Handler) http.Handler
- func RequireAnyPermission(permissions ...string) func(http.Handler) http.Handler
- func RequireAnyRole(roles ...string) func(http.Handler) http.Handler
- func RequirePermission(permission string) func(http.Handler) http.Handler
- func RequireRole(role string) func(http.Handler) http.Handler
- type AuthConfig
- type CORSConfig
- type CSRFConfig
- type ContextKey
- type InternalAuthConfig
- type JWTClaims
- type Middleware
- func CORS(config CORSConfig) Middleware
- func CSRF(config CSRFConfig) Middleware
- func Logging(log *logger.Logger) Middleware
- func Recovery(log *logger.Logger) Middleware
- func RecoveryWithHandler(log *logger.Logger, ...) Middleware
- func RequestID() Middleware
- func Timeout(duration time.Duration) Middleware
- type RateLimitConfig
- type ResponseWriter
Constants ¶
const ( // CSRFTokenHeader is the header name for CSRF token. CSRFTokenHeader = "X-CSRF-Token" //nolint:gosec // Not a credential, just a header name // CSRFCookieName is the cookie name for CSRF token. CSRFCookieName = "csrf_token" // CSRFTokenLength is the length of the CSRF token in bytes (32 bytes = 64 hex chars). CSRFTokenLength = 32 )
Variables ¶
This section is empty.
Functions ¶
func Auth ¶
func Auth(config AuthConfig) func(http.Handler) http.Handler
Auth creates a middleware that validates JWT tokens and extracts user claims.
func CSRFTokenFromRequest ¶
CSRFTokenFromRequest extracts the CSRF token from the request cookie. This can be used by handlers that need to include the token in responses.
func Chain ¶
func Chain(handler http.Handler, middleware ...Middleware) http.Handler
Chain applies multiple middleware in order. Middleware are applied in the order they are provided.
func GetAccountType ¶
GetAccountType extracts the account type from the request context.
func GetUserEmail ¶
GetUserEmail extracts the user email from the request context.
func GetUserPermissions ¶
GetUserPermissions extracts the user permissions from the request context.
func GetUserRoles ¶
GetUserRoles extracts the user roles from the request context.
func GetUserStatus ¶
GetUserStatus extracts the user status from the request context.
func InternalAuth ¶
func InternalAuth(config InternalAuthConfig) func(http.Handler) http.Handler
InternalAuth creates a middleware that validates service-to-service requests using a shared secret header. This protects internal endpoints from external access.
func InternalAuthFunc ¶
func InternalAuthFunc(secret string, next http.HandlerFunc) http.HandlerFunc
InternalAuthFunc is a simpler version that returns a http.HandlerFunc wrapper. Use this for registering with mux.HandleFunc.
func RateLimit ¶
func RateLimit(config RateLimitConfig) func(http.Handler) http.Handler
RateLimit creates a rate limiting middleware with the given configuration
func RequireAnyPermission ¶
RequireAnyPermission creates a middleware that checks if the user has ANY of the required permissions.
func RequireAnyRole ¶
RequireAnyRole creates a middleware that checks if the user has ANY of the required roles.
func RequirePermission ¶
RequirePermission creates a middleware that checks if the user has the required permission.
Types ¶
type AuthConfig ¶
type AuthConfig struct {
JWTSecret string
// Optional: Skip auth for certain paths
SkipPaths []string
}
AuthConfig holds configuration for auth middleware.
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins []string // List of allowed origins, or ["*"] for all
AllowedMethods []string // HTTP methods (GET, POST, etc.)
AllowedHeaders []string // HTTP headers
ExposedHeaders []string // Headers exposed to client
AllowCredentials bool // Allow credentials
MaxAge int // Preflight cache duration in seconds
}
CORSConfig holds CORS configuration.
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns a restrictive CORS configuration. For production, explicitly configure AllowedOrigins via environment variables.
type CSRFConfig ¶
type CSRFConfig struct {
// SkipPaths are paths that don't require CSRF validation (e.g., login, register).
SkipPaths []string
// CookiePath is the path for the CSRF cookie. Default is "/".
CookiePath string
// CookieSecure sets the Secure flag on the cookie. Should be true in production.
CookieSecure bool
// CookieSameSite sets the SameSite attribute. Default is SameSiteLaxMode.
CookieSameSite http.SameSite
}
CSRFConfig holds configuration for CSRF middleware.
func DefaultCSRFConfig ¶
func DefaultCSRFConfig() CSRFConfig
DefaultCSRFConfig returns a default CSRF configuration.
type ContextKey ¶
type ContextKey string
ContextKey is a custom type for context keys to avoid collisions.
const ( // UserIDKey is the context key for user ID. UserIDKey ContextKey = "user_id" // UserEmailKey is the context key for user email. UserEmailKey ContextKey = "user_email" // UserStatusKey is the context key for user status. UserStatusKey ContextKey = "user_status" // UserRolesKey is the context key for user roles. UserRolesKey ContextKey = "user_roles" // UserPermissionsKey is the context key for user permissions. UserPermissionsKey ContextKey = "user_permissions" // JWTTokenKey is the context key for the JWT token string (for service-to-service forwarding). JWTTokenKey ContextKey = "jwt_token" // AccountTypeKey is the context key for account type (user, user_admin). AccountTypeKey ContextKey = "account_type" )
type InternalAuthConfig ¶
type InternalAuthConfig struct {
// Secret is the shared secret for internal service communication.
// Should be set via INTERNAL_SERVICE_SECRET environment variable.
Secret string
// HeaderName is the header to check for the secret. Defaults to X-Internal-Secret.
HeaderName string
}
InternalAuthConfig holds configuration for internal service-to-service auth.
type JWTClaims ¶
type JWTClaims struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Status string `json:"status"`
AccountType string `json:"account_type,omitempty"`
Roles []string `json:"roles,omitempty"`
Permissions []string `json:"permissions,omitempty"`
jwt.RegisteredClaims
}
JWTClaims represents the JWT token claims structure.
type Middleware ¶
Middleware is a function that wraps an http.Handler.
func CORS ¶
func CORS(config CORSConfig) Middleware
CORS returns a middleware that handles CORS requests.
func CSRF ¶
func CSRF(config CSRFConfig) Middleware
CSRF creates a middleware that implements CSRF protection using double-submit cookie pattern.
How it works: 1. On any request, if no CSRF cookie exists, generate one and set it 2. On mutating requests (POST, PUT, DELETE, PATCH), validate that X-CSRF-Token header matches cookie 3. Frontend reads the csrf_token cookie and sends it in X-CSRF-Token header
This is a stateless approach that doesn't require server-side session storage.
func Logging ¶
func Logging(log *logger.Logger) Middleware
Logging returns a middleware that logs HTTP requests and responses.
func Recovery ¶
func Recovery(log *logger.Logger) Middleware
Recovery returns a middleware that recovers from panics and logs them.
func RecoveryWithHandler ¶
func RecoveryWithHandler(log *logger.Logger, handler func(http.ResponseWriter, *http.Request, interface{})) Middleware
RecoveryWithHandler returns a middleware that recovers from panics and calls a custom handler.
func RequestID ¶
func RequestID() Middleware
RequestID returns a middleware that generates or extracts request IDs.
func Timeout ¶
func Timeout(duration time.Duration) Middleware
Timeout returns a middleware that sets a timeout for requests.
type RateLimitConfig ¶
type RateLimitConfig struct {
// RequestsPerMinute is the maximum number of requests allowed per minute
RequestsPerMinute int
// BurstSize is the maximum burst of requests allowed
BurstSize int
// CleanupInterval is how often to clean up expired entries (default: 10 minutes)
CleanupInterval time.Duration
// TrustProxyHeaders enables trusting X-Forwarded-For and X-Real-IP headers.
// SECURITY: Only enable this when behind a trusted reverse proxy (nginx, traefik, etc.)
// that properly sets these headers. Leaving this false prevents IP spoofing attacks.
TrustProxyHeaders bool
}
RateLimitConfig holds configuration for rate limiting
func DefaultRateLimitConfig ¶
func DefaultRateLimitConfig() RateLimitConfig
DefaultRateLimitConfig returns a sensible default configuration Suitable for authentication endpoints (prevent brute force)
func StrictRateLimitConfig ¶
func StrictRateLimitConfig() RateLimitConfig
StrictRateLimitConfig returns a stricter configuration Suitable for sensitive operations (KYC verification, money transfers)
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
StatusCode int
BytesWritten int
// contains filtered or unexported fields
}
ResponseWriter wraps http.ResponseWriter to capture status code and size.
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter
NewResponseWriter creates a new ResponseWriter.
func (*ResponseWriter) Flush ¶
func (rw *ResponseWriter) Flush()
Flush implements http.Flusher to support streaming responses like SSE.
func (*ResponseWriter) Write ¶
func (rw *ResponseWriter) Write(b []byte) (int, error)
Write captures the number of bytes written.
func (*ResponseWriter) WriteHeader ¶
func (rw *ResponseWriter) WriteHeader(statusCode int)
WriteHeader captures the status code.