middleware

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2024 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

The CORS (Cross-Origin Resource Sharing) middleware for Zen framework provides a flexible way to handle cross-origin requests with customizable configurations.

Index

Constants

View Source
const (
	AccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	AccessControlAllowMethods     = "Access-Control-Allow-Methods"
	AccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	AccessControlMaxAge           = "Access-Control-Max-Age"
	AccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	AccessControlRequestHeaders   = "Access-Control-Request-Headers"
	AccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	Vary                          = "Vary"
)

Cors header constants

View Source
const (
	SameOrigin              = "SAMEORIGIN"
	StrictOriginPolicy      = "strict-origin-when-cross-origin"
	HstsMaxAge              = 31536000 // one year in seconds
	StrictTransportSecurity = "Strict-Transport-Security"
	ContentSecurityPolicy   = "Content-Security-Policy"
	XContentTypeOptions     = "X-Content-Type-Options"
	XXSSProtection          = "X-XSS-Protection"
	XFrameOptions           = "X-Frame-Options"
	ReferrerPolicy          = "Referrer-Policy"
)

Variables

View Source
var (
	ErrMissingToken = errors.New("missing authorization token")
	ErrInvalidToken = errors.New("invalid authorization token")
)

custom errors

Functions

func Auth

func Auth(secretKey string) zen.HandlerFunc

Auth returns the Auth Middleware with default config

func AuthWithConfig

func AuthWithConfig(config AuthConfig) zen.HandlerFunc

AuthWithConfig returns the Auth middleware with custom config

func CORSWithConfig

func CORSWithConfig(config CORSConfig) zen.HandlerFunc

CORSWithConfig returns the CORS middleware with custom config

func DefaultCors

func DefaultCors() zen.HandlerFunc

DefaultCors returns the CORS middleware with default configs

func GenerateToken

func GenerateToken(claims jwt.Claims, secretKey string) (string, error)

GenerateToken generates a new JWT token with custom claims

func GetClaims

func GetClaims[T jwt.Claims](c *zen.Context) (T, bool)

GetClaims retrieves the JWT claims from the context with type assertion

func RateLimiterMiddleware

func RateLimiterMiddleware(config ...RateLimitConfig) zen.HandlerFunc

RateLimiterMiddleware creates a new rate limiting middleware

func Recovery

func Recovery() zen.HandlerFunc

Recovery middleware recovers from panics and sends a 500 error

func SecurityMiddleware

func SecurityMiddleware(config ...SecurityConfig) zen.HandlerFunc

SecurityMiddleware creates a new security middleware with the given configuration

Types

type AuthConfig

type AuthConfig struct {
	// secret key used for signing tokens
	SecretKey string

	// TokenLookup is a string in the form of "<source>:<name>" that is used
	// to extract token from the request
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "cookie:<name>"
	TokenLookup string

	// TokenHeaderName is a string in the header. Default value is "Bearer"
	TokenHeadName string

	// SkipPaths defines paths that should skip authentication
	SkipPaths []string

	// UnAuthorized defines function to handle unauthorized requests
	Unauthorized func(*zen.Context, error)

	// ClaimsFactory is a function that creates a new claims instance
	// This allows clients to use their own claims structure
	ClaimsFactory func() jwt.Claims
}

AuthConfig defines the config for Auth middleware

func DefaultAuthConfig

func DefaultAuthConfig() AuthConfig

DefaultAuthConfig returns the default auth configuration

type BaseClaims

type BaseClaims struct {
	UserID string `json:"user_id"`
	Role   string `json:"role"`
	jwt.RegisteredClaims
}

Claims defines the JWT claims

type CORSConfig

type CORSConfig struct {
	// AllowOrigins defines the origins that are allowed
	// Default is ["*"] which allow all origins
	AllowOrigins []string

	// AllowMethods defines the methods that are allowed.
	// Default is [GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS]
	AllowMethods []string

	// AllowHeaders defines the headers that can be used when making the actual request.
	// Default is [] which allows all headers that are requested.
	// Example: ["Content-Type", "Authorization"]
	AllowHeaders []string

	// AllowCredentials indicates whether the response to the request can be exposed
	// when the credentials flag is true.
	// Default is false.
	// WARNING: Setting this to true can lead to security vulnerabilities if AllowOrigins is ["*"].
	AllowCredentials bool

	// ExposeHeaders defines the headers that are safe to expose to the API of a
	// CORS API specification.
	// Default is [].
	// Example: ["Content-Length", "X-Custom-Header"]
	ExposeHeaders []string

	// MaxAge indicates how long the results of a preflight request can be cached
	// Default is 0 which means no caching.
	// Example: 3600 (1 hour)
	MaxAge int
}

