Compare commits
2 Commits
a1b06219e7
...
723f7b2cf7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
723f7b2cf7 | ||
|
|
e8992d2311 |
@ -2,15 +2,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/99designs/basicauth-go"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
"go.uber.org/fx"
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
"git.eeqj.de/sneak/upaas/internal/config"
|
||||
"git.eeqj.de/sneak/upaas/internal/globals"
|
||||
@ -152,6 +156,113 @@ func (m *Middleware) SessionAuth() func(http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
// loginRateLimit configures the login rate limiter.
|
||||
const (
|
||||
loginRateLimit = rate.Limit(5.0 / 60.0) // 5 requests per 60 seconds
|
||||
loginBurst = 5 // allow burst of 5
|
||||
limiterExpiry = 10 * time.Minute // evict entries not seen in 10 minutes
|
||||
limiterCleanupEvery = 1 * time.Minute // sweep interval
|
||||
)
|
||||
|
||||
// ipLimiterEntry stores a rate limiter with its last-seen timestamp.
|
||||
type ipLimiterEntry struct {
|
||||
limiter *rate.Limiter
|
||||
lastSeen time.Time
|
||||
}
|
||||
|
||||
// ipLimiter tracks per-IP rate limiters for login attempts with automatic
|
||||
// eviction of stale entries to prevent unbounded memory growth.
|
||||
type ipLimiter struct {
|
||||
mu sync.Mutex
|
||||
limiters map[string]*ipLimiterEntry
|
||||
lastSweep time.Time
|
||||
}
|
||||
|
||||
func newIPLimiter() *ipLimiter {
|
||||
return &ipLimiter{
|
||||
limiters: make(map[string]*ipLimiterEntry),
|
||||
lastSweep: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// sweep removes entries not seen within limiterExpiry. Must be called with mu held.
|
||||
func (i *ipLimiter) sweep(now time.Time) {
|
||||
for ip, entry := range i.limiters {
|
||||
if now.Sub(entry.lastSeen) > limiterExpiry {
|
||||
delete(i.limiters, ip)
|
||||
}
|
||||
}
|
||||
i.lastSweep = now
|
||||
}
|
||||
|
||||
func (i *ipLimiter) getLimiter(ip string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
|
||||
// Lazy sweep: clean up stale entries periodically.
|
||||
if now.Sub(i.lastSweep) >= limiterCleanupEvery {
|
||||
i.sweep(now)
|
||||
}
|
||||
|
||||
entry, exists := i.limiters[ip]
|
||||
if !exists {
|
||||
entry = &ipLimiterEntry{
|
||||
limiter: rate.NewLimiter(loginRateLimit, loginBurst),
|
||||
}
|
||||
i.limiters[ip] = entry
|
||||
}
|
||||
entry.lastSeen = now
|
||||
|
||||
return entry.limiter
|
||||
}
|
||||
|
||||
// loginLimiter is the singleton IP rate limiter for login attempts.
|
||||
//
|
||||
//nolint:gochecknoglobals // intentional singleton for rate limiting state
|
||||
var loginLimiter = newIPLimiter()
|
||||
|
||||
// LoginRateLimit returns middleware that rate-limits login attempts per IP.
|
||||
// It allows 5 attempts per minute and returns 429 Too Many Requests when exceeded.
|
||||
func (m *Middleware) LoginRateLimit() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(
|
||||
writer http.ResponseWriter,
|
||||
request *http.Request,
|
||||
) {
|
||||
ip := ipFromHostPort(request.RemoteAddr)
|
||||
limiter := loginLimiter.getLimiter(ip)
|
||||
|
||||
if !limiter.Allow() {
|
||||
m.log.WarnContext(request.Context(), "login rate limit exceeded",
|
||||
"remoteIP", ip,
|
||||
)
|
||||
|
||||
// Compute seconds until the next token is available.
|
||||
reservation := limiter.Reserve()
|
||||
delay := reservation.Delay()
|
||||
reservation.Cancel()
|
||||
retryAfter := int(math.Ceil(delay.Seconds()))
|
||||
if retryAfter < 1 {
|
||||
retryAfter = 1
|
||||
}
|
||||
writer.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
|
||||
|
||||
http.Error(
|
||||
writer,
|
||||
"Too Many Requests",
|
||||
http.StatusTooManyRequests,
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(writer, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// SetupRequired returns middleware that redirects to setup if no user exists.
|
||||
func (m *Middleware) SetupRequired() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
|
||||
135
internal/middleware/ratelimit_test.go
Normal file
135
internal/middleware/ratelimit_test.go
Normal file
@ -0,0 +1,135 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"git.eeqj.de/sneak/upaas/internal/config"
|
||||
)
|
||||
|
||||
func newTestMiddleware(t *testing.T) *Middleware {
|
||||
t.Helper()
|
||||
|
||||
return &Middleware{
|
||||
log: slog.Default(),
|
||||
params: &Params{
|
||||
Config: &config.Config{},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRateLimitAllowsUpToBurst(t *testing.T) {
|
||||
// Reset the global limiter to get clean state
|
||||
loginLimiter = newIPLimiter()
|
||||
|
||||
mw := newTestMiddleware(t)
|
||||
|
||||
handler := mw.LoginRateLimit()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
// First 5 requests should succeed (burst)
|
||||
for i := range 5 {
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req.RemoteAddr = "192.168.1.1:12345"
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
assert.Equal(t, http.StatusOK, rec.Code, "request %d should succeed", i+1)
|
||||
}
|
||||
|
||||
// 6th request should be rate limited
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req.RemoteAddr = "192.168.1.1:12345"
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
assert.Equal(t, http.StatusTooManyRequests, rec.Code, "6th request should be rate limited")
|
||||
}
|
||||
|
||||
func TestLoginRateLimitIsolatesIPs(t *testing.T) {
|
||||
loginLimiter = newIPLimiter()
|
||||
|
||||
mw := newTestMiddleware(t)
|
||||
|
||||
handler := mw.LoginRateLimit()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
// Exhaust IP1's budget
|
||||
for range 5 {
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req.RemoteAddr = "10.0.0.1:1234"
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
}
|
||||
|
||||
// IP1 should be blocked
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req.RemoteAddr = "10.0.0.1:1234"
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
assert.Equal(t, http.StatusTooManyRequests, rec.Code)
|
||||
|
||||
// IP2 should still work
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req2.RemoteAddr = "10.0.0.2:1234"
|
||||
rec2 := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec2, req2)
|
||||
assert.Equal(t, http.StatusOK, rec2.Code, "different IP should not be rate limited")
|
||||
}
|
||||
|
||||
func TestLoginRateLimitReturns429Body(t *testing.T) {
|
||||
loginLimiter = newIPLimiter()
|
||||
|
||||
mw := newTestMiddleware(t)
|
||||
|
||||
handler := mw.LoginRateLimit()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
// Exhaust burst
|
||||
for range 5 {
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req.RemoteAddr = "172.16.0.1:5555"
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", nil)
|
||||
req.RemoteAddr = "172.16.0.1:5555"
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
assert.Equal(t, http.StatusTooManyRequests, rec.Code)
|
||||
assert.Contains(t, rec.Body.String(), "Too Many Requests")
|
||||
assert.NotEmpty(t, rec.Header().Get("Retry-After"), "should include Retry-After header")
|
||||
}
|
||||
|
||||
func TestIPLimiterEvictsStaleEntries(t *testing.T) {
|
||||
il := newIPLimiter()
|
||||
|
||||
// Add an entry and backdate its lastSeen
|
||||
il.mu.Lock()
|
||||
il.limiters["1.2.3.4"] = &ipLimiterEntry{
|
||||
limiter: nil,
|
||||
lastSeen: time.Now().Add(-15 * time.Minute),
|
||||
}
|
||||
il.limiters["5.6.7.8"] = &ipLimiterEntry{
|
||||
limiter: nil,
|
||||
lastSeen: time.Now(),
|
||||
}
|
||||
il.mu.Unlock()
|
||||
|
||||
// Trigger sweep
|
||||
il.mu.Lock()
|
||||
il.sweep(time.Now())
|
||||
il.mu.Unlock()
|
||||
|
||||
il.mu.Lock()
|
||||
defer il.mu.Unlock()
|
||||
assert.NotContains(t, il.limiters, "1.2.3.4", "stale entry should be evicted")
|
||||
assert.Contains(t, il.limiters, "5.6.7.8", "fresh entry should remain")
|
||||
}
|
||||
@ -39,7 +39,7 @@ func (s *Server) SetupRoutes() {
|
||||
|
||||
// Public routes
|
||||
s.router.Get("/login", s.handlers.HandleLoginGET())
|
||||
s.router.Post("/login", s.handlers.HandleLoginPOST())
|
||||
s.router.With(s.mw.LoginRateLimit()).Post("/login", s.handlers.HandleLoginPOST())
|
||||
s.router.Get("/setup", s.handlers.HandleSetupGET())
|
||||
s.router.Post("/setup", s.handlers.HandleSetupPOST())
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user