fix(billing): validate quantity parameters and harden quota calculations

Bound user-supplied count/duration parameters at request validation,
route ratio multipliers through guarded setters, and use saturating
int conversions in all quota math paths.
This commit is contained in:
CaIon
2026-07-07 00:21:06 +08:00
parent 45f0484dc1
commit d0bd8aac74
17 changed files with 293 additions and 19 deletions
+78
View File
@@ -2,6 +2,7 @@ package helper
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
@@ -10,6 +11,7 @@ import (
"testing"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/dto"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
@@ -69,3 +71,79 @@ func TestGetAndValidOpenAIImageRequestMultipartStream(t *testing.T) {
require.Contains(t, err.Error(), "invalid stream value")
})
}
// TestGetAndValidOpenAIImageRequestNBounds guards the billing invariant that
// the image generation count can never reach quota calculation with a value
// large enough to overflow int64 into a negative charge.
func TestGetAndValidOpenAIImageRequestNBounds(t *testing.T) {
gin.SetMode(gin.TestMode)
newJSONContext := func(t *testing.T, body string) *gin.Context {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewBufferString(body))
c.Request.Header.Set("Content-Type", "application/json")
return c
}
boundErr := fmt.Sprintf("n must be an integer between 1 and %d", dto.MaxImageN)
tests := []struct {
name string
body string
wantErr string
wantN uint
}{
{
name: "overflowed uint64 n is rejected",
body: `{"model":"gpt-image-1","prompt":"a cat","n":18446744073686646784}`,
wantErr: boundErr,
},
{
name: "n above max is rejected",
body: fmt.Sprintf(`{"model":"gpt-image-1","prompt":"a cat","n":%d}`, dto.MaxImageN+1),
wantErr: boundErr,
},
{
name: "n at max is accepted",
body: fmt.Sprintf(`{"model":"gpt-image-1","prompt":"a cat","n":%d}`, dto.MaxImageN),
wantN: dto.MaxImageN,
},
{
name: "absent n defaults to 1",
body: `{"model":"gpt-image-1","prompt":"a cat"}`,
wantN: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := newJSONContext(t, tt.body)
req, err := GetAndValidOpenAIImageRequest(c, relayconstant.RelayModeImagesGenerations)
if tt.wantErr != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
require.NotNil(t, req.N)
require.Equal(t, tt.wantN, *req.N)
})
}
t.Run("negative multipart n is rejected", func(t *testing.T) {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
require.NoError(t, writer.WriteField("model", "gpt-image-1"))
require.NoError(t, writer.WriteField("prompt", "edit this image"))
require.NoError(t, writer.WriteField("n", "-22904832"))
require.NoError(t, writer.Close())
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", &body)
c.Request.Header.Set("Content-Type", writer.FormDataContentType())
_, err := GetAndValidOpenAIImageRequest(c, relayconstant.RelayModeImagesEdits)
require.Error(t, err)
require.Contains(t, err.Error(), boundErr)
})
}
+11 -1
View File
@@ -155,7 +155,13 @@ func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageReq
c.Request.PostForm = formData
imageRequest.Prompt = formData.Get("prompt")
imageRequest.Model = formData.Get("model")
imageRequest.N = common.GetPointer(uint(common.String2Int(formData.Get("n"))))
if nValue := strings.TrimSpace(formData.Get("n")); nValue != "" {
n, err := strconv.Atoi(nValue)
if err != nil || n < 0 || n > dto.MaxImageN {
return nil, fmt.Errorf("n must be an integer between 1 and %d", dto.MaxImageN)
}
imageRequest.N = common.GetPointer(uint(n))
}
imageRequest.Quality = formData.Get("quality")
imageRequest.Size = formData.Get("size")
if streamValue := strings.TrimSpace(formData.Get("stream")); streamValue != "" {
@@ -201,6 +207,10 @@ func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageReq
return nil, errors.New("size an unexpected error occurred in the parameter, please use 'x' instead of the multiplication sign '×'")
}
if imageRequest.N != nil && *imageRequest.N > dto.MaxImageN {
return nil, fmt.Errorf("n must be an integer between 1 and %d", dto.MaxImageN)
}
// Not "256x256", "512x512", or "1024x1024"
if imageRequest.Model == "dall-e-2" || imageRequest.Model == "dall-e" {
if imageRequest.Size != "" && imageRequest.Size != "256x256" && imageRequest.Size != "512x512" && imageRequest.Size != "1024x1024" {