- Add lint, formatting, vet, and publish workflow checks - Run Go database tests with PostgreSQL and add Java tests - Make consumer sync opt-in; update docs and Go dependency
60 lines
1.7 KiB
Go
60 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// Attempt limits for the credential endpoints (login and the TOTP verify/disable routes). Each key
|
|
// may make limit attempts per window; further attempts are refused until the window ends. The
|
|
// counters live in this process, and AuthGuard's own limits still apply on top.
|
|
const (
|
|
attemptWindow = 15 * time.Minute
|
|
loginAccountLimit = 10
|
|
loginClientLimit = 200
|
|
totpAttemptLimit = 5
|
|
maxTrackedAttemptKeys = 10000
|
|
)
|
|
|
|
type attemptCounter struct {
|
|
windowStart time.Time
|
|
count int
|
|
}
|
|
|
|
// attemptLimiter is a fixed-window counter keyed by an account, a client address or a user.
|
|
type attemptLimiter struct {
|
|
mu sync.Mutex
|
|
window time.Duration
|
|
limit int
|
|
counts map[string]attemptCounter
|
|
}
|
|
|
|
func newAttemptLimiter(window time.Duration, limit int) *attemptLimiter {
|
|
return &attemptLimiter{window: window, limit: limit, counts: make(map[string]attemptCounter)}
|
|
}
|
|
|
|
// allow records one attempt for key at time now and reports whether it is within the limit. When
|
|
// the table is full of live keys, a new key is refused rather than tracked, so flooding distinct
|
|
// keys cannot grow memory without bound.
|
|
func (l *attemptLimiter) allow(key string, now time.Time) bool {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
counter, tracked := l.counts[key]
|
|
if !tracked && len(l.counts) >= maxTrackedAttemptKeys {
|
|
for existing, state := range l.counts {
|
|
if now.Sub(state.windowStart) >= l.window {
|
|
delete(l.counts, existing)
|
|
}
|
|
}
|
|
if len(l.counts) >= maxTrackedAttemptKeys {
|
|
return false
|
|
}
|
|
}
|
|
if counter.windowStart.IsZero() || now.Sub(counter.windowStart) >= l.window {
|
|
counter = attemptCounter{windowStart: now}
|
|
}
|
|
counter.count++
|
|
l.counts[key] = counter
|
|
return counter.count <= l.limit
|
|
}
|