Documentation
¶
Overview ¶
Package lockout provides the login account-lockout limiter and the admin-API rate limiter. It is a self-contained leaf (stdlib only, no Culvert coupling) extracted from the flat package main per ADR-0002.
Index ¶
- Constants
- func Msg(seconds int) string
- type APIRateLimiter
- type LockedEntry
- type LoginLimiter
- func (l *LoginLimiter) AttemptsLeft(ip, username string) int
- func (l *LoginLimiter) Check(ip, username string) (locked bool, secondsRemaining int)
- func (l *LoginLimiter) CheckPair(ip, username string) (locked bool, secondsRemaining int)
- func (l *LoginLimiter) Cleanup()
- func (l *LoginLimiter) ClearFailures(ip, username string)
- func (l *LoginLimiter) EntryCount() int
- func (l *LoginLimiter) RecordFailure(ip, username string) bool
- func (l *LoginLimiter) RecordPairFailure(ip, username string) bool
- func (l *LoginLimiter) RecordSuccess(ip, username string)
- func (l *LoginLimiter) ResetUser(username string)
- func (l *LoginLimiter) Snapshot() []LockedEntry
- func (l *LoginLimiter) SnapshotAndClear() func()
- type Reservation
Constants ¶
const ( // MaxAttempts is the number of failures from one IP against one username // that triggers a pair lock (tier 1). MaxAttempts = 5 // AccountMaxAttempts is the number of failures against one username // across ALL IPs that triggers the account-wide lock (tier 2). AccountMaxAttempts = 20 // Window is the span within which failures accumulate toward a lock. Window = 10 * time.Minute // Duration is how long a pair/account stays locked once tripped. Duration = 15 * time.Minute // TrustTTL is how long a successful login keeps its client IP exempt // from the tier-2 account lock for that username. TrustTTL = 30 * 24 * time.Hour )
const ( // Burst is the max API mutations allowed per window. Burst = 60 // RateWindow is the sliding window width for the API rate limiter. RateWindow = 1 * time.Minute )
const MaxUsernameKeyLen = 256
MaxUsernameKeyLen bounds the username portion of every limiter map key.
Both maps are keyed by data an UNAUTHENTICATED caller chooses: the login POST carries the username verbatim, and an entry survives at least Window (the janitor cannot remove it before then — see Cleanup). Cleanup therefore bounds the ENTRY COUNT over time but said nothing about the SIZE of a key, so a single caller sending oversized usernames retained (request rate x Window x username size) bytes of heap in a package whose own contract is to be bounded. The callers in package main clamp their input first; this bound is the structural half of the same guarantee, so no future caller can reintroduce the exposure by forgetting to.
256 bytes matches maxUsernameLen on the proxy-auth path (proxy_portal.go), which already answered this question for Proxy-Authorization. Note that a name past the bound CAN name a real account: `-user`/`auth.user` and `--reset-password` reach cfg.SetAuth/cfg.SetUIUser, and neither store bounds the name (only the API handlers cap at 64). The login endpoint therefore exempts a configured name from its own rejection, which means such a name reaches this limiter — so the clamp must stay INJECTIVE. See boundUsername.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type APIRateLimiter ¶
type APIRateLimiter struct {
// contains filtered or unexported fields
}
APIRateLimiter limits mutating admin API calls per client IP.
func NewAPIRateLimiter ¶
func NewAPIRateLimiter() *APIRateLimiter
NewAPIRateLimiter returns a ready-to-use APIRateLimiter.
func (*APIRateLimiter) Allow ¶
func (a *APIRateLimiter) Allow(ip string) bool
Allow returns true if the IP is within the rate limit for API mutations.
func (*APIRateLimiter) Cleanup ¶
func (a *APIRateLimiter) Cleanup()
Cleanup removes expired entries.
func (*APIRateLimiter) Refund ¶ added in v1.0.256
func (a *APIRateLimiter) Refund(r Reservation)
Refund returns one unit previously claimed by Reserve. The refund applies only to the window the unit was claimed in: once that window has expired or been replaced by a newer one (a new entry is allocated per window), the unit already expired with it and the refund is a no-op — otherwise an in-flight success crossing the boundary would mint extra capacity in the NEW window. The count never goes negative.
func (*APIRateLimiter) Reserve ¶ added in v1.0.256
func (a *APIRateLimiter) Reserve(ip string) (Reservation, bool)
Reserve ATOMICALLY claims one unit of ip's Burst allowance in the current window and reports whether it succeeded. Unlike Allow, a refusal records nothing, so a caller that charges only some outcomes (e.g. failures) can reserve BEFORE doing expensive or state-retaining work and Refund the unit once the outcome turns out not to be chargeable. A check-then-charge pair (probe, work, then Allow) is not a bound: a concurrent wave all passes the probe before any of it is charged.
type LockedEntry ¶ added in v1.0.63
type LockedEntry struct {
Tier string `json:"tier"`
Username string `json:"username"`
IP string `json:"ip,omitempty"`
SecondsRemaining int `json:"seconds_remaining"`
}
LockedEntry describes one currently-active lockout, for admin visibility. Tier is "account" (tier-2, blocks every IP for Username) or "pair" (tier-1, blocks only IP against Username). IP is empty for account-tier entries.
type LoginLimiter ¶
type LoginLimiter struct {
// contains filtered or unexported fields
}
LoginLimiter tracks failed login attempts per (client IP, username) pair (tier 1) and per username across IPs (tier 2), with a trusted-IP bypass on tier 2 for IPs that previously logged in successfully.
func NewLoginLimiter ¶
func NewLoginLimiter() *LoginLimiter
NewLoginLimiter returns a ready-to-use LoginLimiter.
func (*LoginLimiter) AttemptsLeft ¶
func (l *LoginLimiter) AttemptsLeft(ip, username string) int
AttemptsLeft returns how many more failures the (ip, username) pair is allowed before the tier-1 lock trips.
func (*LoginLimiter) Check ¶
func (l *LoginLimiter) Check(ip, username string) (locked bool, secondsRemaining int)
Check returns (locked bool, secondsRemaining int) for a login attempt by username from client ip. A locked attempt must not be verified further. The pair lock always applies; the account lock is bypassed for IPs with a live trust grant. Expired entries are lazily deleted.
func (*LoginLimiter) CheckPair ¶ added in v1.0.32
func (l *LoginLimiter) CheckPair(ip, username string) (locked bool, secondsRemaining int)
CheckPair reports the tier-1 (IP, username) pair lock ONLY, ignoring the account tier entirely. It is for callers that want pure per-IP rate limiting with no cross-IP aggregation — notably the pre-provisioning setup endpoint, where there is no account to protect yet and an account-wide counter would let a few IPs globally block bootstrap (lockout-as-DoS).
func (*LoginLimiter) Cleanup ¶ added in v1.0.22
func (l *LoginLimiter) Cleanup()
Cleanup removes entries that can no longer affect a decision, bounding the maps against an unbounded-memory DoS: the pair and account keys derive from the attacker-controlled username (and client IP) on the unauthenticated login POST, so without a sweep each failed attempt could leak a permanent entry. An entry is removable when its lock has expired (a future Check would delete it anyway) or when it is unlocked and its failure window has elapsed (a future RecordFailure would reset it to a fresh window). Trusted grants past TrustTTL are dropped too (they no longer bypass anything). Called periodically by the shared cleanup janitor. Removing a stale entry is behaviorally identical to the lazy reset the hot paths already perform, so it changes no decision.
func (*LoginLimiter) ClearFailures ¶ added in v1.0.404
func (l *LoginLimiter) ClearFailures(ip, username string)
ClearFailures clears the (ip, username) pair's tier-1 failure history and NOTHING ELSE. It mints no trust grant.
It exists because RecordSuccess is the wrong primitive for a caller that has not actually verified a credential, and the pre-setup bootstrap branch of the admin login handler was exactly that caller (CHAOS-112 rider). A trust grant is a tier-2 BYPASS: it is checked by accountLockSecondsLocked and suppresses the account-wide lock for that IP for TrustTTL (30 days), which is the only backstop against distributed, IP-rotating brute force. The grant's contract — stated at the top of this file — is that it is earned by "a SUCCESSFUL login", and a caller that forced its own authorization decision has not completed one.
So the two effects of a successful login are separated at the owner, and the weaker one is available on its own: clearing an attacker's own pair counter gives away nothing, while minting the bypass gives away the tier it bypasses. A caller that cannot name the verified credential it is recording must call this, never RecordSuccess.
func (*LoginLimiter) EntryCount ¶ added in v1.0.358
func (l *LoginLimiter) EntryCount() int
EntryCount returns the number of tier-1 pair and tier-2 account entries the limiter is holding (the trusted-IP grants are not counted: only a SUCCESSFUL authentication creates one).
That parenthesis is a PREMISE, not an observation, and it was false until the CHAOS-112 rider: the admin login handler's pre-setup bootstrap branch reached RecordSuccess with no credential verified, so an unauthenticated caller could grow `trusted` — the one map here with no bound on its OUTER key and a 30-day rather than a Window-length prune horizon — while this gauge read zero for all of it. What now enforces the premise is RecordSuccess's stated precondition and the ClearFailures primitive its non-verifying callers use instead; the gate is TestCHAOS112Rider_BootstrapWindowLoginMintsNoTrustGrant in package main.
Both counted maps are keyed by data an UNAUTHENTICATED caller chooses, so their size is a security observable, not a curiosity: MaxUsernameKeyLen bounds each key's bytes (CHAOS-63) and Cleanup bounds how long an entry survives, but nothing here bounds how many a caller may create — that is the callers' job. package main exports it as the culvert_login_limiter_entries gauge.
func (*LoginLimiter) RecordFailure ¶
func (l *LoginLimiter) RecordFailure(ip, username string) bool
RecordFailure registers one failed attempt from ip against username in both tiers. Returns true when this attempt JUST tripped either lock (so the caller can log the lockout event).
func (*LoginLimiter) RecordPairFailure ¶ added in v1.0.32
func (l *LoginLimiter) RecordPairFailure(ip, username string) bool
RecordPairFailure registers one failed attempt against the tier-1 (IP, username) pair ONLY, leaving the account tier untouched. Pair-only companion to CheckPair. Returns true when this attempt JUST tripped the pair lock.
func (*LoginLimiter) RecordSuccess ¶
func (l *LoginLimiter) RecordSuccess(ip, username string)
RecordSuccess clears the pair's failure history and marks ip as trusted for username (TrustTTL, bounded at trustMaxIPs with oldest-first eviction). The tier-2 account counter is deliberately NOT cleared: a victim's successful login must not erase the evidence of a concurrent distributed attack, and the victim doesn't need it cleared — their IP is now trusted.
PRECONDITION, and it is a security precondition rather than a usage note: the caller MUST have verified a real credential for username — a VerifyUIUser (or equivalent) that returned true on the password the client actually supplied. The trust grant this mints is a tier-2 bypass that lives for TrustTTL and is visible in no operator surface (Snapshot reports locks, not grants) and cleared by no operator action (ResetUser deliberately leaves trust alone), so an unearned one cannot be seen or revoked short of a restart. A caller that forces its own authorization verdict — a first-run bootstrap window, a liveness re-check of headers it already accepted, a test harness — must call ClearFailures instead.
func (*LoginLimiter) ResetUser ¶ added in v1.0.32
func (l *LoginLimiter) ResetUser(username string)
ResetUser removes ALL failure/lock state for username — the tier-2 account entry and every (ip, username) pair — without touching the trusted-IP set (trust is an allowance earned by a successful login, not lock state). This is the explicit unlock primitive: test isolation helpers use it where the old single-tier code abused RecordSuccess as a full reset, and it is the natural hook for a future admin "unlock account" API.
func (*LoginLimiter) Snapshot ¶ added in v1.0.63
func (l *LoginLimiter) Snapshot() []LockedEntry
Snapshot returns every currently-active lockout across both tiers, sorted by username then IP for stable display. It is the read side of the explicit unlock primitive (ResetUser) — without it, an operator has no way to see who is locked out short of reading logs or waiting/restarting. It does not mutate limiter state; expired entries are simply omitted.
func (*LoginLimiter) SnapshotAndClear ¶
func (l *LoginLimiter) SnapshotAndClear() func()
SnapshotAndClear captures the current limiter state, replaces it with an empty state, and returns a closure that restores the captured state. It is the exported equivalent of the whitebox snapshot/restore idiom used for test isolation of the package-global limiter: the maps are deep-copied under the mutex and the restore runs under the mutex too, so neither tears against a concurrent reader/writer. Production code never calls this; it exists so package main's test isolation helper does not need access to the unexported maps across the package boundary (ADR-0002 extraction).
type Reservation ¶ added in v1.0.256
type Reservation struct {
// contains filtered or unexported fields
}
Reservation identifies one unit claimed by Reserve. It is bound to the limiter WINDOW it was claimed in, so a Refund landing after the window has rolled over cannot decrement a later window's count. The zero value is a no-op Refund.