fix(accounts): 上游分组文字入库前校验,include 支持多值

- 上游分组名称/描述与探测快照、倍率在同一条 UPDATE 中写库。gjson 对未转义
  字符串返回原始字节,非法 UTF-8 会被 PostgreSQL 以 22021 拒绝,导致整条
  UPDATE 失败:快照与倍率都写不进去,next_probe_at 不推进,账号每个调度
  周期都被重试并挤占探测名额。现在非法 UTF-8 只丢弃对应字段
- 名称拒绝控制字符,备注仅保留换行与制表符,避免上游向管理端写入
  转义序列等不可见内容
- /v1/sub2api/billing 的 include 按逗号分隔列表解析并支持重复参数,
  后续新增可选段时不会让 include=group 失效
This commit is contained in:
shaw committed 2026-11-24 08:58:55 +08:00
1 parent 03aa05fd9f
commit 38903b6d1d
4 files changed
+93 -6

No files matched your search

@@ -3,6 +3,7 @@ package handler
import (
"log/slog"
"net/http"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
@@ -60,7 +61,7 @@ func (h *GatewayHandler) KeyBillingInfo(c *gin.Context) {
}
info := buildKeyBillingInfo(apiKey, resolvedRate, timezone.Now())
if c.Query("include") == "group" {
if keyBillingIncludes(c, "group") {
group, err := h.apiKeyService.GetBillingGroupInfo(c.Request.Context(), *apiKey.GroupID, c.GetHeader("Accept-Language"))
if err != nil {
slog.WarnContext(c.Request.Context(), "billing group display text unavailable", "group_id", *apiKey.GroupID, "error", err)
@@ -72,6 +73,22 @@ func (h *GatewayHandler) KeyBillingInfo(c *gin.Context) {
c.JSON(http.StatusOK, info)
}
// keyBillingIncludes reports whether the caller asked for an optional response section.
// include is a comma-separated list and may be repeated, so a client can request several
// sections in one call (include=group,other or include=group&include=other); unknown sections
// are ignored. An exact-match comparison would stop returning the group as soon as a second
// section exists.
func keyBillingIncludes(c *gin.Context, section string) bool {
for _, value := range c.QueryArray("include") {
for _, item := range strings.Split(value, ",") {
if strings.TrimSpace(item) == section {
return true
}
}
}
return false
}
func (h *GatewayHandler) resolveKeyBillingRate(c *gin.Context, apiKey *service.APIKey) (float64, bool) {
groupRate := apiKey.Group.RateMultiplier
switch apiKey.Group.Platform {
@@ -188,6 +188,35 @@ func TestGatewayRoutesKeyBillingInfoEndToEnd(t *testing.T) {
require.NotContains(t, w.Body.String(), key)
})
t.Run("include accepts a list of sections", func(t *testing.T) {
for query, wantGroup := range map[string]bool{
"include=group,model_pricing": true,
"include=model_pricing,%20group": true,
"include=model_pricing&include=group": true,
"include=group&include=model_pricing": true,
"include=model_pricing": false,
"include=groups": false,
"include=": false,
} {
router, _, key := newKeyBillingRouteTestRouter(config.RunModeStandard, nil)
req := httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing?"+query, nil)
req.Header.Set("x-api-key", key)
req.Header.Set("Accept-Language", "en")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, query)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body), query)
require.Equal(t, 0.75, body["effective_rate_multiplier"], query)
if wantGroup {
require.Equal(t, "Standard", body["group_name"], query)
} else {
require.NotContains(t, body, "group_name", query)
}
}
})
t.Run("optional group lookup failure preserves billing rates", func(t *testing.T) {
router, _, key := newKeyBillingRouteTestRouter(config.RunModeStandard, &keyBillingRouteGroupRepo{})
req := httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing?include=group", nil)
@@ -17,6 +17,8 @@ import (
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/Wei-Shaw/sub2api/internal/domain"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
@@ -747,19 +749,35 @@ func (s *UpstreamBillingProbeService) PreviewGroup(ctx context.Context, account
}
// Treat each optional text field independently so an invalid field cannot block rate updates.
//
// The text comes from a remote upstream and is written to accounts.name / accounts.notes in the
// same UPDATE as the probe snapshot and the synced rate. Anything PostgreSQL would reject must be
// dropped here: a rejected parameter fails the whole statement, the snapshot is never stored, and
// the account is retried every scheduler tick instead of at its probe interval.
func upstreamBillingGroupInfo(body []byte) BillingGroupInfo {
text := func(key string) string {
text := func(key string, multiline bool) string {
value := gjson.GetBytes(body, key)
if value.Type != gjson.String || strings.ContainsRune(value.Str, 0) {
// gjson returns unescaped strings as raw bytes, so invalid UTF-8 reaches us unchanged
// even though encoding/json accepted the body. PostgreSQL rejects it (SQLSTATE 22021).
if value.Type != gjson.String || !utf8.ValidString(value.Str) {
return ""
}
// Control characters (NUL included, which PostgreSQL text cannot store) have no place in
// display text. Notes may span lines; the name is a single line.
for _, r := range value.Str {
if unicode.IsControl(r) && (!multiline || (r != '\n' && r != '\r' && r != '\t')) {
return ""
}
}
return strings.TrimSpace(value.Str)
}
name := text("group_name")
if len(name) > 100 { // accounts.name uses Ent MaxLen(100).
name := text("group_name", false)
// accounts.name uses Ent MaxLen(100), which counts bytes. A longer name would be accepted by
// the VARCHAR(100) column but then fail validation on every later Ent update of the account.
if len(name) > 100 {
name = ""
}
return BillingGroupInfo{Name: name, Description: text("group_description")}
return BillingGroupInfo{Name: name, Description: text("group_description", true)}
}
func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, account *Account, intervalMinutes int) (*UpstreamBillingProbeSnapshot, error) {
@@ -1322,6 +1322,16 @@ func TestUpstreamBillingGroupSyncSharesOneProbeAndPreservesLocalFields(t *testin
{"invalid name", true, true, `"group_name":12,"group_description":"shared"`, "local", "shared", 0.5},
{"old upstream", true, true, `"unrelated":true`, "local", "local notes", 0.5},
{"rate only", false, true, `"group_name":"Pro","group_description":"shared"`, "local", "local notes", 0.5},
// 上游文字与快照、倍率在同一条 UPDATE 里写库:PostgreSQL 会拒绝的内容必须只丢弃该字段,
// 倍率与另一个字段照常同步。
{"invalid utf8 name", true, true, `"group_name":"A` + "\xff" + `B","group_description":"shared"`, "local", "shared", 0.5},
{"invalid utf8 notes", true, true, `"group_name":"Pro","group_description":"bad ` + "\xc3" + `"`, "Pro", "local notes", 0.5},
{"nul in name", true, true, `"group_name":"Pro\u0000","group_description":"shared"`, "local", "shared", 0.5},
{"control character in name", true, true, `"group_name":"Pro\nGroup","group_description":"shared"`, "local", "shared", 0.5},
{"escape sequence in notes", true, true, `"group_name":"Pro","group_description":"a\u001b[31mb"`, "Pro", "local notes", 0.5},
{"multiline notes", true, true, `"group_name":"Pro","group_description":"line one\n\tline two"`, "Pro", "line one\n\tline two", 0.5},
{"name over 100 bytes", true, true, `"group_name":"` + strings.Repeat("组", 34) + `","group_description":"shared"`, "local", "shared", 0.5},
{"name at 100 bytes", true, true, `"group_name":"` + strings.Repeat("a", 100) + `","group_description":"shared"`, strings.Repeat("a", 100), "shared", 0.5},
} {
t.Run(tt.name, func(t *testing.T) {
rate, notes := 1.0, "local notes"
@@ -1350,3 +1360,16 @@ func TestUpstreamBillingGroupSyncSharesOneProbeAndPreservesLocalFields(t *testin
})
}
}
func TestUpstreamBillingGroupInfoNeverReturnsTextPostgresRejects(t *testing.T) {
for _, raw := range []string{
"A\xffB", "\xff", "\xc3", "\xe2\x82", "ok\x00", "\xed\xa0\x80",
} {
body := []byte(`{"group_name":"` + raw + `","group_description":"` + raw + `"}`)
got := upstreamBillingGroupInfo(body)
require.Empty(t, got.Name, "%q", raw)
require.Empty(t, got.Description, "%q", raw)
}
got := upstreamBillingGroupInfo([]byte(`{"group_name":" 标准组 🚀 ","group_description":"支持推理模型\r\n第二行"}`))
require.Equal(t, BillingGroupInfo{Name: "标准组 🚀", Description: "支持推理模型\r\n第二行"}, got)
}