feat(multiplayer): enforce account and IP rate limits

This commit is contained in:
Josh Creek
2026-09-01 19:18:40 +01:00
parent aa97259165
commit e1abac1271
4 changed files with 76 additions and 19 deletions
+54 -17
View File
@@ -35,7 +35,14 @@ func NewRateLimiter(limit int, window time.Duration, maxKeys int) (*RateLimiter,
}
func (l *RateLimiter) Allow(key string, now time.Time) bool {
if l == nil || key == "" || now.IsZero() {
return l.AllowKeys([]string{key}, now)
}
// AllowKeys atomically charges every non-empty key for a request. This lets
// the HTTP boundary enforce both the authenticated credential and source IP
// limits without charging one dimension when the other dimension rejects.
func (l *RateLimiter) AllowKeys(keys []string, now time.Time) bool {
if l == nil || now.IsZero() {
return false
}
l.mu.Lock()
@@ -45,37 +52,67 @@ func (l *RateLimiter) Allow(key string, now time.Time) bool {
delete(l.entries, storedKey)
}
}
entry, exists := l.entries[key]
if !exists {
if len(l.entries) >= l.maxKeys {
return false
unique := make([]string, 0, len(keys))
seen := make(map[string]struct{}, len(keys))
for _, key := range keys {
if key == "" {
continue
}
l.entries[key] = rateWindow{started: now, count: 1}
return true
if _, exists := seen[key]; exists {
continue
}
seen[key] = struct{}{}
unique = append(unique, key)
}
if !now.Before(entry.started.Add(l.window)) {
l.entries[key] = rateWindow{started: now, count: 1}
return true
}
if entry.count >= l.limit {
if len(unique) == 0 {
return false
}
entry.count++
l.entries[key] = entry
newKeys := 0
for _, key := range unique {
entry, exists := l.entries[key]
if !exists {
newKeys++
continue
}
if now.Before(entry.started.Add(l.window)) && entry.count >= l.limit {
return false
}
}
if len(l.entries)+newKeys > l.maxKeys {
return false
}
for _, key := range unique {
entry, exists := l.entries[key]
if !exists || !now.Before(entry.started.Add(l.window)) {
l.entries[key] = rateWindow{started: now, count: 1}
continue
}
entry.count++
l.entries[key] = entry
}
return true
}
func requestRateKey(r *http.Request) string {
keys := requestRateKeys(r)
if len(keys) == 0 {
return ""
}
return keys[0]
}
func requestRateKeys(r *http.Request) []string {
keys := make([]string, 0, 2)
if authorization := strings.TrimSpace(r.Header.Get("Authorization")); authorization != "" {
digest := sha256.Sum256([]byte(authorization))
return "auth:" + hex.EncodeToString(digest[:])
keys = append(keys, "auth:"+hex.EncodeToString(digest[:]))
}
host := r.RemoteAddr
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
host = parsedHost
}
if host == "" {
return ""
return keys
}
return "ip:" + host
return append(keys, "ip:"+host)
}
+20
View File
@@ -28,6 +28,26 @@ func TestRateLimiterEnforcesWindowAndBoundsKeyMemory(t *testing.T) {
}
}
func TestRateLimiterChargesCredentialAndIPDimensionsAtomically(t *testing.T) {
limiter, err := NewRateLimiter(1, time.Minute, 8)
if err != nil {
t.Fatal(err)
}
start := time.Unix(1000, 0)
if !limiter.AllowKeys([]string{"auth:player", "ip:one"}, start) {
t.Fatal("first request was rejected")
}
if limiter.AllowKeys([]string{"auth:player", "ip:two"}, start) {
t.Fatal("same credential bypassed the account dimension by changing IP")
}
if limiter.AllowKeys([]string{"auth:other", "ip:one"}, start) {
t.Fatal("same IP bypassed the IP dimension by changing credential")
}
if !limiter.AllowKeys([]string{"auth:other", "ip:two"}, start) {
t.Fatal("unrelated credential/IP pair was charged by a rejected request")
}
}
func TestRateLimitedHTTPBoundaryReturnsGeneric429(t *testing.T) {
limiter, err := NewRateLimiter(1, time.Minute, 8)
if err != nil {
+1 -1
View File
@@ -207,7 +207,7 @@ func (s *Service) Handler() http.Handler {
var handler http.Handler = mux
if s.RateLimiter != nil {
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.RateLimiter.Allow(requestRateKey(r), s.now()) {
if !s.RateLimiter.AllowKeys(requestRateKeys(r), s.now()) {
writeError(w, http.StatusTooManyRequests, "rate_limited")
return
}