middleware

package
v0.33.1 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: Apache-2.0 Imports: 61 Imported by: 0

Documentation

Overview

Package middleware provides Fiber HTTP middlewares for auth, security, validation, rate limiting, and more.

Index

Constants

View Source
const (
	AlgorithmTokenBucket   = "token_bucket"
	AlgorithmSlidingWindow = "sliding_window"
)

Variables

View Source
var ErrInvalidKey = errors.New("invalid private key")

Functions

func AESEncrypt

func AESEncrypt(data, key []byte) ([]byte, error)

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

func BodyReader() fiber.Handler

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 BreakerStates() fiber.Handler

func BuildCSP added in v0.1.0

func BuildCSP(cfg CSPConfig) string

BuildCSP generates a Content-Security-Policy string from config.

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

func CacheResponse(cc cache.Cache, ttl time.Duration) fiber.Handler

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 ContentSecurity

func ContentSecurity(key *rsa.PublicKey, strict bool) fiber.Handler

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 Cryption

func Cryption(key []byte) fiber.Handler

func DefaultClaims added in v0.9.0

func DefaultClaims(sub, orgID string, roles, permissions []string, ttlSeconds int) map[string]any

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

func DestroySession(ctx context.Context, store *redis.Redis, id string) error

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 GetCorrelationID(c fiber.Ctx) string

func Gunzip

func Gunzip() fiber.Handler

func HeaderSanitize added in v0.1.0

func HeaderSanitize() fiber.Handler

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 JWT

func JWT(cfg JWTConfig) fiber.Handler

func JWTWithOry added in v0.10.0

func JWTWithOry(cfg JWTConfig, oClient *ory.Client) fiber.Handler

JWTWithOry validates JWT tokens using Ory Kratos's JWKS (RS256). Used in "ory" auth mode.

func JWTWithZitadel added in v0.3.0

func JWTWithZitadel(cfg JWTConfig, zClient *zitadel.Client) fiber.Handler

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 Logger

func Logger() fiber.Handler

func LoggerWithConfig added in v0.14.0

func LoggerWithConfig(cfg LoggerConfig) fiber.Handler

func MFARequired added in v0.10.0

func MFARequired() fiber.Handler

MFARequired returns middleware that requires mfa: true in JWT claims.

func MaxBytes

func MaxBytes(limit int) fiber.Handler

func MaxConns

func MaxConns(limit int) fiber.Handler

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

func Ory(cfg OryConfig) fiber.Handler

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 ParseObject(object string) (objType, objID string, err error)

func ParsePublicKey

func ParsePublicKey(pemStr string) (*rsa.PublicKey, error)

func ParseToken added in v0.16.0

func ParseToken(tokenStr, secret, algorithm string) (jwt.MapClaims, error)

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

func ParseTokenUnverified(tokenStr string) (jwt.MapClaims, error)

ParseTokenUnverified decodes a JWT without validating its signature. Use only for introspection flows where signature checking is done elsewhere.

func Prometheus

func Prometheus() fiber.Handler

func PrometheusHandler

func PrometheusHandler() fiber.Handler

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 RegisterValidation(name string, input any)

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 SSE

func SSE() 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 SignBody

func SignBody(key *rsa.PrivateKey, body []byte) (string, error)

func SignToken added in v0.9.0

func SignToken(secret string, algorithm string, claims map[string]any) (string, error)

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 Timeout

func Timeout(d time.Duration) fiber.Handler

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 ValidateInput(modelName string) fiber.Handler

func WebSocket

func WebSocket(handler func(*websocket.Conn)) fiber.Handler

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 BreakerConfig struct {
	// OnRejected is called when the circuit breaker rejects a request.
	// If nil, a default 503 response is returned.
	OnRejected func(fiber.Ctx) error
}

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 CSPLevel added in v0.1.0

type CSPLevel string

CSPLevel defines pre-built CSP policies.

const (
	CSPLevelBasic  CSPLevel = "basic"
	CSPLevelStrict CSPLevel = "strict"
)

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 DeprecationConfig struct {
	Status     string // "current", "deprecated", "removed"
	SunsetDate time.Time
	Message    string
}

type FallbackConfig added in v0.11.0

type FallbackConfig struct {
	// Mode is "degraded" or "stale". Empty means fallback is disabled.
	Mode string
	// Message is the response body for degraded mode.
	Message string
}

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 LoggerConfig struct {
	SkipPaths  []string
	SampleRate float64 // 0=log all, 0.5=log 50%, 1=log none
}

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 RateLimitEntry struct {
	RequestsPerSecond int           `json:"requests_per_second"`
	Burst             int           `json:"burst"`
	TTL               time.Duration `json:"ttl" config:",optional"`
}

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 RetryConfig struct {
	MaxRetries      int
	InitialInterval time.Duration
	MaxBackoff      time.Duration
	Multiplier      float64
}

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

func (*SafeHTTPClient) DoURL added in v0.3.3

func (c *SafeHTTPClient) DoURL(ctx context.Context, urlStr, method string, body io.Reader) (*http.Response, error)

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

type TraceConfig struct {
	Name     string
	Endpoint string
	Sampler  float64
	Batcher  string

	OtlpHeaders    map[string]string
	OtlpHttpPath   string
	OtlpHttpSecure bool

	TraceResponseHeader string
	CustomAttributes    func(fiber.Ctx) []attribute.KeyValue
	SkipPaths           []string
}

type WebSocketConfig

type WebSocketConfig struct {
	Origins          []string
	HandshakeTimeout time.Duration
	ReadBufferSize   int
	WriteBufferSize  int
}

Jump to

Keyboard shortcuts

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