Files
EvoBGP/internal/httpapi/ratelimit.go
T
DenozordecandCursor 6c6e76fca3
CI / changes (push) Successful in 7s
CI / openapi (push) Failing after 40s
CI / web (push) Successful in 56s
CI / commitlint (push) Skipped
CI / go (push) Failing after 34s
CI / bird2 (push) Skipped
CI / release (push) Skipped
feat(ops): protect metrics, rate-limit auth, agent secret timing, e2e smoke
Bearer для /metrics (EVOBGP_METRICS_TOKEN); rate limit /v1/auth/config; constant-time agent secret; OTel stub; Playwright smoke; HTTP_PROXY note; checklist обновлён.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 12:29:00 +07:00

69 lines
1.3 KiB
Go

package httpapi
import (
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
// authRateLimiter is a simple per-IP token bucket for public auth-ish endpoints.
type authRateLimiter struct {
mu sync.Mutex
hits map[string][]time.Time
limit int
window time.Duration
}
func newAuthRateLimiter() *authRateLimiter {
limit := 60
if n, err := strconv.Atoi(strings.TrimSpace(os.Getenv("EVOBGP_AUTH_RATE_LIMIT"))); err == nil && n > 0 {
limit = n
}
return &authRateLimiter{
hits: make(map[string][]time.Time),
limit: limit,
window: time.Minute,
}
}
func (l *authRateLimiter) allow(ip string) bool {
if l == nil {
return true
}
now := time.Now()
l.mu.Lock()
defer l.mu.Unlock()
cut := now.Add(-l.window)
arr := l.hits[ip]
kept := arr[:0]
for _, t := range arr {
if t.After(cut) {
kept = append(kept, t)
}
}
if len(kept) >= l.limit {
l.hits[ip] = kept
return false
}
kept = append(kept, now)
l.hits[ip] = kept
return true
}
func (s *Server) withAuthRateLimit(next http.HandlerFunc) http.HandlerFunc {
if s.authLimiter == nil {
s.authLimiter = newAuthRateLimiter()
}
return func(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r)
if !s.authLimiter.allow(ip) {
writeProblem(w, http.StatusTooManyRequests, "Too Many Requests", "auth rate limit exceeded")
return
}
next(w, r)
}
}