Files
sub2api/backend/internal/pkg/httputil/body_read_error.go
T
shaw ce86c1b306 fix(gateway): close bypasses found in the duplicate-field audit
An independent audit of the conflicting-field fix found, and running code
confirmed, the following. Each is fixed here.

- A JSON body labelled multipart/form-data skipped the check: the JSON
  branch was chosen from the Content-Type header, but JSON handlers never
  look at it. ConflictingField and FromBodyCandidates now detect JSON by
  content. The same header-only branch, and a UTF-8 BOM prefix (stripped by
  the handlers' lenient reader), also let a body bypass the group model
  allowlist on main; both are closed.
- Identical duplicates passed and the gateway's own sjson rewrites then
  split them: reasoning-effort downgrade, model mapping and the fast-policy
  service_tier delete only touch the first occurrence. Every repeated member
  is now rejected, whatever its value. Multipart rejects repeated scalar
  fields (model, n, size, ...) except list fields (name[], image,
  image[...], image_url).
- Nested case variants bound case-insensitively by struct-based protocol
  conversions ({"reasoning":{"effort":"low","Effort":"xhigh"}}). Members
  are now folded at every depth, except inside user-defined key spaces
  (JSON Schema properties/$defs, tool arguments, metadata, ...), where id
  and ID are distinct and only exact repeats are rejected.
- The recursive walker cost depth x size (1 MB at depth 9990: 1.6 s) and
  stored every key as a string (~16x the body). It is replaced by one
  linear byte scan with an explicit stack that compares 64-bit hashes
  (random per-process seed) of the decoded, folded names: 0.6 ms for the
  same body, ~3.7 GB/s on a Claude Code-shaped body. Subtrees deeper than
  10000 levels are bracket-counted, so later same-level members are still
  checked.
- text_max_body_size no longer bounded what group middleware buffered:
  the route-level limit ran after them. The limit is now chosen per route
  at group level.
- Body read failures in gateway middleware answered in the OpenAI shape
  with a different message than the handlers. They now use the entry
  protocol's shape and the handler's "limit is N" message. Rejections
  are recorded as ingress reason conflicting_request_fields.
- The middleware strips a leading BOM and restores the body, so composite
  routing and handlers parse the bytes that were checked.

Refs: GHSA-p3r4-jcm3-2hph
2026-11-20 10:50:32 +08:00

214 lines
6.9 KiB
Go

package httputil
import (
"context"
"errors"
"fmt"
"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
}
// ClientMessage returns the message shown to the client. A size-limit failure
// names the limit so callers can tell which limit they hit.
func (f RequestBodyReadFailure) ClientMessage() string {
if f.Kind == RequestBodyReadErrorMaxBytes {
return BodyTooLargeMessage(f.MaxBytesLimit)
}
return f.Message
}
// BodyTooLargeMessage formats the 413 message for a request body limit.
func BodyTooLargeMessage(limit int64) string {
const mb = 1024 * 1024
if limit >= mb {
return fmt.Sprintf("Request body too large, limit is %dMB", limit/mb)
}
return fmt.Sprintf("Request body too large, limit is %dB", limit)
}
// 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"
}
}