90 lines
2.0 KiB
Go
90 lines
2.0 KiB
Go
package botfilter
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type scoreEvent struct {
|
|
at time.Time
|
|
points int
|
|
}
|
|
|
|
type clientState struct {
|
|
banUntil time.Time
|
|
lastSeen time.Time
|
|
requests int
|
|
sawHome bool
|
|
sawStatic bool
|
|
sawFavicon bool
|
|
events []scoreEvent
|
|
}
|
|
|
|
type requestObservation struct {
|
|
at time.Time
|
|
paths []string
|
|
points int
|
|
forceBan bool
|
|
}
|
|
|
|
type cacheResult struct {
|
|
banned bool
|
|
banUntil time.Time
|
|
score int
|
|
}
|
|
|
|
// clientCache deliberately has no background goroutine. A middleware
|
|
// instance can be discarded on a Traefik reload without needing goroutine
|
|
// cleanup, and opportunistic cleanup keeps its memory use bounded.
|
|
type clientCache struct {
|
|
mu sync.Mutex
|
|
entries map[string]*clientState
|
|
maxEntries int
|
|
maxEvents int
|
|
scoreWindow time.Duration
|
|
banDuration time.Duration
|
|
threshold int
|
|
randomPaths []string
|
|
randomScore int
|
|
operations uint64
|
|
}
|
|
|
|
func newClientCache(cfg *compiledConfig) *clientCache {
|
|
return &clientCache{
|
|
entries: make(map[string]*clientState),
|
|
maxEntries: cfg.MaxTrackedIPs,
|
|
maxEvents: cfg.MaxScoreEventsPerIP,
|
|
scoreWindow: cfg.scoreWindow,
|
|
banDuration: cfg.banDuration,
|
|
threshold: cfg.ScoreThreshold,
|
|
randomPaths: append([]string(nil), cfg.randomPaths...),
|
|
randomScore: cfg.RandomArticleScore,
|
|
}
|
|
}
|
|
|
|
func (c *clientCache) isBanned(ip string, now time.Time) cacheResult {
|
|
if ip == "" {
|
|
return cacheResult{}
|
|
}
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
state := c.entries[ip]
|
|
if state == nil || !state.banUntil.After(now) {
|
|
return cacheResult{}
|
|
}
|
|
return cacheResult{banned: true, banUntil: state.banUntil}
|
|
}
|
|
|
|
func (c *clientCache) observeRequest(ip string, observation requestObservation) cacheResult {
|
|
if ip == "" {
|
|
// An invalid peer address must never share a cache entry with another
|
|
// malformed request. The request can still be rejected by its headers.
|
|
return cacheResult{banned: observation.forceBan}
|
|
}
|
|
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.operations++
|
|
c.cleanupLocked(observation.at)
|
|
|