fix(pagination): validate numeric ranges and reuse safe offsets

Use strconv to reject pagination values outside the native int range,
reuse PaginationParams.Offset for API key slices, and derive test bounds
from math.MaxInt. Cover parsing, response metadata, strict handlers, and
in-memory pagination at the arithmetic boundaries.
This commit is contained in:
SipengXie2024 committed 2026-10-23 15:24:24 +08:00
1 parent f965280489
commit 9aa16c8c66
8 files changed
+190 -28

No files matched your search

@@ -2,6 +2,8 @@ package admin
import (
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"net/netip"
@@ -150,6 +152,32 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) {
}
}
func TestParseOpsOpenAITokenStatsFilter_PaginationBoundaries(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, size := range []int{1, 20, 21, 100} {
bound := math.MaxInt / size
pages := []int{bound}
if bound < math.MaxInt {
pages = append(pages, bound+1)
}
for _, page := range pages {
query := fmt.Sprintf("/?page=%d&page_size=%d", page, size)
t.Run(query, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, query, nil)
filter, err := parseOpsOpenAITokenStatsFilter(c)
if page > bound {
require.ErrorContains(t, err, "invalid page")
return
}
require.NoError(t, err)
require.Equal(t, page, filter.Page)
require.Equal(t, size, filter.PageSize)
})
}
}
}
func TestParseOpsTimeRange(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
@@ -108,8 +108,8 @@ func TestPaginationParamsOffsetUsesNormalizedLimit(t *testing.T) {
func TestPaginationParamsOffsetDoesNotOverflow(t *testing.T) {
t.Parallel()
pages := []int{math.MaxInt, math.MaxInt - 1, math.MaxInt / 2, 461168601842738791, math.MaxInt/1000 + 1}
pageSizes := []int{1, 2, 3, 20, 21, 999, 1000}
pages := []int{math.MinInt, -1, 0, 1, math.MaxInt, math.MaxInt - 1, math.MaxInt / 2, math.MaxInt/20 + 1, math.MaxInt/1000 + 1}
pageSizes := []int{math.MinInt, -1, 0, 1, 2, 3, 20, 21, 999, 1000, 1001, math.MaxInt}
for _, page := range pages {
for _, pageSize := range pageSizes {
params := PaginationParams{Page: page, PageSize: pageSize}
+7 -10
View File
@@ -5,6 +5,7 @@ import (
"log"
"math"
"net/http"
"strconv"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/util/logredact"
@@ -166,7 +167,8 @@ func PaginatedWithResult(c *gin.Context, items any, pagination *PaginationResult
})
}
// ParsePagination 解析分页参数
// ParsePagination 解析分页参数。无效或超出 int 范围的值使用默认值;
// 有效页码按 pageSize 限制上限,返回可安全计算 offset 和 offset+pageSize 的页码。
func ParsePagination(c *gin.Context) (page, pageSize int) {
page = 1
pageSize = 20
@@ -188,7 +190,7 @@ func ParsePagination(c *gin.Context) (page, pageSize int) {
}
}
// Clamp the page so (page-1)*pageSize computed by callers cannot overflow int.
// Clamp the page so both offset and offset+pageSize stay within int.
if page > math.MaxInt/pageSize {
page = math.MaxInt / pageSize
}
@@ -197,12 +199,7 @@ func ParsePagination(c *gin.Context) (page, pageSize int) {
}
func parseInt(s string) (int, error) {
var result int
for _, c := range s {
if c < '0' || c > '9' {
return 0, nil
}
result = result*10 + int(c-'0')
}
return result, nil
// Parse unsigned decimal digits within the positive range of the native int.
value, err := strconv.ParseUint(s, 10, strconv.IntSize-1)
return int(value), err
}
+96 -11
View File
@@ -8,6 +8,8 @@ import (
"math"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
errors2 "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
@@ -694,28 +696,58 @@ func TestParsePagination(t *testing.T) {
},
{
name: "page为MaxInt_钳制到不溢出的上限",
query: "page=9223372036854775807",
query: "page=" + strconv.Itoa(math.MaxInt),
wantPage: math.MaxInt / 20,
wantPageSize: 20,
},
{
name: "page为MaxInt且page_size为1000_钳制到不溢出的上限",
query: "page=9223372036854775807&page_size=1000",
query: "page=" + strconv.Itoa(math.MaxInt) + "&page_size=1000",
wantPage: math.MaxInt / 1000,
wantPageSize: 1000,
},
{
name: "page恰好在上限_有效",
query: "page=461168601842738790",
wantPage: 461168601842738790,
query: "page=" + strconv.Itoa(math.MaxInt/20),
wantPage: math.MaxInt / 20,
wantPageSize: 20,
},
{
name: "page刚超过上限_钳制",
query: "page=461168601842738791",
query: "page=" + strconv.Itoa(math.MaxInt/20+1),
wantPage: math.MaxInt / 20,
wantPageSize: 20,
},
{
name: "page超过MaxInt_使用默认值",
query: "page=" + strconv.FormatUint(uint64(math.MaxInt)+1, 10),
wantPage: 1,
wantPageSize: 20,
},
{
name: "page超过uint64范围_不能回绕为2",
query: "page=18446744073709551618",
wantPage: 1,
wantPageSize: 20,
},
{
name: "page_size超过uint64范围_不能回绕为21",
query: "page_size=18446744073709551637&limit=50",
wantPage: 1,
wantPageSize: 20,
},
{
name: "limit超过uint64范围_不能回绕为21",
query: "limit=18446744073709551637",
wantPage: 1,
wantPageSize: 20,
},
{
name: "超长数字_使用默认值",
query: "page=" + strings.Repeat("9", 100),
wantPage: 1,
wantPageSize: 20,
},
}
for _, tt := range tests {
@@ -730,6 +762,38 @@ func TestParsePagination(t *testing.T) {
}
}
func TestParsePaginationBoundariesAndResponse(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, sizeParam := range []string{"page_size", "limit"} {
for _, size := range []int{1, 2, 3, 20, 21, 999, 1000} {
bound := math.MaxInt / size
pages := []int{bound - 1, bound, math.MaxInt}
if bound < math.MaxInt {
pages = append(pages, bound+1)
}
for _, requestedPage := range pages {
query := "page=" + strconv.Itoa(requestedPage) + "&" + sizeParam + "=" + strconv.Itoa(size)
t.Run(query, func(t *testing.T) {
w, c := newContextWithQuery(query)
page, pageSize := ParsePagination(c)
require.Equal(t, min(requestedPage, bound), page)
require.Equal(t, size, pageSize)
offset := (page - 1) * pageSize
require.GreaterOrEqual(t, offset, 0)
require.LessOrEqual(t, offset, math.MaxInt-pageSize)
Paginated(c, []string{}, 0, page, pageSize)
require.Equal(t, http.StatusOK, w.Code)
_, data := parsePaginatedBody(t, w)
require.Equal(t, page, data.Page)
require.Equal(t, pageSize, data.PageSize)
require.Empty(t, data.Items)
})
}
}
}
}
func Test_parseInt(t *testing.T) {
tests := []struct {
name string
@@ -765,37 +829,58 @@ func Test_parseInt(t *testing.T) {
name: "包含字母_返回0",
input: "abc",
wantVal: 0,
wantErr: false,
wantErr: true,
},
{
name: "数字开头接字母_返回0",
input: "12a",
wantVal: 0,
wantErr: false,
wantErr: true,
},
{
name: "包含负号_返回0",
input: "-1",
wantVal: 0,
wantErr: false,
wantErr: true,
},
{
name: "包含小数点_返回0",
input: "1.5",
wantVal: 0,
wantErr: false,
wantErr: true,
},
{
name: "包含空格_返回0",
input: "1 2",
wantVal: 0,
wantErr: false,
wantErr: true,
},
{
name: "空字符串",
input: "",
wantVal: 0,
wantErr: false,
wantErr: true,
},
{
name: "前导零_有效",
input: "000123",
wantVal: 123,
},
{
name: "正号_无效",
input: "+1",
wantErr: true,
},
{
name: "MaxInt_有效",
input: strconv.Itoa(math.MaxInt),
wantVal: math.MaxInt,
},
{
name: "超过MaxInt_返回范围错误",
input: strconv.FormatUint(uint64(math.MaxInt)+1, 10),
wantVal: math.MaxInt,
wantErr: true,
},
}
@@ -0,0 +1,17 @@
package repository
import (
"math"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/stretchr/testify/require"
)
func TestPaginateSliceLargePage(t *testing.T) {
t.Parallel()
for _, size := range []int{0, 1, 2, 3, 20, 21, 1000, 1001} {
params := pagination.PaginationParams{Page: math.MaxInt, PageSize: size}
require.Empty(t, paginateSlice([]int{1}, params), "page_size=%d", size)
}
}
@@ -5,8 +5,10 @@ import (
"context"
"encoding/json"
"errors"
"math"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
@@ -220,6 +222,18 @@ func TestPromptAdminRejectsInvalidEventIDsTimesAndPagination(t *testing.T) {
}
}
func TestPromptAdminRejectsOverflowingPagination(t *testing.T) {
router := promptAdminRouter(nil)
for _, size := range []int{20, 21, 100} {
query := "/admin/prompt-audit/events?page=" + strconv.Itoa(math.MaxInt/size+1) + "&page_size=" + strconv.Itoa(size)
t.Run(query, func(t *testing.T) {
response := promptAdminRequest(t, router, http.MethodGet, query, nil)
require.Equal(t, http.StatusBadRequest, response.Code)
require.Contains(t, response.Body.String(), "prompt_audit_invalid_pagination")
})
}
}
func validHandlerUpdateRequest(token string) UpdateConfigRequest {
return UpdateConfigRequest{
ExpectedConfigVersion: 7,
+1 -5
View File
@@ -653,11 +653,7 @@ func paginateAPIKeys(keys []APIKey, params pagination.PaginationParams) []APIKey
return []APIKey{}
}
limit := params.Limit()
page := params.Page
if page < 1 {
page = 1
}
offset := (page - 1) * limit
offset := params.Offset()
if offset >= len(keys) {
return []APIKey{}
}
@@ -0,0 +1,25 @@
package service
import (
"math"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/stretchr/testify/require"
)
func TestPaginateAPIKeysLargePage(t *testing.T) {
t.Parallel()
for _, size := range []int{0, 1, 2, 3, 20, 21, 1000, 1001} {
params := pagination.PaginationParams{Page: math.MaxInt, PageSize: size}
require.Empty(t, paginateAPIKeys([]APIKey{{ID: 1}}, params), "page_size=%d", size)
}
}
func TestMergeBalanceHistoryCodesLargePage(t *testing.T) {
t.Parallel()
for _, size := range []int{0, 1, 2, 3, 20, 21, 1000, 1001} {
params := pagination.PaginationParams{Page: math.MaxInt, PageSize: size}
require.Empty(t, mergeBalanceHistoryCodes([]RedeemCode{{ID: 1}}, nil, params), "page_size=%d", size)
}
}