3x-ui/web/middleware/ratelimit.go
Sora39831 90665c92f4 fix: harden registration with rate limiting, input validation, and security fixes
- Add per-IP rate limiter middleware (5 req/min) on /register endpoint
- Validate username (3-64 chars) and password (8-128 chars) with trim
- Use sentinel error ErrUsernameAlreadyExists instead of string matching
- Prevent TurnstileSecretKey exposure via admin settings API (json:"-")
- Skip json:"-" fields in UpdateAllSetting to avoid overwriting secrets
- Add SetTurnstileSecretKey setter for programmatic configuration
- Reuse package-level http.Client in Turnstile verification for connection pooling
- Add io.LimitReader to cap Turnstile response body size
- Log all Turnstile verification error paths for debugging
- Add invalidUsername/invalidPassword i18n keys to all 13 locales
2026-04-03 02:02:25 +08:00

82 lines
1.6 KiB
Go

package middleware
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v2/web/entity"
)
type rateEntry struct {
count int
lastSeen time.Time
}
// RateLimitMiddleware returns a Gin middleware that limits requests per IP.
// maxRequests is the maximum number of requests allowed within the window.
func RateLimitMiddleware(maxRequests int, window time.Duration) gin.HandlerFunc {
var mu sync.Mutex
entries := make(map[string]*rateEntry)
// Periodically evict stale entries to prevent unbounded memory growth
go func() {
ticker := time.NewTicker(window)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
cutoff := time.Now().Add(-window * 2)
for ip, e := range entries {
if e.lastSeen.Before(cutoff) {
delete(entries, ip)
}
}
mu.Unlock()
}
}()
return func(c *gin.Context) {
ip := c.GetHeader("X-Real-IP")
if ip == "" {
ip = c.GetHeader("X-Forwarded-For")
if ip != "" {
// Take the first IP from X-Forwarded-For
if idx := len(ip); idx > 0 {
for i, ch := range ip {
if ch == ',' {
ip = ip[:i]
break
}
}
}
}
}
if ip == "" {
ip = c.Request.RemoteAddr
}
mu.Lock()
now := time.Now()
e, exists := entries[ip]
if !exists || now.Sub(e.lastSeen) > window {
entries[ip] = &rateEntry{count: 1, lastSeen: now}
mu.Unlock()
c.Next()
return
}
e.lastSeen = now
e.count++
if e.count > maxRequests {
mu.Unlock()
c.JSON(http.StatusTooManyRequests, entity.Msg{
Success: false,
Msg: "Too many requests",
})
c.Abort()
return
}
mu.Unlock()
c.Next()
}
}