Documentation
¶
Overview ¶
Package middleware provides Fiber HTTP middlewares for auth, security, validation, rate limiting, and more.
Index ¶
- Constants
- Variables
- func AESEncrypt(data, key []byte) ([]byte, error)
- func APIKey(cfg APIKeyConfig) fiber.Handler
- func BodyReader() fiber.Handler
- func Breaker(cfg ...BreakerConfig) fiber.Handler
- func BreakerStates() fiber.Handler
- func BuildCSP(cfg CSPConfig) string
- func CORS(cfg CORSConfig) fiber.Handler
- func CSRF(cfg CSRFConfig) fiber.Handler
- func CacheResponse(cc cache.Cache, ttl time.Duration) fiber.Handler
- func ContentSecurity(key *rsa.PublicKey, strict bool) fiber.Handler
- func Correlation(cfg CorrelationConfig) fiber.Handler
- func Cryption(key []byte) fiber.Handler
- func DefaultClaims(sub, orgID string, roles, permissions []string, ttlSeconds int) map[string]any
- func Deprecation(cfg DeprecationConfig) fiber.Handler
- func Fallback(cfg FallbackConfig) fiber.Handler
- func GenerateNonce() string
- func GetCorrelationID(c fiber.Ctx) string
- func Gunzip() fiber.Handler
- func HeaderSanitize() fiber.Handler
- func JWT(cfg JWTConfig) fiber.Handler
- func JWTWithOry(cfg JWTConfig, oClient *ory.Client) fiber.Handler
- func JWTWithZitadel(cfg JWTConfig, zClient *zitadel.Client) fiber.Handler
- func Logger() fiber.Handler
- func LoggerWithConfig(cfg LoggerConfig) fiber.Handler
- func MFARequired() fiber.Handler
- func MaxBytes(limit int) fiber.Handler
- func MaxConns(limit int) fiber.Handler
- func OpenFGA(cfg OpenFGAConfig) fiber.Handler
- func Ory(cfg OryConfig) fiber.Handler
- func ParseObject(object string) (objType, objID string, err error)
- func ParsePublicKey(pemStr string) (*rsa.PublicKey, error)
- func Prometheus() fiber.Handler
- func PrometheusHandler() fiber.Handler
- func RateLimit(cfg RateLimitConfig) fiber.Handler
- func RateLimitPost(cfg RateLimitPostConfig) fiber.Handler
- func RegisterValidation(name string, input any)
- func ResetMetrics()
- func Retry(cfg RetryConfig) fiber.Handler
- func SSE() fiber.Handler
- func SecurityHeaders(cfg SecurityHeadersConfig) fiber.Handler
- func Shedding(cfg ...SheddingConfig) fiber.Handler
- func SignBody(key *rsa.PrivateKey, body []byte) (string, error)
- func SignToken(secret string, algorithm string, claims map[string]any) (string, error)
- func Timeout(d time.Duration) fiber.Handler
- func TokenRefreshHandler(cfg TokenRefreshConfig) fiber.Handler
- func Trace(cfg TraceConfig) fiber.Handler
- func ValidateInput(modelName string) fiber.Handler
- func WebSocket(handler func(*websocket.Conn)) fiber.Handler
- func WebSocketWithConfig(cfg WebSocketConfig, handler func(*websocket.Conn)) fiber.Handler
- type APIKeyConfig
- type AuthContext
- type BreakerConfig
- type CORSConfig
- type CSPConfig
- type CSPLevel
- type CSRFConfig
- type CorrelationConfig
- type DeprecationConfig
- type FallbackConfig
- type JWTConfig
- type LoggerConfig
- type OpenFGAConfig
- type OryConfig
- type RateLimitConfig
- type RateLimitEntry
- type RateLimitPostConfig
- type RetryConfig
- type SSRFConfig
- type SafeHTTPClient
- type SecurityHeadersConfig
- type SheddingConfig
- type TokenRefreshConfig
- type TraceConfig
- type WebSocketConfig
Constants ¶
const ( AlgorithmTokenBucket = "token_bucket" AlgorithmSlidingWindow = "sliding_window" )
Variables ¶
var ErrInvalidKey = errors.New("invalid private key")
Functions ¶
func AESEncrypt ¶
func APIKey ¶ added in v0.3.0
func APIKey(cfg APIKeyConfig) fiber.Handler
APIKey creates a middleware that validates API keys against OpenFGA. The API key is treated as a subject in OpenFGA (apikey:<key_id>).
func BodyReader ¶ added in v0.14.0
BodyReader reads the request body once and caches it in context locals. Downstream middlewares should call getRequestBody() instead of c.Body(). Must be registered before any middleware that reads the request body.
func Breaker ¶
func Breaker(cfg ...BreakerConfig) fiber.Handler
func BreakerStates ¶ added in v0.11.0
func CORS ¶
func CORS(cfg CORSConfig) fiber.Handler
func CSRF ¶ added in v0.1.0
func CSRF(cfg CSRFConfig) fiber.Handler
func CacheResponse ¶ added in v0.11.0
CacheResponse wraps a handler to cache its GET responses in KV. The cache key is method:path. On subsequent GETs, the cached response is returned. Use for read-only REST endpoints where data changes infrequently.
func Correlation ¶ added in v0.11.0
func Correlation(cfg CorrelationConfig) fiber.Handler
func DefaultClaims ¶ added in v0.9.0
DefaultClaims builds standard JWT claims for a user session.
func Deprecation ¶ added in v0.11.0
func Deprecation(cfg DeprecationConfig) fiber.Handler
func Fallback ¶ added in v0.11.0
func Fallback(cfg FallbackConfig) fiber.Handler
func GenerateNonce ¶ added in v0.1.0
func GenerateNonce() string
GenerateNonce creates a CSP nonce (base64 random 32 bytes).
func GetCorrelationID ¶ added in v0.11.0
func HeaderSanitize ¶ added in v0.1.0
func JWTWithOry ¶ added in v0.10.0
JWTWithOry validates JWT tokens using Ory Kratos's JWKS (RS256). Used in "ory" auth mode.
func JWTWithZitadel ¶ added in v0.3.0
JWTWithZitadel validates JWT tokens using Zitadel's JWKS (RS256). Used in "openfga-zitadel" auth mode.
func LoggerWithConfig ¶ added in v0.14.0
func LoggerWithConfig(cfg LoggerConfig) fiber.Handler
func MFARequired ¶ added in v0.10.0
MFARequired returns middleware that requires mfa: true in JWT claims.
func OpenFGA ¶ added in v0.3.0
func OpenFGA(cfg OpenFGAConfig) fiber.Handler
OpenFGA creates a middleware that checks authorization against OpenFGA. It requires AuthContext to be present (set by JWT middleware).
func Ory ¶ added in v0.3.0
Ory creates a middleware that checks authorization via Ory Keto. It requires AuthContext to be present (set by JWT middleware).
func ParseObject ¶ added in v0.3.0
func Prometheus ¶
func PrometheusHandler ¶
func RateLimit ¶ added in v0.1.0
func RateLimit(cfg RateLimitConfig) fiber.Handler
func RateLimitPost ¶ added in v0.9.0
func RateLimitPost(cfg RateLimitPostConfig) fiber.Handler
func RegisterValidation ¶ added in v0.1.0
func ResetMetrics ¶ added in v0.14.0
func ResetMetrics()
ResetMetrics clears all collected metrics. Used in tests.
func Retry ¶ added in v0.11.0
func Retry(cfg RetryConfig) fiber.Handler
func SecurityHeaders ¶ added in v0.1.0
func SecurityHeaders(cfg SecurityHeadersConfig) fiber.Handler
func Shedding ¶
func Shedding(cfg ...SheddingConfig) fiber.Handler
func SignToken ¶ added in v0.9.0
SignToken creates and signs a JWT using the given secret and algorithm. Supported algorithms: HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512. For RS* and ES*, secret must be a PEM-encoded private key.
func TokenRefreshHandler ¶ added in v0.3.0
func TokenRefreshHandler(cfg TokenRefreshConfig) fiber.Handler
TokenRefreshHandler returns a handler that delegates token refresh to the configured identity provider, or re-signs the JWT in manual mode.
func Trace ¶
func Trace(cfg TraceConfig) fiber.Handler
func ValidateInput ¶ added in v0.1.0
func WebSocketWithConfig ¶
func WebSocketWithConfig(cfg WebSocketConfig, handler func(*websocket.Conn)) fiber.Handler
Types ¶
type APIKeyConfig ¶ added in v0.3.0
type APIKeyConfig struct {
// Prefix identifies API keys (e.g., "sk-"). Empty means no prefix check.
Prefix string
// Client is the OpenFGA checker for authorization checks.
Client openfga.Checker
// Relation is the required relation (e.g., "can_access", "can_write").
Relation string
// Object is the resource object (e.g., "webhook:stripe").
Object string
// Header is the header to look for the API key (default: "Authorization").
Header string
// AuthResolver resolves an API key into an AuthContext for role-based auth.
// When nil and no FGA client, only presence + prefix are validated.
AuthResolver func(ctx context.Context, key string) (*AuthContext, error)
}
APIKeyConfig configures API key authentication for an entry.
type AuthContext ¶ added in v0.3.0
type AuthContext struct {
UserID string
OrgID string
Roles []string
Permissions []string
RawToken string
Claims jwt.MapClaims
}
func AuthFromContext ¶ added in v0.3.0
func AuthFromContext(ctx context.Context) *AuthContext
func GetAuth ¶ added in v0.3.0
func GetAuth(c fiber.Ctx) *AuthContext
type BreakerConfig ¶ added in v0.11.0
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins string
AllowedMethods string
AllowedHeaders string
AllowCredentials bool
MaxAge int
}
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
type CSPConfig ¶ added in v0.1.0
type CSPConfig struct {
Level CSPLevel `json:"level" config:",default=basic"`
DefaultSrc []string `json:"default_src" config:",optional"`
ScriptSrc []string `json:"script_src" config:",optional"`
StyleSrc []string `json:"style_src" config:",optional"`
ImgSrc []string `json:"img_src" config:",optional"`
ConnectSrc []string `json:"connect_src" config:",optional"`
FontSrc []string `json:"font_src" config:",optional"`
FrameSrc []string `json:"frame_src" config:",optional"`
FrameAncestors []string `json:"frame_ancestors" config:",optional"`
ObjectSrc []string `json:"object_src" config:",optional"`
BaseURI []string `json:"base_uri" config:",optional"`
FormAction []string `json:"form_action" config:",optional"`
UpgradeInsecureReq bool `json:"upgrade_insecure_requests" config:",optional"`
}
CSPConfig configures Content-Security-Policy generation.
type CSRFConfig ¶ added in v0.1.0
type CSRFConfig struct {
Enabled bool `json:"enabled" config:",optional"`
CookieName string `json:"cookie_name" config:",optional"`
HeaderName string `json:"header_name" config:",optional"`
SameSite string `json:"same_site" config:",optional"`
Secure bool `json:"secure" config:",optional"`
ExcludePaths []string `json:"exclude_paths" config:",optional"`
JSONCheck bool `json:"json_check" config:",optional"`
}
type CorrelationConfig ¶ added in v0.11.0
type CorrelationConfig struct {
RequestHeader string
ResponseHeader string
ContextKey string
SkipPaths []string
}
func DefaultCorrelationConfig ¶ added in v0.11.0
func DefaultCorrelationConfig() CorrelationConfig
type DeprecationConfig ¶ added in v0.11.0
type FallbackConfig ¶ added in v0.11.0
type JWTConfig ¶
type JWTConfig struct {
Secret string
PrevSecret string
ContextKey string
TokenLookup string
Algorithm string
Issuer string
Audience string
TokenBlacklist func(rawToken string) bool
}
func DefaultJWTConfig ¶
func DefaultJWTConfig() JWTConfig
type LoggerConfig ¶ added in v0.14.0
type OpenFGAConfig ¶ added in v0.3.0
type OpenFGAConfig struct {
Client openfga.Checker // interface (supports caching)
Relation string // e.g., "can_read", "can_write", "can_delete"
Object string // e.g., "product:123", "order:456"
Roles []string // YAML-defined roles to check
Permissions []string // YAML-defined permissions to check
}
OpenFGAConfig defines the configuration for OpenFGA authorization middleware.
type OryConfig ¶ added in v0.3.0
type OryConfig struct {
Client *ory.Client
Roles []string // YAML-defined roles to check
Permissions []string // YAML-defined permissions to check
}
OryConfig defines the configuration for Ory authorization middleware.
type RateLimitConfig ¶ added in v0.1.0
type RateLimitConfig struct {
Enabled bool `json:"enabled" config:",optional"`
Global *RateLimitEntry `json:"global" config:",optional"`
PerIP *RateLimitEntry `json:"per_ip" config:",optional"`
Algorithm string `json:"algorithm" config:",default=sliding_window"`
TTL time.Duration `json:"ttl" config:",optional"`
SkipFailedRequests bool `json:"skip_failed_requests" config:",optional"`
SkipSuccessfulRequests bool `json:"skip_successful_requests" config:",optional"`
MaxFunc func(c fiber.Ctx) int `json:"-" config:"-"`
RedisConn *redis.Redis `json:"-" config:"-"`
}
type RateLimitEntry ¶ added in v0.1.0
type RateLimitPostConfig ¶ added in v0.9.0
type RateLimitPostConfig struct {
ServerPerUser *RateLimitEntry
ServerPerKey *RateLimitEntry
EntryPerUser *RateLimitEntry
EntryPerKey *RateLimitEntry
PerRoleLimits map[string]*RateLimitEntry
MaxFunc func(c fiber.Ctx) int
Algorithm string
TTL time.Duration
RedisConn *redis.Redis
}
type RetryConfig ¶ added in v0.11.0
type SSRFConfig ¶ added in v0.1.0
type SSRFConfig struct {
Enabled bool `json:"enabled"`
BlockPrivate bool `json:"block_private" config:",optional"`
BlockLoopback bool `json:"block_loopback" config:",optional"`
BlockMetadata bool `json:"block_metadata" config:",optional"`
AllowedHosts []string `json:"allowed_hosts" config:",optional"`
AllowAll bool `json:"allow_all" config:",optional"`
}
type SafeHTTPClient ¶ added in v0.1.0
type SafeHTTPClient struct {
// contains filtered or unexported fields
}
func NewSafeHTTPClient ¶ added in v0.1.0
func NewSafeHTTPClient(cfg SSRFConfig) *SafeHTTPClient
type SecurityHeadersConfig ¶ added in v0.1.0
type SecurityHeadersConfig struct {
FrameOptions string `json:"frame_options" config:",optional"`
ReferrerPolicy string `json:"referrer_policy" config:",optional"`
PermissionsPolicy string `json:"permissions_policy" config:",optional"`
HSTS bool `json:"hsts" config:",optional"`
HSTSMaxAge int `json:"hsts_max_age" config:",optional"`
HSTSIncludeSubs bool `json:"hsts_include_subdomains" config:",optional"`
CSP string `json:"csp" config:",optional"`
COOP string `json:"coop" config:",optional"`
COEP string `json:"coep" config:",optional"`
CORP string `json:"corp" config:",optional"`
CacheControl string `json:"cache_control" config:",optional"`
CSPReportPath string `json:"csp_report_path" config:",optional"`
}
type SheddingConfig ¶ added in v0.11.0
type SheddingConfig struct {
// Allow is a function that returns nil if the request is allowed.
// If it returns an error, the request is rejected with 503.
// If nil, the default adaptive CPU-based shedder is used.
Allow func() error
}
type TokenRefreshConfig ¶ added in v0.3.0
type TokenRefreshConfig struct {
// RefreshTokenTTL is how long the refresh token is valid (manual mode).
RefreshTokenTTL time.Duration
// JWTSecret used to sign new tokens (manual mode).
JWTSecret string
// ZitadelTokenURL is the Zitadel token endpoint URL (openfga-zitadel mode).
ZitadelTokenURL string
// ZitadelClientID is the Zitadel OAuth2 client ID.
ZitadelClientID string
// KratosRefreshURL is the Kratos session refresh URL (ory mode).
KratosRefreshURL string
}
TokenRefreshConfig configures the token refresh endpoint behavior.
type TraceConfig ¶
Source Files
¶
- apikey.go
- auth_context.go
- body.go
- breaker.go
- content_security.go
- correlation.go
- cors.go
- cryption.go
- csp.go
- csrf.go
- deprecation.go
- fallback.go
- gunzip.go
- header_sanitize.go
- jwt.go
- jwt_zitadel.go
- limiter_sliding.go
- logger.go
- logger_config.go
- maxbytes.go
- maxconns.go
- mfa.go
- openfga.go
- ory.go
- ory_jwt.go
- pools.go
- prometheus.go
- rate_limit.go
- response_cache.go
- retry.go
- security_headers.go
- shedding.go
- sse.go
- ssrf.go
- timeout.go
- tokenrefresh.go
- trace.go
- validate.go
- websocket.go