diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 58372073dd..6ec51d5430 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -147,14 +147,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } @@ -2163,14 +2160,11 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 55abd416a2..1db2e0584a 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -47,14 +47,11 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.chatCompletionsErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.chatCompletionsErrorResponse(c, status, "invalid_request_error", message) return } diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 233cf07f3b..79544a48de 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -47,14 +47,11 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.responsesErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.responsesErrorResponse(c, status, "invalid_request_error", message) return } diff --git a/backend/internal/handler/gateway_systemone.go b/backend/internal/handler/gateway_systemone.go index 4f0d650985..2cb25a5a32 100644 --- a/backend/internal/handler/gateway_systemone.go +++ b/backend/internal/handler/gateway_systemone.go @@ -56,14 +56,11 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } model, err := typesafe.ValidateSystemOneRequest(body) diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index ad6cb765dc..e160f8cef9 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -65,14 +65,12 @@ func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + bodyLog := requestLogger(c, "handler.gemini_cached_contents") + if handleRequestBodyReadError(c, bodyLog, err) { return nil, false } - if maxErr, ok := extractMaxBytesError(err); ok { - googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) - return nil, false - } - googleError(c, http.StatusBadRequest, "Failed to read request body") + status, message := requestBodyReadFailure(bodyLog, c.Request, err) + googleErrorWithType(c, status, "invalid_request_error", "", message) return nil, false } if len(body) == 0 { diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 57c91802fd..06e2472f8d 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -374,14 +374,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) - return - } - googleError(c, http.StatusBadRequest, "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + googleErrorWithType(c, status, "invalid_request_error", "", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index 91814fdf4c..3b9b7c9dda 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -203,10 +203,16 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) { body, err := readGrokVoiceGatewayBody(c) if err != nil { - if handleRequestBodyReadError(c, err) { + if errors.Is(err, errGrokVoiceBodyRequired) { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + bodyLog := requestLogger(c, "handler.openai_gateway.grok_voice", zap.String("endpoint", endpoint)) + if handleRequestBodyReadError(c, bodyLog, err) { + return + } + status, message := requestBodyReadFailure(bodyLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if endpoint == "tts" { @@ -377,15 +383,20 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( }) } +var errGrokVoiceBodyRequired = errors.New("request body is required") + +// readGrokVoiceGatewayBody returns errGrokVoiceBodyRequired for a missing body; +// any other error comes from reading the body and goes through the shared +// read-failure classification. func readGrokVoiceGatewayBody(c *gin.Context) ([]byte, error) { if c == nil || c.Request == nil { - return nil, errors.New("request body is required") + return nil, errGrokVoiceBodyRequired } if c.Request.Body == nil { if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodDelete { return nil, nil } - return nil, errors.New("request body is required") + return nil, errGrokVoiceBodyRequired } return pkghttputil.ReadRequestBodyWithPrealloc(c.Request) } diff --git a/backend/internal/handler/grok_audio_body_test.go b/backend/internal/handler/grok_audio_body_test.go index 84621dce9f..80df25a844 100644 --- a/backend/internal/handler/grok_audio_body_test.go +++ b/backend/internal/handler/grok_audio_body_test.go @@ -1,10 +1,14 @@ package handler import ( + "io" + "net" "net/http" "net/http/httptest" + "os" "strings" "testing" + "testing/iotest" "github.com/Wei-Shaw/sub2api/internal/config" pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" @@ -51,3 +55,55 @@ func TestGrokVoiceRequestBodyMemoryOverload(t *testing.T) { }) } } + +// Read failures other than the memory budget go through the shared classifier: +// a timeout is a 408 with a fixed message, never the raw socket error, and a +// missing body keeps its validation message. +func TestGrokVoiceRequestBodyReadFailures(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := &OpenAIGatewayHandler{ + gatewayService: &service.OpenAIGatewayService{}, + billingCacheService: billing, + apiKeyService: &service.APIKeyService{}, + concurrencyHelper: &ConcurrencyHelper{concurrencyService: service.NewConcurrencyService(nil)}, + cfg: cfg, + } + timeoutErr := &net.OpError{Op: "read", Net: "tcp", Source: &net.TCPAddr{IP: net.IPv4(10, 0, 0, 1), Port: 8080}, Err: os.ErrDeadlineExceeded} + for _, tc := range []struct { + name string + body io.Reader + wantStatus int + wantText string + }{ + {"timeout", iotest.ErrReader(timeoutErr), http.StatusRequestTimeout, "Timed out reading request body"}, + {"truncated", iotest.ErrReader(io.ErrUnexpectedEOF), http.StatusBadRequest, "Failed to read request body"}, + {"missing", nil, http.StatusBadRequest, "request body is required"}, + } { + t.Run(tc.name, func(t *testing.T) { + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformGrok}, + User: &service.User{ID: 1}, + }) + c.Next() + }) + router.POST("/v1/tts", func(c *gin.Context) { h.GrokVoice(c, "tts") }) + req := httptest.NewRequest(http.MethodPost, "/v1/tts", nil) + if tc.body != nil { + req.Body = io.NopCloser(tc.body) + } else { + req.Body = nil + } + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + require.Equal(t, tc.wantStatus, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), tc.wantText) + require.NotContains(t, rec.Body.String(), "10.0.0.1") + }) + } +} diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index db4b4c3f3b..4a13293a2e 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -90,14 +90,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. if endpoint.RequiresRequestBody() { body, err = pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/image_task_handler.go b/backend/internal/handler/image_task_handler.go index 4a49980131..2b01168c54 100644 --- a/backend/internal/handler/image_task_handler.go +++ b/backend/internal/handler/image_task_handler.go @@ -77,14 +77,12 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + bodyLog := requestLogger(c, "handler.image_task.create") + if handleRequestBodyReadError(c, bodyLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - imageTaskJSONError(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - imageTaskJSONError(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(bodyLog, c.Request, err) + imageTaskJSONError(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index dd93c44581..8a76f6b23c 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -52,14 +52,11 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index d6bec93e98..ac22b8a553 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -51,15 +51,11 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - logRequestBodyReadFailure(reqLog, c.Request, err) - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index dbcd7c9979..2813578457 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -48,14 +48,11 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/openai_gateway_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go index 050a5057bd..57572c2016 100644 --- a/backend/internal/handler/openai_gateway_count_tokens.go +++ b/backend/internal/handler/openai_gateway_count_tokens.go @@ -42,14 +42,11 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 || !gjson.ValidBytes(body) { @@ -138,14 +135,12 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { func (h *OpenAIGatewayHandler) GrokCountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + bodyLog := requestLogger(c, "handler.openai_gateway.grok_count_tokens") + if handleRequestBodyReadError(c, bodyLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(bodyLog, c.Request, err) + h.anthropicErrorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { @@ -211,14 +206,11 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.anthropicErrorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index daad104171..05d9ab3191 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -424,15 +424,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - logRequestBodyReadFailure(reqLog, c.Request, err) - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } @@ -1210,14 +1206,11 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.anthropicErrorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index a8e6413e7b..9510fb060b 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -50,14 +50,11 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if handleRequestBodyReadError(c, err) { + if handleRequestBodyReadError(c, reqLog, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) - return - } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + status, message := requestBodyReadFailure(reqLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if len(body) == 0 { diff --git a/backend/internal/handler/request_body_limit.go b/backend/internal/handler/request_body_limit.go index 4fd1aa13b9..a52bb0bfb4 100644 --- a/backend/internal/handler/request_body_limit.go +++ b/backend/internal/handler/request_body_limit.go @@ -1,7 +1,6 @@ package handler import ( - "errors" "fmt" "net/http" @@ -9,26 +8,24 @@ import ( pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/gin-gonic/gin" + "go.uber.org/zap" ) // handleRequestBodyReadError handles cancellation and temporary capacity errors // before callers classify malformed or oversized request bodies. -func handleRequestBodyReadError(c *gin.Context, err error) bool { - if err != nil && failoverClientGone(c) { +// +// A read deadline on HTTP/1 also cancels the request context, so a body read +// timeout is left to requestBodyReadFailure (408) instead of being reported as +// a client that went away (499). +func handleRequestBodyReadError(c *gin.Context, reqLog *zap.Logger, err error) bool { + if err != nil && !pkghttputil.IsRequestBodyReadTimeout(err) && failoverClientGone(c) { + logRequestBodyReadFailure(reqLog, pkghttputil.DescribeRequestBodyReadFailure(c.Request, err)) c.Abort() return true } return middleware2.RejectRequestBodyMemoryOverload(c, err) } -func extractMaxBytesError(err error) (*http.MaxBytesError, bool) { - var maxErr *http.MaxBytesError - if errors.As(err, &maxErr) { - return maxErr, true - } - return nil, false -} - func formatBodyLimit(limit int64) string { const mb = 1024 * 1024 if limit >= mb { diff --git a/backend/internal/handler/request_body_limit_test.go b/backend/internal/handler/request_body_limit_test.go index 826657cd1a..bbb3d2a070 100644 --- a/backend/internal/handler/request_body_limit_test.go +++ b/backend/internal/handler/request_body_limit_test.go @@ -4,8 +4,10 @@ import ( "bytes" "context" "io" + "net" "net/http" "net/http/httptest" + "os" "testing" "github.com/Wei-Shaw/sub2api/internal/server/middleware" @@ -22,15 +24,8 @@ func TestRequestBodyLimitTooLarge(t *testing.T) { router.POST("/test", func(c *gin.Context) { _, err := io.ReadAll(c.Request.Body) if err != nil { - if maxErr, ok := extractMaxBytesError(err); ok { - c.JSON(http.StatusRequestEntityTooLarge, gin.H{ - "error": buildBodyTooLargeMessage(maxErr.Limit), - }) - return - } - c.JSON(http.StatusBadRequest, gin.H{ - "error": "read_failed", - }) + status, message := requestBodyReadFailure(nil, c.Request, err) + c.JSON(status, gin.H{"error": message}) return } c.JSON(http.StatusOK, gin.H{"ok": true}) @@ -50,10 +45,15 @@ func TestHandleRequestBodyReadErrorCancellation(t *testing.T) { name string cancelled bool committed bool + readErr error + handled bool }{ - {name: "cancelled", cancelled: true}, - {name: "cancelled_after_commit", cancelled: true, committed: true}, + {name: "cancelled", cancelled: true, handled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true, handled: true}, {name: "ordinary_read_error"}, + // An HTTP/1 read deadline also cancels the request context; the + // timeout must reach requestBodyReadFailure (408). + {name: "read_timeout_with_cancelled_context", cancelled: true, readErr: &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}}, } { t.Run(tc.name, func(t *testing.T) { recorder := httptest.NewRecorder() @@ -69,10 +69,14 @@ func TestHandleRequestBodyReadErrorCancellation(t *testing.T) { require.NoError(t, err) } bodyBefore := recorder.Body.String() - require.Equal(t, tc.cancelled, handleRequestBodyReadError(c, io.ErrUnexpectedEOF)) - require.Equal(t, tc.cancelled, c.IsAborted()) + readErr := tc.readErr + if readErr == nil { + readErr = io.ErrUnexpectedEOF + } + require.Equal(t, tc.handled, handleRequestBodyReadError(c, nil, readErr)) + require.Equal(t, tc.handled, c.IsAborted()) status := http.StatusOK - if tc.cancelled && !tc.committed { + if tc.handled && !tc.committed { status = statusClientClosedRequest } require.Equal(t, status, c.Writer.Status()) diff --git a/backend/internal/handler/request_body_read_log.go b/backend/internal/handler/request_body_read_log.go index 5c6d73d934..0068c79212 100644 --- a/backend/internal/handler/request_body_read_log.go +++ b/backend/internal/handler/request_body_read_log.go @@ -1,79 +1,30 @@ package handler import ( - "context" - "errors" - "io" - "net" "net/http" - "strings" - "syscall" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "go.uber.org/zap" ) -// logRequestBodyReadFailure records a bounded, payload-free reason for a body -// read failure. Clients continue to receive the stable generic error message; -// operators get enough information to distinguish compression failures from a -// disconnected/truncated upload without logging request content. -func logRequestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) { - if reqLog == nil || err == nil { - return +// requestBodyReadFailure maps a request body read error to the response status +// and message. Read timeouts (408) are no longer reported as malformed +// requests; other read failures keep the stable generic 400 message. Failures +// other than the configured size limit are logged with bounded, payload-free +// diagnostics (kind, declared length, bytes received and read duration) so +// operators can tell a stalled or slow upload from a broken client without +// logging request content. +func requestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) (int, string) { + failure := pkghttputil.DescribeRequestBodyReadFailure(req, err) + if failure.Kind == pkghttputil.RequestBodyReadErrorMaxBytes { + return failure.Status, buildBodyTooLargeMessage(failure.MaxBytesLimit) } - - contentLength := int64(-1) - contentEncoding := "identity" - if req != nil { - contentLength = req.ContentLength - contentEncoding = requestContentEncodingCategory(req.Header.Get("Content-Encoding")) - } - - reqLog.Warn("read request body failed", - zap.String("error_kind", requestBodyReadErrorKind(err)), - zap.String("content_encoding", contentEncoding), - zap.Int64("content_length", contentLength), - ) + logRequestBodyReadFailure(reqLog, failure) + return failure.Status, failure.Message } -func requestContentEncodingCategory(value string) string { - switch strings.ToLower(strings.TrimSpace(value)) { - case "", "identity": - return "identity" - case "gzip", "x-gzip": - return "gzip" - case "zstd": - return "zstd" - case "deflate": - return "deflate" - default: - return "other" +func logRequestBodyReadFailure(reqLog *zap.Logger, failure pkghttputil.RequestBodyReadFailure) { + if reqLog != nil { + reqLog.Warn("read request body failed", failure.LogFields()...) } } - -func requestBodyReadErrorKind(err error) string { - if err == nil { - return "none" - } - var maxErr *http.MaxBytesError - if errors.As(err, &maxErr) { - return "max_bytes" - } - lower := strings.ToLower(err.Error()) - if strings.Contains(lower, "decode content-encoding") { - if strings.Contains(lower, "unsupported content-encoding") { - return "unsupported_content_encoding" - } - return "decode_content_encoding" - } - if errors.Is(err, context.Canceled) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) { - return "client_disconnect" - } - if errors.Is(err, io.ErrUnexpectedEOF) { - return "truncated_body" - } - var netErr net.Error - if errors.As(err, &netErr) { - return "transport" - } - return "io_read" -} diff --git a/backend/internal/handler/request_body_read_log_test.go b/backend/internal/handler/request_body_read_log_test.go index 8a8d21f100..f9eef560a4 100644 --- a/backend/internal/handler/request_body_read_log_test.go +++ b/backend/internal/handler/request_body_read_log_test.go @@ -3,25 +3,36 @@ package handler import ( + "context" + "encoding/json" "errors" "fmt" "io" + "net" "net/http" + "net/http/httptest" + "os" "strings" "testing" + "testing/iotest" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" ) -func TestLogRequestBodyReadFailureClassifiesWithoutPayload(t *testing.T) { +func TestRequestBodyReadFailureLogsWithoutPayload(t *testing.T) { log, logs := newObservedLogger(t) req, err := http.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader("secret-payload-marker")) require.NoError(t, err) req.Header.Set("Content-Encoding", "gzip") req.ContentLength = 21 - logRequestBodyReadFailure(log, req, errors.New(`decode Content-Encoding "gzip": unexpected EOF secret-payload-marker`)) + status, message := requestBodyReadFailure(log, req, errors.New(`decode Content-Encoding "gzip": unexpected EOF secret-payload-marker`)) + require.Equal(t, http.StatusBadRequest, status) + require.Equal(t, "Failed to read request body", message) entries := logs.All() require.Len(t, entries, 1) require.Equal(t, "read request body failed", entries[0].Message) @@ -32,9 +43,97 @@ func TestLogRequestBodyReadFailureClassifiesWithoutPayload(t *testing.T) { require.NotContains(t, entries[0].Message+fmt.Sprint(fields), "secret-payload-marker") } -func TestRequestBodyReadErrorKind(t *testing.T) { - require.Equal(t, "unsupported_content_encoding", requestBodyReadErrorKind(errors.New(`decode Content-Encoding "br": unsupported Content-Encoding`))) - require.Equal(t, "truncated_body", requestBodyReadErrorKind(io.ErrUnexpectedEOF)) - require.Equal(t, "max_bytes", requestBodyReadErrorKind(&http.MaxBytesError{Limit: 10})) - require.Equal(t, "other", requestContentEncodingCategory("private-payload-marker")) +func TestRequestBodyReadFailureKeepsBodyLimitMessageWithoutLogging(t *testing.T) { + log, logs := newObservedLogger(t) + status, message := requestBodyReadFailure(log, nil, &http.MaxBytesError{Limit: 2 << 20}) + require.Equal(t, http.StatusRequestEntityTooLarge, status) + require.Equal(t, buildBodyTooLargeMessage(2<<20), message) + require.Empty(t, logs.All()) +} + +// cancelOnReadErr models net/http on HTTP/1: a failed body read cancels the +// request context before the error reaches the handler. +type cancelOnReadErr struct { + err error + cancel context.CancelFunc +} + +func (r cancelOnReadErr) Read([]byte) (int, error) { + r.cancel() + return 0, r.err +} + +// The Anthropic /v1/messages handler reads the full body before it knows the +// model or account. A failed read must report why instead of a generic 400. +func TestGatewayMessagesClassifiesRequestBodyReadFailures(t *testing.T) { + gin.SetMode(gin.TestMode) + deadlineErr := &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded} + + tests := []struct { + name string + readErr error + cancelCtx bool + wantStatus int + wantMessage string + }{ + {"h2 read timeout", deadlineErr, false, http.StatusRequestTimeout, "Timed out reading request body"}, + // net/http cancels the request context when an HTTP/1 read deadline + // fires; this is still a timeout, not a client that went away. + {"http1 read timeout", deadlineErr, true, http.StatusRequestTimeout, "Timed out reading request body"}, + // A client that went away gets no body, matching the failover path. + {"client disconnect", io.ErrUnexpectedEOF, true, 499, ""}, + {"truncated body", io.ErrUnexpectedEOF, false, http.StatusBadRequest, "Failed to read request body"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + failing := iotest.ErrReader(tc.readErr) + if tc.cancelCtx { + failing = cancelOnReadErr{err: tc.readErr, cancel: cancel} + } + body := io.MultiReader(strings.NewReader(`{"model":"claude-sonnet-4-5","messages":[`), failing) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", body).WithContext(ctx) + req.ContentLength = 1 << 20 + c.Request = req + groupID := int64(1) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) + + (&GatewayHandler{}).Messages(c) + + require.Equal(t, tc.wantStatus, c.Writer.Status()) + if tc.wantMessage == "" { + require.Empty(t, rec.Body.String()) + return + } + var resp struct { + Type string `json:"type"` + Error struct { + Type string `json:"type"` + Message string `json:"message"` + } `json:"error"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + require.Equal(t, "error", resp.Type) + require.Equal(t, "invalid_request_error", resp.Error.Type) + require.Equal(t, tc.wantMessage, resp.Error.Message) + }) + } +} + +// Google-format errors carry no type field; body read failures must still be +// attributed to the client request rather than the platform. +func TestGeminiRequestBodyReadTimeoutClassifiedAsClient(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + c.Request.Body = io.NopCloser(iotest.ErrReader(&net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded})) + readGeminiCachedContentBody(c) + }) + require.Equal(t, http.StatusRequestTimeout, entry.StatusCode) + require.Equal(t, "invalid_request_error", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.Equal(t, "P3", entry.Severity) } diff --git a/backend/internal/pkg/googleapi/status.go b/backend/internal/pkg/googleapi/status.go index 18a0eacb41..692843d0e7 100644 --- a/backend/internal/pkg/googleapi/status.go +++ b/backend/internal/pkg/googleapi/status.go @@ -14,6 +14,8 @@ func HTTPStatusToGoogleStatus(status int) string { return "PERMISSION_DENIED" case http.StatusNotFound: return "NOT_FOUND" + case http.StatusRequestTimeout: + return "DEADLINE_EXCEEDED" case http.StatusTooManyRequests: return "RESOURCE_EXHAUSTED" case 499: // client closed request diff --git a/backend/internal/pkg/googleapi/status_test.go b/backend/internal/pkg/googleapi/status_test.go index 123515be0f..030130f751 100644 --- a/backend/internal/pkg/googleapi/status_test.go +++ b/backend/internal/pkg/googleapi/status_test.go @@ -14,6 +14,7 @@ func TestHTTPStatusToGoogleStatus(t *testing.T) { {http.StatusUnauthorized, "UNAUTHENTICATED"}, {http.StatusForbidden, "PERMISSION_DENIED"}, {http.StatusNotFound, "NOT_FOUND"}, + {http.StatusRequestTimeout, "DEADLINE_EXCEEDED"}, {http.StatusTooManyRequests, "RESOURCE_EXHAUSTED"}, {499, "CANCELLED"}, {http.StatusBadGateway, "INTERNAL"}, diff --git a/backend/internal/pkg/httputil/body.go b/backend/internal/pkg/httputil/body.go index 2923520dde..901057c487 100644 --- a/backend/internal/pkg/httputil/body.go +++ b/backend/internal/pkg/httputil/body.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "strings" + "time" "github.com/klauspost/compress/zstd" ) @@ -107,8 +108,13 @@ func readRequestBodyWithBudget(req *http.Request) (requestBodyBuffer, error) { } } + startedAt := time.Now() raw, err := readRequestBodyChunksWithBudget(req.Context(), req.Body, capHint, req.ContentLength) if err != nil { + var readErr *RequestBodyReadError + if errors.As(err, &readErr) { + readErr.Elapsed = time.Since(startedAt) + } return requestBodyBuffer{}, err } @@ -156,18 +162,20 @@ func readRequestBodyChunksWithBudget(ctx context.Context, reader io.Reader, init n := 0 var err error for n < len(chunk) && err == nil { - if err := ctx.Err(); err != nil { - return requestBodyBuffer{}, err + if ctxErr := ctx.Err(); ctxErr != nil { + return requestBodyBuffer{}, &RequestBodyReadError{Err: ctxErr, BytesRead: int64(total + n)} } var read int read, err = reader.Read(chunk[n:]) n += read } - if err := ctx.Err(); err != nil { - return requestBodyBuffer{}, err - } + // Report the read error before the context: on HTTP/1 a read deadline + // also cancels the request context, which would hide the timeout. if err != nil && err != io.EOF { - return requestBodyBuffer{}, err + return requestBodyBuffer{}, &RequestBodyReadError{Err: err, BytesRead: int64(total + n)} + } + if ctxErr := ctx.Err(); ctxErr != nil { + return requestBodyBuffer{}, &RequestBodyReadError{Err: ctxErr, BytesRead: int64(total + n)} } if n > 0 { chunks = append(chunks, chunk[:n]) diff --git a/backend/internal/pkg/httputil/body_read_error.go b/backend/internal/pkg/httputil/body_read_error.go new file mode 100644 index 0000000000..5acaa741db --- /dev/null +++ b/backend/internal/pkg/httputil/body_read_error.go @@ -0,0 +1,194 @@ +package httputil + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "os" + "strings" + "syscall" + "time" + + "go.uber.org/zap" +) + +// Stable, payload-free labels for request body read failures. +const ( + RequestBodyReadErrorMaxBytes = "max_bytes" + RequestBodyReadErrorTimeout = "read_timeout" + RequestBodyReadErrorClientDisconnect = "client_disconnect" + RequestBodyReadErrorTruncated = "truncated_body" + RequestBodyReadErrorDecodeContentEncoding = "decode_content_encoding" + RequestBodyReadErrorUnsupportedContentEncoding = "unsupported_content_encoding" + RequestBodyReadErrorTransport = "transport" + RequestBodyReadErrorIO = "io_read" +) + +// StatusClientClosedRequest is the non-standard status recorded when the client +// goes away before the server responds. +const StatusClientClosedRequest = 499 + +// RequestBodyReadError annotates a failed request body read with progress +// counters. It never carries request content. +type RequestBodyReadError struct { + Err error + BytesRead int64 + Elapsed time.Duration +} + +func (e *RequestBodyReadError) Error() string { return e.Err.Error() } + +func (e *RequestBodyReadError) Unwrap() error { return e.Err } + +// RequestBodyReadFailure is the response and the payload-free diagnostics for a +// failed request body read. +type RequestBodyReadFailure struct { + Kind string + Status int + Message string + // MaxBytesLimit is set when Kind is RequestBodyReadErrorMaxBytes. + MaxBytesLimit int64 + + contentLength int64 + contentEncoding string + protocol string + chunked bool + bytesRead int64 + elapsed time.Duration +} + +// DescribeRequestBodyReadFailure classifies a request body read error. Timeouts +// and client disconnects get their own status codes so they are not reported +// as malformed requests; other failures keep the generic 400 response. +func DescribeRequestBodyReadFailure(req *http.Request, err error) RequestBodyReadFailure { + failure := RequestBodyReadFailure{ + Kind: classifyRequestBodyReadError(req, err), + contentLength: -1, + contentEncoding: "identity", + bytesRead: -1, + } + if req != nil { + failure.contentLength = req.ContentLength + failure.contentEncoding = RequestContentEncodingCategory(req.Header.Get("Content-Encoding")) + failure.protocol = req.Proto + failure.chunked = len(req.TransferEncoding) > 0 + } + var readErr *RequestBodyReadError + if errors.As(err, &readErr) { + failure.bytesRead = readErr.BytesRead + failure.elapsed = readErr.Elapsed + } + + switch failure.Kind { + case RequestBodyReadErrorMaxBytes: + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + failure.MaxBytesLimit = maxErr.Limit + } + failure.Status = http.StatusRequestEntityTooLarge + failure.Message = "Request body is too large" + case RequestBodyReadErrorTimeout: + failure.Status = http.StatusRequestTimeout + failure.Message = "Timed out reading request body" + case RequestBodyReadErrorClientDisconnect: + failure.Status = StatusClientClosedRequest + failure.Message = "Client closed the connection before the request body was received" + default: + failure.Status = http.StatusBadRequest + failure.Message = "Failed to read request body" + } + return failure +} + +// LogFields returns diagnostics that never include request content or error +// text, which may embed peer addresses or decoder input. +func (f RequestBodyReadFailure) LogFields() []zap.Field { + fields := []zap.Field{ + zap.String("error_kind", f.Kind), + zap.Int("status", f.Status), + zap.String("protocol", f.protocol), + zap.String("content_encoding", f.contentEncoding), + zap.Int64("content_length", f.contentLength), + zap.Bool("chunked", f.chunked), + } + if f.bytesRead >= 0 { + fields = append(fields, + zap.Int64("bytes_read", f.bytesRead), + zap.Int64("read_ms", f.elapsed.Milliseconds()), + ) + } + return fields +} + +func classifyRequestBodyReadError(req *http.Request, err error) string { + if err == nil { + return RequestBodyReadErrorIO + } + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + return RequestBodyReadErrorMaxBytes + } + lower := strings.ToLower(err.Error()) + if strings.Contains(lower, "decode content-encoding") { + if strings.Contains(lower, "unsupported content-encoding") { + return RequestBodyReadErrorUnsupportedContentEncoding + } + return RequestBodyReadErrorDecodeContentEncoding + } + // Check timeouts first: on HTTP/1 a read deadline also cancels the request + // context, which would otherwise look like a client disconnect. + if IsRequestBodyReadTimeout(err) { + return RequestBodyReadErrorTimeout + } + if requestBodyClientGone(req, err, lower) { + return RequestBodyReadErrorClientDisconnect + } + // HTTP/2 reports an END_STREAM that arrives before Content-Length bytes + // with "request declared a Content-Length of N but only wrote M bytes". + if errors.Is(err, io.ErrUnexpectedEOF) || strings.Contains(lower, "request declared a content-length") { + return RequestBodyReadErrorTruncated + } + var netErr net.Error + if errors.As(err, &netErr) { + return RequestBodyReadErrorTransport + } + return RequestBodyReadErrorIO +} + +// IsRequestBodyReadTimeout reports whether a body read failed because a read +// deadline expired (for example WithBodyReadTimeout's per-read deadline). +func IsRequestBodyReadTimeout(err error) bool { + var netErr net.Error + return errors.Is(err, os.ErrDeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) +} + +func requestBodyClientGone(req *http.Request, err error, lowerErr string) bool { + if errors.Is(err, context.Canceled) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) { + return true + } + // HTTP/2 reports a closed client connection with this message. + if strings.Contains(lowerErr, "client disconnected") { + return true + } + // net/http cancels the request context when the connection fails, so an + // unexpected EOF with a canceled context is a disconnect, not a short body. + return req != nil && errors.Is(req.Context().Err(), context.Canceled) +} + +// RequestContentEncodingCategory maps Content-Encoding to a bounded label. +func RequestContentEncodingCategory(value string) string { + switch strings.ToLower(strings.TrimSpace(value)) { + case "", "identity": + return "identity" + case "gzip", "x-gzip": + return "gzip" + case "zstd": + return "zstd" + case "deflate": + return "deflate" + default: + return "other" + } +} diff --git a/backend/internal/pkg/httputil/body_read_error_test.go b/backend/internal/pkg/httputil/body_read_error_test.go new file mode 100644 index 0000000000..a752616553 --- /dev/null +++ b/backend/internal/pkg/httputil/body_read_error_test.go @@ -0,0 +1,124 @@ +package httputil + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "strings" + "syscall" + "testing" + "testing/iotest" + "time" + + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" +) + +func TestReadRequestBodyWithPreallocReportsProgressOnReadError(t *testing.T) { + reader := io.MultiReader(bytes.NewReader([]byte("partial")), iotest.ErrReader(io.ErrUnexpectedEOF)) + req := &http.Request{Body: io.NopCloser(reader), ContentLength: 100, Header: make(http.Header)} + + got, err := ReadRequestBodyWithPrealloc(req) + + var readErr *RequestBodyReadError + if got != nil || !errors.As(err, &readErr) || !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("read error lost its cause or progress: body=%q err=%v", got, err) + } + if readErr.BytesRead != int64(len("partial")) || readErr.Elapsed < 0 { + t.Fatalf("unexpected progress: bytes=%d elapsed=%s", readErr.BytesRead, readErr.Elapsed) + } +} + +func TestDescribeRequestBodyReadFailure(t *testing.T) { + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + deadlineErr := &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded} + resetErr := &net.OpError{Op: "read", Net: "tcp", Err: os.NewSyscallError("read", syscall.ECONNRESET)} + + tests := []struct { + name string + ctx context.Context + err error + wantKind string + wantStatus int + }{ + // net/http cancels the request context on an HTTP/1 read timeout too; + // the timeout must still win over the disconnect classification. + {"http1 read deadline", canceledCtx, &RequestBodyReadError{Err: deadlineErr}, RequestBodyReadErrorTimeout, http.StatusRequestTimeout}, + {"http2 read deadline", context.Background(), fmt.Errorf("%w", os.ErrDeadlineExceeded), RequestBodyReadErrorTimeout, http.StatusRequestTimeout}, + {"http1 disconnect mid body", canceledCtx, &RequestBodyReadError{Err: io.ErrUnexpectedEOF}, RequestBodyReadErrorClientDisconnect, StatusClientClosedRequest}, + {"connection reset", context.Background(), resetErr, RequestBodyReadErrorClientDisconnect, StatusClientClosedRequest}, + {"http2 client disconnected", context.Background(), errors.New("client disconnected"), RequestBodyReadErrorClientDisconnect, StatusClientClosedRequest}, + {"truncated body", context.Background(), &RequestBodyReadError{Err: io.ErrUnexpectedEOF}, RequestBodyReadErrorTruncated, http.StatusBadRequest}, + {"http2 short body", context.Background(), errors.New("request declared a Content-Length of 10 but only wrote 3 bytes"), RequestBodyReadErrorTruncated, http.StatusBadRequest}, + {"max bytes", context.Background(), &RequestBodyReadError{Err: &http.MaxBytesError{Limit: 64}}, RequestBodyReadErrorMaxBytes, http.StatusRequestEntityTooLarge}, + {"decode", context.Background(), errors.New(`decode Content-Encoding "gzip": unexpected EOF`), RequestBodyReadErrorDecodeContentEncoding, http.StatusBadRequest}, + {"unsupported encoding", context.Background(), errors.New(`decode Content-Encoding "br": unsupported Content-Encoding`), RequestBodyReadErrorUnsupportedContentEncoding, http.StatusBadRequest}, + {"other", context.Background(), errors.New("boom"), RequestBodyReadErrorIO, http.StatusBadRequest}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + req, err := http.NewRequestWithContext(tc.ctx, http.MethodPost, "/v1/messages", nil) + if err != nil { + t.Fatal(err) + } + got := DescribeRequestBodyReadFailure(req, tc.err) + if got.Kind != tc.wantKind || got.Status != tc.wantStatus || got.Message == "" { + t.Fatalf("got kind=%q status=%d message=%q, want kind=%q status=%d", got.Kind, got.Status, got.Message, tc.wantKind, tc.wantStatus) + } + }) + } + + if got := DescribeRequestBodyReadFailure(nil, &http.MaxBytesError{Limit: 64}); got.MaxBytesLimit != 64 { + t.Fatalf("max bytes limit not reported: %d", got.MaxBytesLimit) + } + if got := DescribeRequestBodyReadFailure(nil, errors.New("boom")); got.Message != "Failed to read request body" { + t.Fatalf("generic failures must keep the stable message, got %q", got.Message) + } +} + +func TestRequestBodyReadFailureLogFieldsArePayloadFree(t *testing.T) { + req, err := http.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader("secret-payload-marker")) + if err != nil { + t.Fatal(err) + } + req.ContentLength = 4096 + req.Header.Set("Content-Encoding", "zstd") + readErr := &RequestBodyReadError{ + Err: &net.OpError{Op: "read", Net: "tcp", Err: errors.New("10.0.0.1 secret-payload-marker")}, + BytesRead: 1024, + Elapsed: 1500 * time.Millisecond, + } + + core, logs := observer.New(zap.WarnLevel) + zap.New(core).Warn("read request body failed", DescribeRequestBodyReadFailure(req, readErr).LogFields()...) + + entries := logs.All() + if len(entries) != 1 { + t.Fatalf("expected one log entry, got %d", len(entries)) + } + fields := entries[0].ContextMap() + want := map[string]any{ + "error_kind": RequestBodyReadErrorTransport, + "status": int64(http.StatusBadRequest), + "content_encoding": "zstd", + "content_length": int64(4096), + "bytes_read": int64(1024), + "read_ms": int64(1500), + "chunked": false, + "protocol": "HTTP/1.1", + } + for key, value := range want { + if fields[key] != value { + t.Fatalf("field %s = %#v, want %#v (all: %v)", key, fields[key], value, fields) + } + } + if strings.Contains(fmt.Sprint(fields), "secret-payload-marker") || strings.Contains(fmt.Sprint(fields), "10.0.0.1") { + t.Fatalf("log fields leaked error text: %v", fields) + } +} diff --git a/backend/internal/server/middleware/group_model_allowlist.go b/backend/internal/server/middleware/group_model_allowlist.go index 3c8c5d0628..d77d22541a 100644 --- a/backend/internal/server/middleware/group_model_allowlist.go +++ b/backend/internal/server/middleware/group_model_allowlist.go @@ -1,7 +1,6 @@ package middleware import ( - "errors" "fmt" "net/http" "strings" @@ -113,18 +112,10 @@ func isResponsesWebSocketRoute(c *gin.Context) bool { func groupModelAllowlistModelsFromBody(c *gin.Context) ([]string, bool) { body, err := httputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if RejectRequestBodyReadError(c, err) { + if RejectRequestBodyReadError(c, "middleware.group_model_allowlist", err) { return nil, false } - status := http.StatusBadRequest - message := "Failed to read request body" - var maxErr *http.MaxBytesError - if errors.As(err, &maxErr) { - status = http.StatusRequestEntityTooLarge - message = "Request body is too large" - } - c.JSON(status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}}) - c.Abort() + AbortWithRequestBodyReadFailure(c, "middleware.group_model_allowlist", err) return nil, false } requestmodel.ResetRequestBody(c.Request, body) diff --git a/backend/internal/server/middleware/request_body_memory.go b/backend/internal/server/middleware/request_body_memory.go index d66034f996..70666849fb 100644 --- a/backend/internal/server/middleware/request_body_memory.go +++ b/backend/internal/server/middleware/request_body_memory.go @@ -11,8 +11,11 @@ import ( // RejectRequestBodyReadError handles early ingress termination before the route // handler runs. Cancelled clients have no response body and an uncommitted // response is marked 499, matching the gateway handler's cancellation path. -func RejectRequestBodyReadError(c *gin.Context, err error) bool { - if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil { +// A read deadline on HTTP/1 also cancels the request context; timeouts are left +// to AbortWithRequestBodyReadFailure (408). +func RejectRequestBodyReadError(c *gin.Context, component string, err error) bool { + if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil && !pkghttputil.IsRequestBodyReadTimeout(err) { + logRequestBodyReadFailure(c, component, pkghttputil.DescribeRequestBodyReadFailure(c.Request, err)) if !c.Writer.Written() { c.Status(499) } diff --git a/backend/internal/server/middleware/request_body_memory_test.go b/backend/internal/server/middleware/request_body_memory_test.go index 30cff09a4e..67cda868ff 100644 --- a/backend/internal/server/middleware/request_body_memory_test.go +++ b/backend/internal/server/middleware/request_body_memory_test.go @@ -3,8 +3,10 @@ package middleware import ( "context" "io" + "net" "net/http" "net/http/httptest" + "os" "strings" "sync" "testing" @@ -66,10 +68,15 @@ func TestRejectRequestBodyReadErrorCancellation(t *testing.T) { name string cancelled bool committed bool + readErr error + handled bool }{ - {name: "cancelled", cancelled: true}, - {name: "cancelled_after_commit", cancelled: true, committed: true}, + {name: "cancelled", cancelled: true, handled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true, handled: true}, {name: "ordinary_read_error"}, + // An HTTP/1 read deadline also cancels the request context; the + // timeout must reach AbortWithRequestBodyReadFailure (408). + {name: "read_timeout_with_cancelled_context", cancelled: true, readErr: &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}}, } { t.Run(tc.name, func(t *testing.T) { recorder := httptest.NewRecorder() @@ -85,10 +92,14 @@ func TestRejectRequestBodyReadErrorCancellation(t *testing.T) { require.NoError(t, err) } bodyBefore := recorder.Body.String() - require.Equal(t, tc.cancelled, RejectRequestBodyReadError(c, io.ErrUnexpectedEOF)) - require.Equal(t, tc.cancelled, c.IsAborted()) + readErr := tc.readErr + if readErr == nil { + readErr = io.ErrUnexpectedEOF + } + require.Equal(t, tc.handled, RejectRequestBodyReadError(c, "test", readErr)) + require.Equal(t, tc.handled, c.IsAborted()) status := http.StatusOK - if tc.cancelled && !tc.committed { + if tc.handled && !tc.committed { status = 499 } require.Equal(t, status, c.Writer.Status()) diff --git a/backend/internal/server/middleware/request_body_read_failure.go b/backend/internal/server/middleware/request_body_read_failure.go new file mode 100644 index 0000000000..a41430a62f --- /dev/null +++ b/backend/internal/server/middleware/request_body_read_failure.go @@ -0,0 +1,24 @@ +package middleware + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// AbortWithRequestBodyReadFailure writes the shared response for a failed body +// read in middleware that inspects the body before the handler. It applies the +// same classification and payload-free diagnostics as the gateway handlers. +func AbortWithRequestBodyReadFailure(c *gin.Context, component string, err error) { + failure := httputil.DescribeRequestBodyReadFailure(c.Request, err) + if failure.Kind != httputil.RequestBodyReadErrorMaxBytes { + logRequestBodyReadFailure(c, component, failure) + } + c.AbortWithStatusJSON(failure.Status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": failure.Message}}) +} + +func logRequestBodyReadFailure(c *gin.Context, component string, failure httputil.RequestBodyReadFailure) { + fields := append([]zap.Field{zap.String("component", component)}, failure.LogFields()...) + logger.FromContext(c.Request.Context()).Warn("read request body failed", fields...) +} diff --git a/backend/internal/server/request_body_read_timeout_test.go b/backend/internal/server/request_body_read_timeout_test.go new file mode 100644 index 0000000000..0886aba544 --- /dev/null +++ b/backend/internal/server/request_body_read_timeout_test.go @@ -0,0 +1,163 @@ +//go:build unit + +package server + +import ( + "bufio" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const testBodyReadTimeout = 300 * time.Millisecond + +// bodyKindHandler reads the body through the shared gateway reader and reports +// the classified failure kind and status. +func bodyKindHandler(kinds chan<- string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := pkghttputil.ReadRequestBodyWithPrealloc(r) + if err != nil { + failure := pkghttputil.DescribeRequestBodyReadFailure(r, err) + if kinds != nil { + kinds <- failure.Kind + } + w.Header().Set("X-Body-Error", failure.Kind) + w.WriteHeader(failure.Status) + return + } + _, _ = io.WriteString(w, strconv.Itoa(len(body))) + }) +} + +func newBodyReadTimeoutTestServer(t *testing.T, h http.Handler, h2c bool) (*httptest.Server, *http.Client) { + t.Helper() + ts := httptest.NewUnstartedServer(pkghttputil.WithBodyReadTimeout(h, testBodyReadTimeout)) + transport := &http.Transport{} + if h2c { + protocols := new(http.Protocols) + protocols.SetHTTP1(true) + protocols.SetUnencryptedHTTP2(true) + ts.Config.Protocols = protocols + clientProtocols := new(http.Protocols) + clientProtocols.SetUnencryptedHTTP2(true) + transport.Protocols = clientProtocols + } + ts.Start() + t.Cleanup(ts.Close) + t.Cleanup(transport.CloseIdleConnections) + return ts, &http.Client{Transport: transport, Timeout: 10 * time.Second} +} + +// A stalled upload is classified as a read timeout (408) over both protocols. +// On HTTP/1 the deadline also cancels the request context; the timeout must +// still win over the client-disconnect classification. +func TestBodyReadTimeoutClassifiedAsTimeout(t *testing.T) { + for _, h2c := range []bool{false, true} { + name := "http1" + if h2c { + name = "h2c" + } + t.Run(name, func(t *testing.T) { + ts, client := newBodyReadTimeoutTestServer(t, bodyKindHandler(nil), h2c) + pr, pw := io.Pipe() + defer func() { _ = pw.Close() }() + go func() { _, _ = pw.Write([]byte(`{"model":"x","messages":[`)) }() + req, err := http.NewRequest(http.MethodPost, ts.URL, pr) + require.NoError(t, err) + req.ContentLength = 1 << 20 + + start := time.Now() + resp, err := client.Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + + require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) + require.Equal(t, pkghttputil.RequestBodyReadErrorTimeout, resp.Header.Get("X-Body-Error")) + elapsed := time.Since(start) + require.GreaterOrEqual(t, elapsed, testBodyReadTimeout) + require.Less(t, elapsed, 5*time.Second) + }) + } +} + +// A client that disconnects mid-upload is still classified as a disconnect, +// using the real net/http error and context behavior. +func TestBodyReadClassifiesHTTP1ClientDisconnect(t *testing.T) { + kinds := make(chan string, 1) + ts, _ := newBodyReadTimeoutTestServer(t, bodyKindHandler(kinds), false) + conn, err := net.DialTimeout("tcp", ts.Listener.Addr().String(), time.Second) + require.NoError(t, err) + _, err = io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1000\r\n\r\nabc") + require.NoError(t, err) + time.Sleep(50 * time.Millisecond) + require.NoError(t, conn.Close()) + + select { + case kind := <-kinds: + require.Equal(t, pkghttputil.RequestBodyReadErrorClientDisconnect, kind) + case <-time.After(5 * time.Second): + t.Fatal("handler did not observe the disconnect") + } +} + +// End to end over a real HTTP/1 connection: a stalled Anthropic /v1/messages +// upload is answered with an Anthropic-format 408 after the configured body +// read timeout instead of an empty 499 or a generic 400. +func TestHTTPServerBodyReadTimeoutAnthropicMessages(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + groupID := int64(1) + r.POST("/v1/messages", func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) + c.Next() + }, (&handler.GatewayHandler{}).Messages) + cfg := ingressTestConfig() + cfg.Server.MaxRequestBodySize = 0 + cfg.Gateway.MaxBodySize = 0 + cfg.Gateway.RequestBodyReadTimeoutSeconds = 1 + addr, stop := serveIngressTestServer(t, ProvideHTTPServer(cfg, r)) + defer stop() + + conn, err := net.DialTimeout("tcp", addr, time.Second) + require.NoError(t, err) + defer func() { _ = conn.Close() }() + _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) + partial := `{"model":"claude-sonnet-4-5","max_tokens":1,"messages":[` + _, err = io.WriteString(conn, "POST /v1/messages HTTP/1.1\r\nHost: test\r\nContent-Type: application/json\r\nContent-Length: 1048576\r\n\r\n"+partial) + require.NoError(t, err) + + start := time.Now() + reader := bufio.NewReader(conn) + resp, err := http.ReadResponse(reader, nil) + require.NoError(t, err) + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + + require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) + elapsed := time.Since(start) + require.GreaterOrEqual(t, elapsed, 900*time.Millisecond) + require.Less(t, elapsed, 5*time.Second) + var payload struct { + Error struct { + Type string `json:"type"` + Message string `json:"message"` + } `json:"error"` + } + require.NoError(t, json.Unmarshal(body, &payload)) + require.Equal(t, "invalid_request_error", payload.Error.Type) + require.Equal(t, "Timed out reading request body", payload.Error.Message) + require.True(t, resp.Close, "connection with an unread body must not be reused") +} diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 3c1036921d..0e7dbef05a 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -1,7 +1,6 @@ package routes import ( - "errors" "net/http" "strings" @@ -564,18 +563,10 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - if middleware.RejectRequestBodyReadError(c, err) { + if middleware.RejectRequestBodyReadError(c, "middleware.composite_route", err) { return } - status := http.StatusBadRequest - message := "Failed to read request body" - var maxErr *http.MaxBytesError - if errors.As(err, &maxErr) { - status = http.StatusRequestEntityTooLarge - message = "Request body is too large" - } - c.JSON(status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}}) - c.Abort() + middleware.AbortWithRequestBodyReadFailure(c, "middleware.composite_route", err) return }