// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "sync" "time" ) const ( loginFailureLimit = 5 loginFailureWindow = 15 * time.Minute loginBlockDuration = 15 * time.Minute loginLimiterMaxKeys = 10000 ) type limitEntry struct { failures []time.Time blockedUntil time.Time } func (e *limitEntry) blocked(now time.Time) bool { return now.Before(e.blockedUntil) } func (e *limitEntry) prune(now time.Time) { kept := e.failures[:0] for _, t := range e.failures { if now.Sub(t) < loginFailureWindow { kept = append(kept, t) } } e.failures = kept } func (e *limitEntry) lastFailure() time.Time { if len(e.failures) == 0 { return time.Time{} } return e.failures[len(e.failures)-1] } type limitTable struct { max int entries map[string]*limitEntry } func newLimitTable(max int) *limitTable { return &limitTable{max: max, entries: make(map[string]*limitEntry)} } func (t *limitTable) prune(now time.Time) { for key, e := range t.entries { e.prune(now) if len(e.failures) == 0 && !e.blocked(now) { delete(t.entries, key) } } } func (t *limitTable) evictOne(now time.Time) bool { victim := "" var oldest time.Time for key, e := range t.entries { if e.blocked(now) { continue } if last := e.lastFailure(); victim == "" || last.Before(oldest) { victim, oldest = key, last } } if victim == "" { return false } delete(t.entries, victim) return true } func (t *limitTable) full(now time.Time) bool { if len(t.entries) < t.max { return false } t.prune(now) return len(t.entries) >= t.max } func (t *limitTable) allows(key string, now time.Time) bool { if e := t.entries[key]; e != nil { return !e.blocked(now) } if !t.full(now) { return true } for _, e := range t.entries { if !e.blocked(now) { return true } } return false } func (t *limitTable) fail(key string, now time.Time) { e := t.entries[key] if e == nil { if t.full(now) && !t.evictOne(now) { return } e = &limitEntry{} t.entries[key] = e } if e.blocked(now) { return } e.prune(now) e.failures = append(e.failures, now) if len(e.failures) >= loginFailureLimit { e.blockedUntil = now.Add(loginBlockDuration) e.failures = nil } } type loginLimiter struct { mu sync.Mutex now func() time.Time users *limitTable origins *limitTable } func newLoginLimiter(now func() time.Time, maxKeys int) *loginLimiter { return &loginLimiter{now: now, users: newLimitTable(maxKeys), origins: newLimitTable(maxKeys)} } func (l *loginLimiter) allow(username, origin string) bool { l.mu.Lock() defer l.mu.Unlock() now := l.now() userOK := l.users.allows(username, now) originOK := l.origins.allows(origin, now) return userOK && originOK } func (l *loginLimiter) fail(username, origin string) { l.mu.Lock() defer l.mu.Unlock() now := l.now() l.users.fail(username, now) l.origins.fail(origin, now) } func (l *loginLimiter) succeed(username string) { l.mu.Lock() defer l.mu.Unlock() delete(l.users.entries, username) }