This commit is contained in:
2026-06-20 19:16:44 +08:00
parent db3d030169
commit dbb87823e8
26 changed files with 676 additions and 115 deletions
+4 -1
View File
@@ -68,7 +68,10 @@ func sliceLines(s string, line, limit *int) string {
}
end := len(lines)
if limit != nil && *limit >= 0 {
if start+*limit < end {
// overflow-safe:用剩余行数为上限做钳制,避免 start+*limit 在 *limit 很大
// (如 math.MaxInt)时整数溢出为负,绕过下界判断后导致 lines[start:end] panic。
remaining := len(lines) - start
if *limit < remaining {
end = start + *limit
}
}
@@ -3,6 +3,7 @@ package handlers_test
import (
"context"
"encoding/json"
"math"
"os"
"path/filepath"
"testing"
@@ -81,6 +82,37 @@ func TestFsRead_LineLimit(t *testing.T) {
assert.Equal(t, "L1\nL2", out.Content)
}
// TestFsRead_HugeLimit_NoOverflow 锁定 bug #2:limit 为 math.MaxInt 时
// start+limit 会整数溢出为负,旧逻辑下 lines[start:end] 会 panic。修复后应安全
// 钳制到文件末尾,返回从 line 起的剩余内容。
func TestFsRead_HugeLimit_NoOverflow(t *testing.T) {
t.Parallel()
tmp := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(tmp, "f.txt"),
[]byte("L0\nL1\nL2\nL3\n"), 0o644))
h := handlers.NewFsReadHandler()
sess := handlers.SessionContext{CwdPath: tmp}
line := 1
limit := math.MaxInt
params := mustJSON(t, map[string]any{
"sessionId": "x", "path": filepath.Join(tmp, "f.txt"),
"line": line, "limit": limit,
})
var res handlers.FsResult
require.NotPanics(t, func() {
res = h.Handle(context.Background(), sess, params)
})
require.Nil(t, res.Err)
var out struct {
Content string `json:"content"`
}
require.NoError(t, json.Unmarshal(res.OK, &out))
// 从 line=1 到末尾(split 出 5 个元素:L0 L1 L2 L3 "")。
assert.Equal(t, "L1\nL2\nL3\n", out.Content)
}
func mustJSON(t *testing.T, v any) json.RawMessage {
t.Helper()
b, err := json.Marshal(v)