ratelimit

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: GPL-2.0, GPL-3.0 Imports: 3 Imported by: 0

Documentation

Overview

Package ratelimit implements a dual sliding-window rate limiter for authentication attempts (per-IP and per-account). It is consumed by the server's auth handlers via the RateLimitChecker 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 the server layer. 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.

func (*RateLimiter) Record

func (rl *RateLimiter) Record(ip, username string)

Record records a failed authentication attempt in both the IP and account sliding windows.

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).

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the background prune goroutine.

Jump to

Keyboard shortcuts

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