Documentation
¶
Index ¶
- Constants
- Variables
- func BasicAuth(cfg *BasicAuthConfig) httpserver.Middleware
- func CORS(cfg *CORSConfig) httpserver.Middleware
- func Logger(logger log.Logger) httpserver.Middleware
- func RateLimit(ctx context.Context, cfg *RateLimitConfig) httpserver.Middleware
- func ValidatePasswords(expected, actual string) bool
- type Authenticator
- type BasicAuthConfig
- type CORSConfig
- type LeakyBucket
- type RateLimitConfig
Constants ¶
const ( DefaultConcurrentRequestLimit = 100 DefaultRequestTimeout = 30 * time.Second DefaultBucketCapacity = 1000 DefaultLeakRate = 100 DefaultLeakInterval = time.Second )
Variables ¶
var ( ErrInvalidPrincipals = errors.New("basic-auth: principals cannot be nil") ErrInvalidTokens = errors.New("basic-auth: tokens cannot be nil") ErrInvalidAuthenticator = errors.New("basic-auth: authenticator cannot be nil") ErrMismatchPassword = errors.New("basic-auth: password mismatch") //nolint:gochecknoglobals // Maintain a set of predefined bcrypt prefixes that are used throughout the application. BcryptHashPrefixes = []string{"$2a$", "$2b$", "$2x$", "$2y$"} )
var ( ErrMissingAllowedOrigins = errors.New("CORS: allowed origins cannot be empty") ErrMissingAllowedMethods = errors.New("CORS: allowed methods cannot be empty") ErrInvalidMaxAge = errors.New("CORS: max age must be non-negative") )
var ( ErrInvalidConcurrentRequestLimit = errors.New( "rate-limit: concurrent request limit must be non-negative", ) ErrInvalidRequestTimeout = errors.New("rate-limit: request timeout must be positive") ErrInvalidBucketCapacity = errors.New( "rate-limit: bucket capacity must be positive", ) ErrInvalidLeakRate = errors.New( "rate-limit: leak rate must be positive", ) ErrInvalidLeakInterval = errors.New( "rate-limit: leak interval must be positive", ) )
Functions ¶
func BasicAuth ¶
func BasicAuth(cfg *BasicAuthConfig) httpserver.Middleware
func CORS ¶
func CORS(cfg *CORSConfig) httpserver.Middleware
CORS returns a middleware that enables Cross-Origin Resource Sharing (CORS).
func Logger ¶
func Logger(logger log.Logger) httpserver.Middleware
Logger provides an HTTP middleware that logs incoming requests using the specified logger.
func RateLimit ¶
func RateLimit(ctx context.Context, cfg *RateLimitConfig) httpserver.Middleware
RateLimit returns a middleware for rate limiting incoming requests based on the provided configuration. It uses a leaky bucket algorithm for burst control and concurrent slot limiting for simultaneous requests.
func ValidatePasswords ¶
ValidatePasswords compares an expected password with an actual password, supporting bcrypt and byte-to-byte comparison.
Types ¶
type Authenticator ¶
Authenticator is a function type that validates a username and password, returning true if authentication succeeds.
type BasicAuthConfig ¶
type BasicAuthConfig struct {
// Principals defines a mapping of usernames to their respective passwords for basic authentication.
Principals map[string]string `json:"principals" yaml:"principals"`
// Authenticator validates a username and password.
Authenticator Authenticator
// Tokens defines a list of pre-approved tokens for token-based authentication.
Tokens []string `json:"tokens" yaml:"tokens"`
// UseTokens indicates whether token-based authentication is enabled in addition to basic authentication.
UseTokens bool
}
BasicAuthConfig holds the configuration for BasicAuth middleware.
func (*BasicAuthConfig) SetDefaults ¶
func (c *BasicAuthConfig) SetDefaults()
func (*BasicAuthConfig) Validate ¶
func (c *BasicAuthConfig) Validate() error
type CORSConfig ¶
type CORSConfig struct {
// AllowedOrigins is a list of origins a cross-domain request can be executed from.
// If the special "*" value is present, all origins will be allowed.
// Default: ["*"]
AllowedOrigins []string `json:"allowedOrigins" yaml:"allowedOrigins"`
// AllowedMethods is a list of methods the client is allowed to use with cross-domain requests.
// Default: ["HEAD", "GET", "POST"]
AllowedMethods []string `json:"allowedMethods" yaml:"allowedMethods"`
// AllowedHeaders is a list of headers the client is allowed to use with cross-domain requests.
// Default: ["Accept", "Authorization", "Content-Type", "X-CSRF-Token"]
AllowedHeaders []string `json:"allowedHeaders" yaml:"allowedHeaders"`
// ExposedHeaders indicates which headers are safe to expose to the API of a CORS response.
// Default: []
ExposedHeaders []string `json:"exposedHeaders" yaml:"exposedHeaders"`
// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
// Default: 0 (no cache)
MaxAge int `json:"maxAge" yaml:"maxAge"`
// AllowCredentials indicates whether the request can include user credentials.
// Default: false
AllowCredentials bool `json:"allowCredentials" yaml:"allowCredentials"`
}
CORSConfig holds the configuration for CORS middleware.
func (*CORSConfig) SetDefaults ¶
func (c *CORSConfig) SetDefaults()
func (*CORSConfig) Validate ¶
func (c *CORSConfig) Validate() error
type LeakyBucket ¶
type LeakyBucket chan struct{}
LeakyBucket is a limited-capacity channel that implements a leaky bucket algorithm for rate-limiting operations.
func NewLeakyBucket ¶
func NewLeakyBucket(capacity int) LeakyBucket
func (LeakyBucket) Remove ¶
func (b LeakyBucket) Remove()
Remove removes a single element from the bucket if available, otherwise does nothing.
func (LeakyBucket) StartLeaking ¶
StartLeaking begins removing elements from the bucket at a steady rate defined by the interval and rate parameters.
func (LeakyBucket) TryAdd ¶
func (b LeakyBucket) TryAdd() bool
TryAdd attempts to add an element to the bucket. Returns true if successful, or false if the bucket is full.
func (LeakyBucket) TryAddWithTimeout ¶
func (b LeakyBucket) TryAddWithTimeout(timeout time.Duration) bool
TryAddWithTimeout attempts to add an element to the bucket within the specified timeout duration. Returns true if successful.
type RateLimitConfig ¶
type RateLimitConfig struct {
// ConcurrentRequestLimit defines the maximum number of requests that can be processed concurrently.
// If set to 0, there is no limit.
ConcurrentRequestLimit int `json:"concurrentRequestLimit" yaml:"concurrentRequestLimit"`
// RequestTimeout defines the maximum time a request can wait in the queue.
// If a request waits longer than this, it will be rejected with a timeout error.
RequestTimeout time.Duration `json:"requestTimeout" yaml:"requestTimeout"`
// BucketCapacity defines the maximum number of requests that can accumulate in the bucket.
// Once the bucket is full, additional requests are rejected immediately.
BucketCapacity int `json:"bucketCapacity" yaml:"bucketCapacity"`
// LeakRate defines how many request slots are freed per leak interval.
// This determines the sustained request rate: LeakRate / LeakInterval = requests/second.
LeakRate int `json:"leakRate" yaml:"leakRate"`
// LeakInterval defines how often request slots are freed from the bucket.
// Larger intervals with proportionally larger LeakRate reduce timer overhead.
LeakInterval time.Duration `json:"leakInterval" yaml:"leakInterval"`
}
RateLimitConfig holds the configuration for RateLimit middleware.
func (*RateLimitConfig) SetDefaults ¶
func (c *RateLimitConfig) SetDefaults()
func (*RateLimitConfig) Validate ¶
func (c *RateLimitConfig) Validate() error