Files
FlowReader/internal/handler/ratelimit.go
T
Antigravity AgentandClaude Opus 5.5 03e57e4308 fix(backend): harden security and speed up feeds and article API
Security:
- WebSocket events are routed to their owner only (no cross-user leak);
  hub close is idempotent (fixes double-close panic), adds ping/pong and
  write deadlines.
- Session tokens stored as SHA-256 (migration 008 keeps sessions valid);
  single-query auth middleware puts the user in the request context.
- Client IP only trusts X-Forwarded-For from TRUSTED_PROXIES; rate limiter
  map is bounded; per-user limit on AI summaries.
- Argon2id at OWASP minimum with a concurrency cap; constant-time login
  for unknown emails; atomic first-admin bootstrap; REGISTRATION_ENABLED.
- CSP/HSTS/COOP headers, same-origin guard on mutations, body size limits,
  wider SSRF denylist, bounded feed/page/AI response reads, generic errors.
- Upgrade chi, pgx, x/net, x/text, x/crypto (known CVEs); commit go.sum.

Performance:
- List endpoints return a plain-text excerpt and reading time instead of
  full HTML; content is sanitized once at ingest (legacy rows backfilled).
- Keyset pagination on (sort_at, id) with matching partial indexes;
  redundant indexes dropped (migration 007).
- Fetcher: bounded worker pool, conditional GET (ETag/Last-Modified),
  exponential backoff, dedupe before insert, column-safe truncation,
  retention-aware ingest, per-user refresh coalescing.
- Read/favorite/read-all are single ownership-scoped statements.
- gzip compression, immutable caching for hashed assets, path-safe SPA
  handler, server timeouts; expired sessions purged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 07:34:08 +02:00

119 lines
3.1 KiB
Go

package handler
import (
"net/http"
"sync"
"time"
)
// rateLimiter is a simple in-memory token-bucket limiter keyed by client IP.
// It protects brute-force-prone endpoints (login/register) without external
// dependencies. Stale buckets are evicted periodically to bound memory.
type rateLimiter struct {
mu sync.Mutex
buckets map[string]*bucket
rate float64 // tokens added per second
capacity float64 // max tokens (burst)
}
// maxBuckets caps the number of tracked keys per limiter.
const maxBuckets = 50_000
type bucket struct {
tokens float64
last time.Time
}
// newRateLimiter allows `burst` requests immediately, refilling at
// `perMinute` requests per minute thereafter.
func newRateLimiter(perMinute, burst int) *rateLimiter {
rl := &rateLimiter{
buckets: make(map[string]*bucket),
rate: float64(perMinute) / 60.0,
capacity: float64(burst),
}
go rl.cleanupLoop()
return rl
}
func (rl *rateLimiter) allow(key string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
b, ok := rl.buckets[key]
if !ok {
// Bound memory: under a flood of distinct keys, fail closed rather
// than growing the map without limit.
if len(rl.buckets) >= maxBuckets {
return false
}
rl.buckets[key] = &bucket{tokens: rl.capacity - 1, last: now}
return true
}
// Refill based on elapsed time.
b.tokens += now.Sub(b.last).Seconds() * rl.rate
if b.tokens > rl.capacity {
b.tokens = rl.capacity
}
b.last = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
func (rl *rateLimiter) cleanupLoop() {
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for range ticker.C {
rl.mu.Lock()
for k, b := range rl.buckets {
// Drop buckets that have been idle long enough to be full again.
if time.Since(b.last) > 15*time.Minute {
delete(rl.buckets, k)
}
}
rl.mu.Unlock()
}
}
// Middleware returns a chi-compatible middleware enforcing the limit per IP.
func (rl *rateLimiter) Middleware(next http.Handler) http.Handler {
return rl.middlewareBy(getClientIP)(next)
}
// middlewareBy enforces the limit per key computed from the request.
func (rl *rateLimiter) middlewareBy(key func(*http.Request) string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !rl.allow(key(r)) {
w.Header().Set("Retry-After", "60")
respondError(w, http.StatusTooManyRequests, "Too many requests. Please slow down.")
return
}
next.ServeHTTP(w, r)
})
}
}
// NewAuthRateLimiter builds the limiter used for authentication routes:
// 10 requests/minute per IP with a small burst.
func NewAuthRateLimiter() func(http.Handler) http.Handler {
return newRateLimiter(10, 5).Middleware
}
// NewUserRateLimiter limits an authenticated user's calls to an expensive
// endpoint (e.g. AI summaries). Must run after RequireAuth.
func NewUserRateLimiter(perMinute, burst int) func(http.Handler) http.Handler {
return newRateLimiter(perMinute, burst).middlewareBy(func(r *http.Request) string {
if u := currentUser(r); u != nil {
return u.ID.String()
}
return getClientIP(r)
})
}