Files
new-api/controller/responses_websocket.go
RedwindA 19d435e7fd fix(relay): mask only the custom upstream address in error messages (#7822)
* fix(relay): mask only the upstream address in error messages

MaskSensitiveInfo masked every URL, domain and IPv4 in upstream error
messages, which garbled documentation links, email domains and dotted
identifiers that clients need to read.

It now takes the upstream addresses of the request: the channel base URL,
the origin the gateway actually dialed (recorded in doRequest, DoWssRequest,
the AWS SDK client and the Xunfei and Volcengine TTS dials, which covers
absolute Advanced Custom routes), the channel proxy and the environment
proxy. URLs and bare hostnames on those hosts and all IPv4 addresses are
masked; other URLs and domains stay readable. With no upstream address no
address is masked. Credentials are masked on every URL regardless of host:
api_key values, query values and userinfo.

The URL matcher also keeps quotes, colons and semicolons that follow a URL,
keeps parentheses and apostrophes inside it, masks an IPv4 URL host whole and
keeps a country-code TLD when the host has a port.

* fix(relay): keep preset official endpoints readable in masked errors

A channel on the base URL new-api presets for its type reaches a public
official endpoint, so its address is not masked. Only addresses the admin
configured are: a custom base URL, the origin of an Advanced Custom route,
and the channel and environment proxies. Preset hosts are compared with
their port so a configured localhost upstream stays apart from the Ollama
preset.

The origins recorded for the AWS SDK, Xunfei and Volcengine TTS dials and the
plugin allowedHosts masking are dropped: they are all official endpoints.

* fix(relay): mask IPv4 addresses and plugin allowed hosts in every error

IPv4 addresses in network errors include the gateway's own address, so they
are masked even when the channel uses a preset base URL. Task plugin build
failures mask the plugin's allowedHosts again: an installed plugin may point
them at private hosts.

* fix(relay): mask bracketed IPv6 addresses in errors

Go network errors write IPv6 addresses in brackets, as in
"dial tcp [2001:db8::1]:443". Like IPv4, they are the resolved upstream or
the gateway's own address, so they are masked on every error once the
bracketed content parses as an IP.
2026-10-15 15:49:45 +08:00

129 lines
4.5 KiB
Go

package controller
import (
"bytes"
"context"
"errors"
"net"
"net/http"
"sync"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/relay"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/gin-gonic/gin"
)
type responsesWSRequestContextKey struct{}
type responsesWSRequestState struct {
requestID string
handle func(*gin.Context) *types.NewAPIError
apiError *types.NewAPIError
}
// Each response.create runs the ordinary request middleware to completion,
// without routing another HTTP request or retaining a pooled Gin context.
var responsesWSRequestEngine = sync.OnceValue(func() *gin.Engine {
engine := gin.New()
engine.ForwardedByClientIP = false
_ = engine.SetTrustedProxies(nil)
engine.POST("/v1/responses", func(c *gin.Context) {
state := c.Request.Context().Value(responsesWSRequestContextKey{}).(*responsesWSRequestState)
c.Set(common.RequestIdKey, state.requestID)
common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
c.Next()
}, middleware.BodyStorageCleanup(), middleware.TokenAuth(), middleware.ModelRequestRateLimit(), func(c *gin.Context) {
state := c.Request.Context().Value(responsesWSRequestContextKey{}).(*responsesWSRequestState)
state.apiError = state.handle(c)
if state.apiError != nil {
status := state.apiError.StatusCode
if status < http.StatusBadRequest {
status = http.StatusInternalServerError
}
c.Status(status)
}
})
return engine
})
type responsesWSResponseWriter struct {
header http.Header
status int
body bytes.Buffer
}
func (w *responsesWSResponseWriter) Header() http.Header {
return w.header
}
func (w *responsesWSResponseWriter) WriteHeader(status int) {
if w.status == 0 {
w.status = status
}
}
func (w *responsesWSResponseWriter) Write(data []byte) (int, error) {
w.WriteHeader(http.StatusOK)
return w.body.Write(data)
}
func newResponsesWSRequestRunner(c *gin.Context) relay.ResponsesWSRequestRunner {
// Capture credentials before channel selection or header overrides. Resolve
// the peer once with the public router's trusted-proxy configuration.
headers := c.Request.Header.Clone()
for _, name := range []string{"Connection", "Upgrade", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Sec-WebSocket-Extensions", "Sec-WebSocket-Protocol", "Content-Length", "Content-Encoding"} {
headers.Del(name)
}
remoteAddr := net.JoinHostPort(c.ClientIP(), "0")
return func(request *http.Request, requestID string, handle func(*gin.Context) *types.NewAPIError) *types.NewAPIError {
state := &responsesWSRequestState{requestID: requestID, handle: handle}
ctx := context.WithValue(request.Context(), responsesWSRequestContextKey{}, state)
ctx = context.WithValue(ctx, common.RequestIdKey, requestID)
request = request.Clone(ctx)
request.Method = http.MethodPost
request.URL.Path = "/v1/responses"
request.URL.RawPath = ""
request.Header = headers.Clone()
request.Header.Set("Content-Type", "application/json")
request.RemoteAddr = remoteAddr
response := &responsesWSResponseWriter{header: make(http.Header)}
responsesWSRequestEngine().ServeHTTP(response, request)
if state.apiError != nil {
return state.apiError
}
if response.status < http.StatusBadRequest {
return nil
}
var body struct {
Error *types.OpenAIError `json:"error"`
}
if common.Unmarshal(response.body.Bytes(), &body) == nil && body.Error != nil {
return types.WithOpenAIError(*body.Error, response.status, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
}
// A rejection without an OpenAI error body keeps its HTTP status text.
return types.NewErrorWithStatusCode(errors.New(http.StatusText(response.status)), types.ErrorCodeInvalidRequest, response.status, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
}
}
func ResponsesWebSocket(c *gin.Context) {
requestID := c.GetString(common.RequestIdKey)
runner := newResponsesWSRequestRunner(c)
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
defer ws.Close()
if apiError := relay.ResponsesWebSocketHelper(c, ws, runner); apiError != nil {
logger.LogError(c, common.LogText("responses websocket relay error: %s", common.LocalLogPreview(apiError.Error())))
apiError.SetMessage(common.MessageWithRequestId(apiError.Error(), requestID))
helper.WssError(c, ws, apiError.ToOpenAIError(common.UpstreamAddresses(c)...))
}
}