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:
@@ -54,6 +54,12 @@ func oaiImage2AliImageRequest(info *relaycommon.RelayInfo, request dto.ImageRequ
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters may come from Extra["parameters"], bypassing the standard
|
||||
// top-level n validation; enforce the same bound before it becomes a
|
||||
// billing multiplier.
|
||||
if imageRequest.Parameters.N < 0 || imageRequest.Parameters.N > dto.MaxImageN {
|
||||
return nil, fmt.Errorf("parameters.n must be an integer between 1 and %d", dto.MaxImageN)
|
||||
}
|
||||
if imageRequest.Parameters.N != 0 {
|
||||
info.PriceData.AddOtherRatio("n", float64(imageRequest.Parameters.N))
|
||||
}
|
||||
|
||||
@@ -456,8 +456,10 @@ func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInf
|
||||
return nil
|
||||
}
|
||||
|
||||
// metadata can override Duration past standard request validation;
|
||||
// cap it because it is used as a billing multiplier.
|
||||
otherRatios := map[string]float64{
|
||||
"seconds": float64(aliReq.Parameters.Duration),
|
||||
"seconds": float64(min(aliReq.Parameters.Duration, relaycommon.MaxTaskDurationSeconds)),
|
||||
}
|
||||
ratios, err := ProcessAliOtherRatios(aliReq)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,8 @@ package gemini
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
)
|
||||
|
||||
// ParseVeoDurationSeconds extracts durationSeconds from metadata.
|
||||
@@ -46,19 +48,21 @@ func ParseVeoResolution(metadata map[string]any) string {
|
||||
|
||||
// ResolveVeoDuration returns the effective duration in seconds.
|
||||
// Priority: metadata["durationSeconds"] > stdDuration > stdSeconds > default (8).
|
||||
// The result is capped because it is used as a billing multiplier and the
|
||||
// metadata path bypasses standard request validation.
|
||||
func ResolveVeoDuration(metadata map[string]any, stdDuration int, stdSeconds string) int {
|
||||
if metadata != nil {
|
||||
if _, exists := metadata["durationSeconds"]; exists {
|
||||
if d := ParseVeoDurationSeconds(metadata); d > 0 {
|
||||
return d
|
||||
return min(d, relaycommon.MaxTaskDurationSeconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
if stdDuration > 0 {
|
||||
return stdDuration
|
||||
return min(stdDuration, relaycommon.MaxTaskDurationSeconds)
|
||||
}
|
||||
if s, err := strconv.Atoi(stdSeconds); err == nil && s > 0 {
|
||||
return s
|
||||
return min(s, relaycommon.MaxTaskDurationSeconds)
|
||||
}
|
||||
return 8
|
||||
}
|
||||
|
||||
@@ -78,6 +78,22 @@ func validatePrompt(prompt string) *dto.TaskError {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MaxTaskDurationSeconds caps user-supplied video duration. Duration is used
|
||||
// as a billing multiplier (OtherRatio "seconds"); an unbounded value could
|
||||
// overflow quota calculation into a negative charge.
|
||||
const MaxTaskDurationSeconds = 3600
|
||||
|
||||
func validateTaskDurationBounds(req TaskSubmitReq) *dto.TaskError {
|
||||
seconds := req.Duration
|
||||
if seconds == 0 && req.Seconds != "" {
|
||||
seconds, _ = strconv.Atoi(req.Seconds)
|
||||
}
|
||||
if seconds < 0 || seconds > MaxTaskDurationSeconds {
|
||||
return createTaskError(fmt.Errorf("seconds must be between 1 and %d", MaxTaskDurationSeconds), "invalid_seconds", http.StatusBadRequest, true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateMultipartTaskRequest(c *gin.Context, info *RelayInfo, action string) (TaskSubmitReq, error) {
|
||||
var req TaskSubmitReq
|
||||
if _, err := c.MultipartForm(); err != nil {
|
||||
@@ -156,6 +172,10 @@ func ValidateMultipartDirect(c *gin.Context, info *RelayInfo) *dto.TaskError {
|
||||
return taskErr
|
||||
}
|
||||
|
||||
if taskErr := validateTaskDurationBounds(req); taskErr != nil {
|
||||
return taskErr
|
||||
}
|
||||
|
||||
action := constant.TaskActionTextGenerate
|
||||
if hasInputReference {
|
||||
action = constant.TaskActionGenerate
|
||||
@@ -217,6 +237,10 @@ func ValidateBasicTaskRequest(c *gin.Context, info *RelayInfo, action string) *d
|
||||
return taskErr
|
||||
}
|
||||
|
||||
if taskErr := validateTaskDurationBounds(req); taskErr != nil {
|
||||
return taskErr
|
||||
}
|
||||
|
||||
if len(req.Images) == 0 && strings.TrimSpace(req.Image) != "" {
|
||||
// 兼容单图上传
|
||||
req.Images = []string{req.Image}
|
||||
|
||||
@@ -31,3 +31,67 @@ func TestValidateMultipartDirectNormalizesImageField(t *testing.T) {
|
||||
require.Equal(t, []string{"https://example.com/first.png"}, storedReq.Images)
|
||||
require.Equal(t, constant.TaskActionGenerate, info.Action)
|
||||
}
|
||||
|
||||
// TestTaskDurationBounds guards the billing invariant that user-supplied
|
||||
// video duration (a quota multiplier via OtherRatio "seconds") is bounded, so
|
||||
// it can never overflow quota calculation into a negative charge.
|
||||
func TestTaskDurationBounds(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
newContext := func(t *testing.T, body string) (*gin.Context, *RelayInfo) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/video/generations", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
context, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
context.Request = request
|
||||
return context, &RelayInfo{TaskRelayInfo: &TaskRelayInfo{}}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "huge duration is rejected",
|
||||
body: `{"model":"sora-2","prompt":"a cat","duration":9999999999}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "huge seconds string is rejected",
|
||||
body: `{"model":"sora-2","prompt":"a cat","seconds":"9999999999"}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "negative duration is rejected",
|
||||
body: `{"model":"sora-2","prompt":"a cat","duration":-8}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "normal duration is accepted",
|
||||
body: `{"model":"sora-2","prompt":"a cat","seconds":"8"}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name+" (multipart direct)", func(t *testing.T) {
|
||||
context, info := newContext(t, tt.body)
|
||||
taskErr := ValidateMultipartDirect(context, info)
|
||||
if tt.wantErr {
|
||||
require.NotNil(t, taskErr)
|
||||
require.Equal(t, "invalid_seconds", taskErr.Code)
|
||||
} else {
|
||||
require.Nil(t, taskErr)
|
||||
}
|
||||
})
|
||||
t.Run(tt.name+" (basic task request)", func(t *testing.T) {
|
||||
context, info := newContext(t, tt.body)
|
||||
taskErr := ValidateBasicTaskRequest(context, info, constant.TaskActionGenerate)
|
||||
if tt.wantErr {
|
||||
require.NotNil(t, taskErr)
|
||||
require.Equal(t, "invalid_seconds", taskErr.Code)
|
||||
} else {
|
||||
require.Nil(t, taskErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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" {
|
||||
|
||||
+8
-6
@@ -193,13 +193,15 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitRe
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 将 OtherRatios 应用到基础额度
|
||||
// 6. 将 OtherRatios 应用到基础额度(饱和转换,防止溢出成负数)
|
||||
if !common.StringsContains(constant.TaskPricePatches, modelName) {
|
||||
quotaWithRatios := float64(info.PriceData.Quota)
|
||||
for _, ra := range info.PriceData.OtherRatios {
|
||||
if ra != 1.0 {
|
||||
info.PriceData.Quota = int(float64(info.PriceData.Quota) * ra)
|
||||
quotaWithRatios *= ra
|
||||
}
|
||||
}
|
||||
info.PriceData.Quota = common.QuotaFromFloat(quotaWithRatios)
|
||||
}
|
||||
|
||||
// 7. 预扣费(仅首次 — 重试时 info.Billing 已存在,跳过)
|
||||
@@ -261,21 +263,21 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitRe
|
||||
// 公式: baseQuota × ∏(ratio) — 其中 baseQuota 是不含 OtherRatios 的基础额度。
|
||||
func recalcQuotaFromRatios(info *relaycommon.RelayInfo, ratios map[string]float64) int {
|
||||
// 从 PriceData 获取不含 OtherRatios 的基础价格
|
||||
baseQuota := info.PriceData.Quota
|
||||
baseQuota := float64(info.PriceData.Quota)
|
||||
// 先除掉原有的 OtherRatios 恢复基础额度
|
||||
for _, ra := range info.PriceData.OtherRatios {
|
||||
if ra != 1.0 && ra > 0 {
|
||||
baseQuota = int(float64(baseQuota) / ra)
|
||||
baseQuota /= ra
|
||||
}
|
||||
}
|
||||
// 应用新的 ratios
|
||||
result := float64(baseQuota)
|
||||
result := baseQuota
|
||||
for _, ra := range ratios {
|
||||
if ra != 1.0 {
|
||||
result *= ra
|
||||
}
|
||||
}
|
||||
return int(result)
|
||||
return common.QuotaFromFloat(result)
|
||||
}
|
||||
|
||||
var fetchRespBuilders = map[int]func(c *gin.Context) (respBody []byte, taskResp *dto.TaskError){
|
||||
|
||||
Reference in New Issue
Block a user