CORSConfig defines the config for CORS middleware It allows fine-grained control over Cross-Origin Resource Sharing behavior.

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns the default CORS configuration

type ContentSecurityPolicyDirective

type ContentSecurityPolicyDirective struct {
	DefaultSrc []string
	ScriptSrc  []string
	StyleSrc   []string
	ImgSrc     []string
	ConnectSrc []string
	FontSrc    []string
	ObjectSrc  []string
	MediaSrc   []string
	FrameSrc   []string
	ReportURI  string
}

ContentSecurityPolicyDirective represents CSP directives

type RateLimitConfig

type RateLimitConfig struct {
	Limit           int                               // Maximum requests per window
	Window          time.Duration                     // Window duration
	BurstLimit      int                               // Temporary burst allowance above the limit
	CustomKeyFunc   func(*zen.Context) string         // function to generate key for rate limiting
	ExcludePaths    []string                          // paths to exclude from rate limiting
	StatusCode      int                               // HTTP status code for rate limit exceeded
	CustomErrorFunc func(*zen.Context, time.Duration) // Custom error handling
	Strategy        RateLimitStrategy                 // rate limiting strategy to use
}

RateLimitConfig holds configuration for the RateLimiter middleware

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() RateLimitConfig

DefaultRateLimiterConfig returns the default configs for RateLimiter which for now, we are going to stick to IP-based

type RateLimitStrategy

type RateLimitStrategy string

RateLimitStrategy defines the type of rate limiting to use

const (
	IPBased       RateLimitStrategy = "ip-based"
	SlidingWindow RateLimitStrategy = "sliding-window"
)

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter implements the ratelimiting logic

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter with the given configuration

type SecStrategy

type SecStrategy uint

SecurityStrategy defines the type of security measures to enable

const (
	HeaderSecurity SecStrategy = 1 << iota
	RequestSanitization
	IPSecurity
	SessionSecurity
)

security strategies - can be combined using bitwise OR

type SecurityConfig

type SecurityConfig struct {
	// Enabled strategies
	Strategies SecStrategy

	// Security headers configuration
	HSTS                  bool // HTTP Strict Transport Security
	HSTSMaxAge            int  // Max age for HSTS in seconds
	HSTSIncludeSubdomains bool // Include subdomains in HSTS
	HSTSPreload           bool // Include in HSTS preload list

	CSPDirectives      *ContentSecurityPolicyDirective
	FrameOptions       string // DENY, SAMEORIGIN, or ALLOW-FROM uri
	ContentTypeOptions bool   // X-Content-Type-Options: nosniff
	XSSProtection      bool   // X-XSS-Protection
	ReferrerPolicy     string // Referrer-Policy header value

	// Request Sanitization Configurations
	MaxRequestSize    int64    // maximum request size in bytes
	AllowedFileTypes  []string // Allowed file extensions for uploads
	SanitizeHTML      bool     // Whether to sanitize HTML in request bodies
	SQLInjectionCheck bool     // SQL injection attacks
	XSSCheck          bool     // Check for XSS attempts

	// IP Security Configuration
	AllowedIPs        []string // Allowed IP addresses/ranges
	BlockedIPs        []string // Blocked IP addresses/ranges
	EnableGeoBlocking bool     // Enable geographic blocking
	AllowedCountries  []string // Allowed country codes

	// Session Security Configuration
	SessionTimeout  int           // Session timeout in seconds
	RotateSessionID bool          // Whether to rotate session IDs
	SecureCookies   bool          // Whether to set Secure flag on cookies
	SameSiteCookies http.SameSite // SameSite cookie policy

	// Custom handlers
	CustomErrorHandler  func(*zen.Context, error)
	OnSecurityViolation func(*zen.Context, string) // Called when a security violation occurs
}

SecurityConfig holds the configuration for the Security middleware

func DefaultSecurityConfig

func DefaultSecurityConfig() SecurityConfig

DefaultSecurityConfig returns the default security configuration

Jump to

Keyboard shortcuts

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