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 Basic(cfg BasicConfig) 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 CreateSession(ctx context.Context, store *redis.Redis, ttl time.Duration, userID string, ...) (string, error)
- 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 DestroySession(ctx context.Context, store *redis.Redis, id string) error
- func Fallback(cfg FallbackConfig) fiber.Handler
- func GenerateNonce() string
- func GetCorrelationID(c fiber.Ctx) string
- func Gunzip() fiber.Handler
- func HeaderSanitize() fiber.Handler
- func Introspect(cfg OAuthConfig) 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 KratosSession(cfg KratosSessionConfig) 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 ParseToken(tokenStr, secret, algorithm string) (jwt.MapClaims, error)
- func ParseTokenUnverified(tokenStr string) (jwt.MapClaims, 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 Session(cfg SessionConfig) 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 BasicConfig
- type BasicValidator
- type BreakerConfig
- type CORSConfig
- type CSPConfig
- type CSPLevel
- type CSRFConfig
- type CorrelationConfig
- type DeprecationConfig
- type FallbackConfig
- type JWTConfig
- type KratosSessionConfig
- type LoggerConfig
- type OAuthConfig
- type OpenFGAConfig
- type OryConfig
- type RateLimitConfig
- type RateLimitEntry
- type RateLimitPostConfig
- type RetryConfig
- type SSRFConfig
- type SafeHTTPClient
- type SecurityHeadersConfig
- type SessionConfig
- 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 Basic ¶ added in v0.27.0
func Basic(cfg BasicConfig) fiber.Handler
Basic validates an Authorization: Basic header via Validator and injects the resulting AuthContext for roles, per-user rate limiting and handlers.
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 CreateSession ¶ added in v0.27.0
func CreateSession(ctx context.Context, store *redis.Redis, ttl time.Duration, userID string, roles []string) (string, error)
CreateSession stores a new session and returns its ID. The caller sets the cookie (name from config) with the returned ID.
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 DestroySession ¶ added in v0.27.0
DestroySession revokes a session immediately (logout).
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 Introspect ¶ added in v0.27.0
func Introspect(cfg OAuthConfig) fiber.Handler
Introspect validates a Bearer access token against the configured introspection endpoint and injects the resulting AuthContext (sub → UserID, scope words → Roles). Inactive/revoked tokens get 401.
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 KratosSession ¶ added in v0.31.0
func KratosSession(cfg KratosSessionConfig) fiber.Handler
KratosSession validates an Ory Kratos session (Bearer token or cookie) via /sessions/whoami and injects an AuthContext. Roles are resolved downstream by the Keto authorization middleware; identity comes from Kratos.
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 ParseToken ¶ added in v0.16.0
ParseToken validates a JWT signature and returns its claims. secret must match the algorithm used to sign (HS*: raw secret, RS*/ES*: PEM public key).
func ParseTokenUnverified ¶ added in v0.16.0
ParseTokenUnverified decodes a JWT without validating its signature. Use only for introspection flows where signature checking is done elsewhere.
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 Session ¶ added in v0.27.0
func Session(cfg SessionConfig) fiber.Handler
Session validates the session cookie against the store and injects the resulting AuthContext for roles, per-user rate limiting and handlers. Missing/expired/unknown sessions get 401.
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 BasicConfig ¶ added in v0.27.0
type BasicConfig struct {
// Validator resolves credentials. Required.
Validator BasicValidator
// Realm is advertised in the WWW-Authenticate challenge.
Realm string
}
BasicConfig configures HTTP Basic authentication (RFC 7617).
type BasicValidator ¶ added in v0.27.0
type BasicValidator func(ctx context.Context, user, pass string) (*AuthContext, error)
BasicValidator resolves HTTP Basic credentials into an AuthContext. Return nil (no error) to reject with 403; return an error for 401.
type BreakerConfig ¶ added in v0.11.0
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins string
AllowedMethods string
AllowedHeaders string
AllowCredentials bool
MaxAge int
ExposeHeaders string
AllowPrivateNetwork bool
AllowOriginsFunc func(origin string) bool
Next func(fiber.Ctx) bool
}
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
// JWKSURL enables RS256/RS384/RS512 validation against a remote JWKS
// endpoint with kid-based key rotation (e.g. an OAuth server's
// /.well-known/jwks.json). When set, Secret is ignored for verification.
JWKSURL string
}
func DefaultJWTConfig ¶
func DefaultJWTConfig() JWTConfig
type KratosSessionConfig ¶ added in v0.31.0
type KratosSessionConfig struct {
// Client is the Ory client (Kratos + Keto).
Client *ory.Client
// ContextKey is the Locals key for the raw session (default "session").
ContextKey string
}
KratosSessionConfig configures Ory Kratos session validation.
type LoggerConfig ¶ added in v0.14.0
type OAuthConfig ¶ added in v0.27.0
type OAuthConfig struct {
// IntrospectionURL is the RFC 7662 endpoint (https recommended).
IntrospectionURL string
// ClientID/Secret authenticate this service at the endpoint.
ClientID string
ClientSecret string
// CacheTTL caches active verdicts in memory (keyed by token hash).
// Zero disables the cache. A cached token stays valid until TTL even
// if revoked upstream — keep it short (default 60s).
CacheTTL time.Duration
// HTTPClient overrides the default client (5s timeout).
HTTPClient *http.Client
}
OAuthConfig validates opaque Bearer tokens from a third-party OAuth provider via RFC 7662 token introspection. (For JWT-shaped tokens issued by an external OIDC provider, prefer jwt mode with `jwks_url` instead.)
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"`
// Next skips this middleware (returns control to next handler) when it
// returns true. Used to let a per-route csp_group override the global CSP.
Next func(fiber.Ctx) bool
}
type SessionConfig ¶ added in v0.27.0
type SessionConfig struct {
// Cookie is the session cookie name (default "sid").
Cookie string
// Store holds sessions as sess:<id> JSON with TTL expiry. Required:
// without shared storage, sessions break under prefork/clustering.
Store *redis.Redis
// TTL is the session lifetime from creation (no sliding refresh).
TTL time.Duration
}
SessionConfig validates a session cookie against a server-side store. Unlike JWT cookies (stateless), sessions can be revoked individually.
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
- basic.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
- kratos_session.go
- limiter_sliding.go
- logger.go
- logger_config.go
- maxbytes.go
- maxconns.go
- mfa.go
- oauth.go
- openfga.go
- ory.go
- ory_jwt.go
- pools.go
- prometheus.go
- rate_limit.go
- response_cache.go
- retry.go
- security_headers.go
- session.go
- shedding.go
- sse.go
- ssrf.go
- timeout.go
- tokenrefresh.go
- trace.go
- validate.go
- websocket.go