parsimony/internal/api/limit.go
tgiachi 625d487eca fix(security): API token strength and brute-force lockout
- Refuse an API token under 24 characters or with whitespace at startup, without echoing it
- Lock an address out for 5 minutes after 10 wrong or missing tokens in 5 minutes (429 with Retry-After)
- Ignore X-Forwarded-For for the lockout, forget idle addresses
- Document both
2026-11-09 20:25:05 +01:00

97 lines
2.1 KiB
Go

package api
import (
"net"
"net/http"
"sync"
"time"
)
// Brute-force protection for the bearer token: after maxFailures wrong (or missing) tokens within
// failureWindow, an address is locked out for lockout, valid token included.
const (
maxFailures = 10
failureWindow = 5 * time.Minute
lockout = 5 * time.Minute
sweepEvery = time.Minute
)
type attempts struct {
count int
first time.Time
blockedUntil time.Time
}
type limiter struct {
mu sync.Mutex
now func() time.Time
byIP map[string]*attempts
lastSweep time.Time
}
func newLimiter(now func() time.Time) *limiter {
return &limiter{now: now, byIP: map[string]*attempts{}, lastSweep: now()}
}
// blocked reports whether ip is locked out and for how much longer.
func (l *limiter) blocked(ip string) (time.Duration, bool) {
l.mu.Lock()
defer l.mu.Unlock()
if e := l.byIP[ip]; e != nil {
if wait := e.blockedUntil.Sub(l.now()); wait > 0 {
return wait, true
}
}
return 0, false
}
func (l *limiter) fail(ip string) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
l.sweep(now)
e := l.byIP[ip]
if e == nil || now.Sub(e.first) > failureWindow {
e = &attempts{first: now}
l.byIP[ip] = e
}
e.count++
if e.count >= maxFailures {
e.blockedUntil = now.Add(lockout)
}
}
func (l *limiter) succeed(ip string) {
l.mu.Lock()
defer l.mu.Unlock()
delete(l.byIP, ip)
}
// sweep forgets addresses whose failures and lockout are over, so the map cannot grow forever.
func (l *limiter) sweep(now time.Time) {
if now.Sub(l.lastSweep) < sweepEvery {
return
}
l.lastSweep = now
for ip, e := range l.byIP {
if now.Sub(e.first) > failureWindow && !now.Before(e.blockedUntil) {
delete(l.byIP, ip)
}
}
}
func (l *limiter) size() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.byIP)
}
// clientIP is the address of the TCP peer. X-Forwarded-For is deliberately ignored: anyone can
// send it, so trusting it would let an attacker choose a fresh identity for every guess.
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}