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
- Variables
- func Auth(secretKey string) zen.HandlerFunc
- func AuthWithConfig(config AuthConfig) zen.HandlerFunc
- func CORSWithConfig(config CORSConfig) zen.HandlerFunc
- func DefaultCors() zen.HandlerFunc
- func GenerateToken(claims jwt.Claims, secretKey string) (string, error)
- func GetClaims[T jwt.Claims](c *zen.Context) (T, bool)
- func RateLimiterMiddleware(config ...RateLimitConfig) zen.HandlerFunc
- func Recovery() zen.HandlerFunc
- func SecurityMiddleware(config ...SecurityConfig) zen.HandlerFunc
- type AuthConfig
- type BaseClaims
- type CORSConfig
- type ContentSecurityPolicyDirective
- type RateLimitConfig
- type RateLimitStrategy
- type RateLimiter
- type SecStrategy
- type SecurityConfig
Constants ¶
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
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 ¶
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 ¶
GenerateToken generates a new JWT token with custom claims
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 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