Documentation
¶
Overview ¶
Package ratelimit admits authentication attempts against sliding windows of failures per IP key, per account and per trusted device, and counts requests on anonymous begin routes per IP key. What it guarantees is a bound on failed attempts, and on begin-route requests, per window, per key, under the key rules of IPKey and AccountKey, for the Config.MaxEntries keys each dimension used most recently; its windows live in memory and reset on restart.
Devices follow OWASP's device-cookie protocol (https://owasp.org/www-community/Slow_Down_Online_Guessing_Attacks_with_Device_Cookies): a browser that signed in to an account carries a sealed cookie naming it, and its failures count against its own bucket, so locking the account for untrusted clients leaves that browser working.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrRefused is matched by every *RefusedError. ErrRefused = errors.New("ratelimit: too many attempts") // ErrConfigInvalid is matched by every *ConfigError. ErrConfigInvalid = errors.New("ratelimit: invalid config") )
Functions ¶
This section is empty.
Types ¶
type Account ¶
type Account struct {
// contains filtered or unexported fields
}
Account is the account dimension's key. Build it with AccountKey; the zero value means no account, an IP-only Attempt.
func AccountKey ¶
AccountKey returns username's key: its access.NormalizeUsername form, so every spelling of one account shares one key. A refused input keys as its raw bytes capped at 256, apart from every canonical name, so a refusal never escapes the account dimension. Every key has the same fixed size, however long the username.
type Attempt ¶
type Attempt struct {
IP IP
// Device is the device cookie as presented; zero when absent.
Device access.Secret
// Account is zero for an IP-only attempt (setup and token consumption).
Account Account
// OmitIP leaves the IP dimension out: IP is neither checked nor charged.
// It is for a caller already holding a full session for Account (a
// step-up, a current-password check), and needs an Account. A zero IP
// without OmitIP is still the shared "unknown" key.
OmitIP bool
}
Attempt is one authentication attempt to admit.
type Config ¶
type Config struct {
// Devices seals and opens device cookies. Required: the device protocol
// has no off state. Pass a persisted ring so trusted devices survive a
// restart; with access.NewEphemeralSealer() a restart makes every browser
// untrusted until a sign-in by another method reissues its cookie.
Devices *access.Sealer
// Logger receives the eviction warnings; nil uses slog.Default().
Logger *slog.Logger
// IP bounds failed attempts per IP key.
IP Rate
// Account bounds failures from untrusted clients per account.
Account Rate
// Device bounds failures per account and device cookie.
Device Rate
// Request bounds every request on an anonymous begin route per IP key.
Request Rate
// IPv6Prefix is the IPv6 prefix length one IP key covers, 48 to 128.
IPv6Prefix int
// MaxEntries bounds the keys each dimension tracks, and so its memory.
// A key's limit is exact while it is among its dimension's MaxEntries
// most recently used keys. A new key past that is never refused for
// capacity: it evicts the least recently used key whatever its count,
// and that key starts over. This limiter bounds no spray across more
// keys; docs/configuration.md names what does on each route.
MaxEntries int
// Prune is how often windows whose failures have all expired are
// dropped, and how often each dimension that evicted keys at their
// limit logs one warning with their count.
Prune time.Duration
}
Config configures a Limiter. Start from DefaultConfig and set Devices.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default rates and bounds: 10 per 15m per IP, 100 per hour per account, 10 per hour per device, 60 requests per minute per IP, an IPv6 /64 (RFC 6177), 10000 keys per dimension and a 5m prune. Devices is left nil for the caller to set.
type ConfigError ¶
type ConfigError struct{ Field string }
ConfigError names the Config field New refused, such as "IP.Limit".
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
func (*ConfigError) Is ¶
func (*ConfigError) Is(target error) bool
Is reports whether target is ErrConfigInvalid.
type IP ¶
type IP struct {
// contains filtered or unexported fields
}
IP is the IP dimension's key. Build it with IPKey; the zero value is the shared "unknown" key, the one IPKey returns for the zero netip.Addr.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter admits attempts and requests. Build one with New; it is safe for concurrent use.
func New ¶
New returns a Limiter whose prune goroutine runs until ctx ends or Shutdown. It refuses non-positive limits and windows, an IPv6Prefix outside 48 to 128, a non-positive MaxEntries or Prune, and a nil Devices, each with *ConfigError naming the field.
func (*Limiter) Attempt ¶
func (l *Limiter) Attempt(a Attempt) (*Reservation, error)
Attempt reserves one failure slot in every applicable dimension under the lock and refuses with *RefusedError when any is full: the IP dimension unless OmitIP, then the device bucket for a valid device cookie of the attempt's account, else the account's untrusted bucket. An OmitIP attempt with no Account is an error that is not a *RefusedError. A reservation is a recorded failure until Succeed or Cancel, so an abandoned one never leaks a free attempt.
func (*Limiter) DeviceCookie ¶
DeviceCookie returns a fresh device cookie for acct after a successful sign-in that ran no Attempt (passkey, OIDC). It keeps the device ID of a presented cookie that is valid for acct, so a device stays one device, and returns the zero Secret for the zero Account.
func (*Limiter) Request ¶
Request counts one call on an anonymous begin route, refusing with *RefusedError when ip's request window is full. A refused call is not counted.
func (*Limiter) Shutdown ¶
Shutdown stops the prune goroutine and blocks until it has exited or ctx ends, returning nil in the first case and ctx.Err() in the second. Exit is checked before ctx, so once the goroutine is gone Shutdown returns nil even for an expired ctx. It is safe to call more than once.
type RefusedError ¶
RefusedError is a refused Attempt or Request. Dimension is "ip", "account", "device" or "request", whichever waits longest, and RetryAfter is exactly how long until that key's oldest live entry ages out.
func (*RefusedError) Error ¶
func (e *RefusedError) Error() string
func (*RefusedError) Is ¶
func (*RefusedError) Is(target error) bool
Is reports whether target is ErrRefused.
type Reservation ¶
type Reservation struct {
// contains filtered or unexported fields
}
Reservation is an admitted Attempt. Only the first of Succeed, Fail and Cancel acts; every later call does nothing.
func (*Reservation) Cancel ¶
func (r *Reservation) Cancel()
Cancel removes this reservation's entries without crediting a success. It is for a server-side refusal before anything was counted or verified (a hash permit refused).
func (*Reservation) Fail ¶
func (r *Reservation) Fail()
Fail settles the reservation as the failure it already counts.
func (*Reservation) Succeed ¶
func (r *Reservation) Succeed() (deviceCookie access.Secret)
Succeed removes this reservation's own entries, clears the succeeding account's bucket for this client (the device bucket for a valid device cookie, else the untrusted bucket), and returns a fresh device cookie, which keeps a trusted attempt's device ID. It never touches other accounts' failures in the IP window. It returns the zero Secret for an IP-only attempt and once the reservation is settled.
func (*Reservation) Trusted ¶
func (r *Reservation) Trusted() bool
Trusted reports whether the attempt carried a valid device cookie for its account.