mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
fix(middleware): abort canceled Redis rate-limit checks with 499 (#8512)
Treat Redis rate-limit failures as client-closed (HTTP 499, no error log) only when both the Redis error and request context report context.Canceled, while keeping deadline timeouts and Redis failures fail-closed with HTTP 500. Closes #8462
This commit is contained in:
1 parent
5f56c685d4
commit
5911c8cca8
2 files changed
+86
No files matched your search
@@ -36,8 +36,20 @@ end
|
||||
return {1, count, ttl}
|
||||
`
|
||||
|
||||
// statusClientClosedRequest is the nginx convention for a request the client
|
||||
// abandoned before the server responded. It is never seen by the client and
|
||||
// only keeps access logs from counting the abort as a server error.
|
||||
const statusClientClosedRequest = 499
|
||||
|
||||
var inMemoryRateLimiter common.InMemoryRateLimiter
|
||||
|
||||
// requestCanceledByClient reports whether a Redis rate limit failure was caused
|
||||
// by the client closing its request. A deadline or any other Redis failure is
|
||||
// still a server error, so the limiter keeps failing closed for those.
|
||||
func requestCanceledByClient(c *gin.Context, err error) bool {
|
||||
return errors.Is(err, context.Canceled) && errors.Is(c.Request.Context().Err(), context.Canceled)
|
||||
}
|
||||
|
||||
var defNext = func(c *gin.Context) {
|
||||
c.Next()
|
||||
}
|
||||
@@ -115,6 +127,10 @@ func redisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark st
|
||||
duration,
|
||||
)
|
||||
if err != nil {
|
||||
if requestCanceledByClient(c, err) {
|
||||
c.AbortWithStatus(statusClientClosedRequest)
|
||||
return
|
||||
}
|
||||
logger.LogError(c.Request.Context(), common.LogText("rate limit check failed (mark=%s): %v", mark, err))
|
||||
c.Status(http.StatusInternalServerError)
|
||||
c.Abort()
|
||||
@@ -250,6 +266,10 @@ func userRateLimitFactory(maxRequestNum int, duration int64, mark string) func(c
|
||||
func userRedisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, key string) {
|
||||
allowed, _, ttlSeconds, err := redisFixedWindowTake(c.Request.Context(), key, maxRequestNum, duration)
|
||||
if err != nil {
|
||||
if requestCanceledByClient(c, err) {
|
||||
c.AbortWithStatus(statusClientClosedRequest)
|
||||
return
|
||||
}
|
||||
logger.LogError(c.Request.Context(), common.LogText("rate limit check failed (key=%s): %v", key, err))
|
||||
c.Status(http.StatusInternalServerError)
|
||||
c.Abort()
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -227,6 +229,70 @@ func TestRedisFailurePolicies(t *testing.T) {
|
||||
assert.Equal(t, http.StatusNoContent, performRateLimitRequest(router, "/email", "192.0.2.62:12345").Code)
|
||||
}
|
||||
|
||||
func TestRedisRateLimiterRequestContextErrors(t *testing.T) {
|
||||
useRateLimitMiniRedis(t)
|
||||
|
||||
canceledContext := func() context.Context {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
return ctx
|
||||
}
|
||||
expiredContext := func() context.Context {
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0))
|
||||
cancel()
|
||||
return ctx
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
requestCtx func() context.Context
|
||||
wantStatus int
|
||||
wantLogged bool
|
||||
}{
|
||||
{name: "IP limiter client canceled", path: "/ip", requestCtx: canceledContext, wantStatus: 499},
|
||||
{name: "user limiter client canceled", path: "/user", requestCtx: canceledContext, wantStatus: 499},
|
||||
{name: "IP limiter deadline exceeded", path: "/ip", requestCtx: expiredContext, wantStatus: http.StatusInternalServerError, wantLogged: true},
|
||||
{name: "user limiter deadline exceeded", path: "/user", requestCtx: expiredContext, wantStatus: http.StatusInternalServerError, wantLogged: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
common.LogWriterMu.Lock()
|
||||
previousErrorWriter := gin.DefaultErrorWriter
|
||||
gin.DefaultErrorWriter = &logs
|
||||
common.LogWriterMu.Unlock()
|
||||
restoreErrorWriter := func() {
|
||||
common.LogWriterMu.Lock()
|
||||
gin.DefaultErrorWriter = previousErrorWriter
|
||||
common.LogWriterMu.Unlock()
|
||||
}
|
||||
t.Cleanup(restoreErrorWriter)
|
||||
|
||||
downstreamCalled := false
|
||||
downstream := func(c *gin.Context) {
|
||||
downstreamCalled = true
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
router := gin.New()
|
||||
require.NoError(t, router.SetTrustedProxies(nil))
|
||||
router.GET("/ip", rateLimitFactory(1, 30, "CTX-IP"), downstream)
|
||||
router.GET("/user", func(c *gin.Context) { c.Set("id", 9) }, userRateLimitFactory(1, 30, "CTX-USER"), downstream)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequestWithContext(tt.requestCtx(), http.MethodGet, tt.path, nil)
|
||||
request.RemoteAddr = "192.0.2.63:12345"
|
||||
router.ServeHTTP(recorder, request)
|
||||
restoreErrorWriter()
|
||||
|
||||
assert.Equal(t, tt.wantStatus, recorder.Code)
|
||||
assert.Empty(t, recorder.Body.String())
|
||||
assert.False(t, downstreamCalled)
|
||||
assert.Equal(t, tt.wantLogged, strings.Contains(logs.String(), "rate limit check failed"), logs.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlobalWebRateLimitCountsFrontendFilesInStaticBucket(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
previousWebEnable, previousWebNum, previousWebDuration := common.GlobalWebRateLimitEnable, common.GlobalWebRateLimitNum, common.GlobalWebRateLimitDuration
|
||||
|
||||
Reference in new issue
Block a user