Documentation
¶
Overview ¶
Package ratelimit implements a dual sliding-window rate limiter for authentication attempts (per-IP and per-account). Callers (typically an HTTP server's auth handlers) consume it via the Checker interface.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Checker ¶
type Checker interface {
Allow(ip, username string) (allowed bool, retryAfter time.Duration)
Record(ip, username string)
Reset(ip, username string)
}
Checker is the narrow interface consumed by callers (e.g. HTTP auth handlers). It decouples request handling from the concrete sliding-window implementation.
type Config ¶
type Config struct {
IPLimit int
IPWindow time.Duration
AcctLimit int
AcctWindow time.Duration
PruneInterval time.Duration
MaxEntries int
}
Config groups all rate-limit tuning parameters into a single inspectable value. Use DefaultConfig() for production defaults.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the production rate-limit configuration:
- Per-IP: 10 attempts / 15 minutes
- Per-account: 100 attempts / 1 hour
- Max tracked entries: 10000
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter tracks failed authentication attempts per IP and per account using dual sliding windows (OWASP ASVS 2.2.1).
func NewRateLimiter ¶
func NewRateLimiter(ctx context.Context, cfg Config) *RateLimiter
NewRateLimiter creates a rate limiter with the given configuration. A background goroutine prunes stale entries at cfg.PruneInterval. The goroutine stops when ctx is cancelled. Call Stop for explicit shutdown.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(ip, username string) (allowed bool, retryAfter time.Duration)
Allow checks both IP and account windows. Both must be within limits for the request to proceed. Returns false with a retry-after duration if either limit is exceeded. An empty ip or username skips that dimension (a missing key carries no per-client signal and would otherwise lump unrelated callers into one shared bucket); callers should supply a real per-client IP so the IP dimension applies.
func (*RateLimiter) Record ¶
func (rl *RateLimiter) Record(ip, username string)
Record records a failed authentication attempt in the IP and account sliding windows. An empty ip or username skips that dimension, mirroring Allow and Reset.
func (*RateLimiter) Reset ¶
func (rl *RateLimiter) Reset(ip, username string)
Reset clears the sliding window entries for the given IP and username. Call after a successful authentication to prevent permanent soft-lockout (OWASP ASVS 2.2.1).