autoresearch iter 6: reject negative cursor instead of silently using 0

parsePositiveInt reported invalidity through a bool that both call sites
discarded, and returned (false, nil) whenever Atoi succeeded on a negative
number. GetLogs therefore accepted ?cursor=-5 and served it as cursor 0
('latest') instead of the documented 400. Validity now travels through the
error result, which no caller can ignore.
This commit is contained in:
ryan
2026-08-29 08:16:50 +08:00
parent 850f99a2c8
commit ce33997c23
3 changed files with 139 additions and 7 deletions
+15 -7
View File
@@ -11,6 +11,7 @@ import (
"Wavelet/plugins/domain/admin/model"
"Wavelet/plugins/domain/admin/service"
"encoding/json"
"errors"
"net/http"
"strconv"
@@ -47,11 +48,11 @@ func GetLogs(c *gin.Context) {
limitStr := c.DefaultQuery("limit", "200")
var cursor, limit int
if _, err := parsePositiveInt(cursorStr, &cursor); err != nil {
if err := parsePositiveInt(cursorStr, &cursor); err != nil {
response.AbortWithError(c, http.StatusBadRequest, errs.InvalidCursorParam)
return
}
if _, err := parsePositiveInt(limitStr, &limit); err != nil || limit <= 0 {
if err := parsePositiveInt(limitStr, &limit); err != nil || limit <= 0 {
limit = defaultLimit
}
if limit > maxLimit {
@@ -183,15 +184,22 @@ func getUpgrader() *websocket.Upgrader {
}
}
func parsePositiveInt(s string, result *int) (bool, error) {
// errNegativeParam 表示查询参数解析出了负数。
var errNegativeParam = errors.New("parameter must not be negative")
// parsePositiveInt 解析非负整数查询参数;返回错误时 result 保持调用前的值。
func parsePositiveInt(s string, result *int) error {
if s == "" {
*result = 0
return true, nil
return nil
}
n, err := strconv.Atoi(s)
if err != nil || n < 0 {
return false, err
if err != nil {
return err
}
if n < 0 {
return errNegativeParam
}
*result = n
return true, nil
return nil
}
@@ -0,0 +1,41 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package handler
import (
"testing"
)
func TestParsePositiveInt(t *testing.T) {
const untouched = 77
tests := []struct {
name string
input string
want int
wantErr bool
}{
{name: "empty means zero", input: "", want: 0},
{name: "zero accepted", input: "0", want: 0},
{name: "positive accepted", input: "42", want: 42},
{name: "negative rejected", input: "-5", want: untouched, wantErr: true},
{name: "oversized rejected", input: "99999999999999999999", want: untouched, wantErr: true},
{name: "non numeric rejected", input: "abc", want: untouched, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := untouched
err := parsePositiveInt(tt.input, &got)
if (err != nil) != tt.wantErr {
t.Fatalf("parsePositiveInt(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
}
if got != tt.want {
t.Errorf("parsePositiveInt(%q) left result %d, want %d", tt.input, got, tt.want)
}
})
}
}