Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Honor unlimited file query limits https://github.com/siyuan-note/siyuan/issues/20221

Danielb851b2147fc9
diff --git a/kernel/cli/cmd/file.go b/kernel/cli/cmd/file.go
index 36a806f66e..301860b35d 100644
--- a/kernel/cli/cmd/file.go
+++ b/kernel/cli/cmd/file.go
@@ -290,7 +290,7 @@ var fileGrepCmd = &cobra.Command{
ctx, _ := cmd.Flags().GetInt("context")
max, _ := cmd.Flags().GetInt("limit")
if max <= 0 {
- max = 200
+ max = int(^uint(0) >> 1)
}
results, err := gulu.File.Grep(abs, include, pattern, ctx, max)
if err != nil {
@@ -329,9 +329,6 @@ var fileFindCmd = &cobra.Command{
}
include, _ := cmd.Flags().GetString("include")
max, _ := cmd.Flags().GetInt("limit")
- if max <= 0 {
- max = 200
- }
var results []string
total := 0
err = filepath.WalkDir(abs, func(path string, d os.DirEntry, err error) error {
@@ -352,14 +349,14 @@ var fileFindCmd = &cobra.Command{
return nil
}
total++
- if len(results) < max {
+ if max <= 0 || len(results) < max {
rel, relErr := filepath.Rel(util.WorkspaceDir, path)
if relErr != nil {
rel = path
}
results = append(results, rel)
}
- if total >= max {
+ if max > 0 && total >= max {
return filepath.SkipAll
}
return nil
@@ -372,7 +369,7 @@ var fileFindCmd = &cobra.Command{
data, _ := json.MarshalIndent(results, "", " ")
fmt.Println(string(data))
default:
- if max < total {
+ if max > 0 && max < total {
fmt.Printf("Found %d files (showing first %d):\n\n", total, max)
} else {
fmt.Printf("Found %d files:\n\n", len(results))
diff --git a/kernel/cli/cmd/file_limit_test.go b/kernel/cli/cmd/file_limit_test.go
new file mode 100644
index 0000000000..c66bdd036b
--- /dev/null
+++ b/kernel/cli/cmd/file_limit_test.go
@@ -0,0 +1,90 @@
+package cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "github.com/spf13/cobra"
+)
+
+func TestFileQueryLimits(t *testing.T) {
+ workspace := t.TempDir()
+ originalWorkspace, originalData, originalFormat := util.WorkspaceDir, util.DataDir, outputFormat
+ util.WorkspaceDir, util.DataDir, outputFormat = workspace, filepath.Join(workspace, "data"), "json"
+ t.Cleanup(func() {
+ util.WorkspaceDir, util.DataDir, outputFormat = originalWorkspace, originalData, originalFormat
+ })
+ query := filepath.Join(workspace, "query")
+ if err := os.Mkdir(query, 0755); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 205; i++ {
+ if err := os.WriteFile(filepath.Join(query, fmt.Sprintf("%03d.txt", i)), []byte("match\n"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, command := range []*cobra.Command{fileFindCmd, fileGrepCmd} {
+ limitFlag := command.Flags().Lookup("limit")
+ originalLimit, originalChanged := limitFlag.Value.String(), limitFlag.Changed
+ t.Cleanup(func() {
+ _ = limitFlag.Value.Set(originalLimit)
+ limitFlag.Changed = originalChanged
+ })
+ if command == fileGrepCmd {
+ for name, value := range map[string]string{"path": "query", "pattern": "match"} {
+ flag := command.Flags().Lookup(name)
+ original, changed := flag.Value.String(), flag.Changed
+ t.Cleanup(func() {
+ _ = flag.Value.Set(original)
+ flag.Changed = changed
+ })
+ if err := flag.Value.Set(value); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ for _, limit := range []int{200, 0, -1, 3} {
+ t.Run(command.Name()+"/"+strconv.Itoa(limit), func(t *testing.T) {
+ if err := limitFlag.Value.Set(strconv.Itoa(limit)); err != nil {
+ t.Fatal(err)
+ }
+ output, err := os.CreateTemp(workspace, "output-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ originalStdout := os.Stdout
+ os.Stdout = output
+ defer func() { os.Stdout = originalStdout }()
+ err = command.RunE(command, []string{"query"})
+ os.Stdout = originalStdout
+ if closeErr := output.Close(); closeErr != nil {
+ t.Fatal(closeErr)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(output.Name())
+ if err != nil {
+ t.Fatal(err)
+ }
+ var results []json.RawMessage
+ if err = json.Unmarshal(data, &results); err != nil {
+ t.Fatalf("invalid JSON: %v, %s", err, data)
+ }
+ want := limit
+ if limit <= 0 {
+ want = 205
+ }
+ if len(results) != want || strings.Contains(string(data), "output-") {
+ t.Fatalf("returned %d results, want %d", len(results), want)
+ }
+ })
+ }
+ }
+}
diff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.go
index 3d4af836a7..24b2bea75d 100644
--- a/kernel/mcp/tools/file.go
+++ b/kernel/mcp/tools/file.go
@@ -293,11 +293,10 @@ func getFloat64Arg(args map[string]any, key string) float64 {
}
func resolveLimit(args map[string]any, defaultLimit int) int {
- limit := int(getFloat64Arg(args, "limit"))
- if limit <= 0 {
+ if _, exists := args["limit"]; !exists {
return defaultLimit
}
- return limit
+ return int(getFloat64Arg(args, "limit"))
}
func fileRead(args map[string]any) (CallToolResult, error) {
@@ -973,9 +972,6 @@ func grepGuarded(root, include, pattern string, context, maxResults int) ([]*gul
if err != nil {
return nil, err
}
- if maxResults <= 0 {
- maxResults = 64
- }
var results []*gulu.GrepResult
info, err := os.Stat(root)
@@ -1016,7 +1012,7 @@ func grepGuarded(root, include, pattern string, context, maxResults int) ([]*gul
if err != nil {
return results, err
}
- if len(results) > maxResults {
+ if maxResults > 0 && len(results) > maxResults {
results = results[:maxResults]
}
return results, nil
@@ -1024,7 +1020,7 @@ func grepGuarded(root, include, pattern string, context, maxResults int) ([]*gul
// grepGuardedFile 逐行匹配单个文件并收集上下文行,语义与 gulu 的 grep 保持一致。
func grepGuardedFile(path string, re *regexp.Regexp, context int, results *[]*gulu.GrepResult, maxResults int) {
- if len(*results) >= maxResults {
+ if maxResults > 0 && len(*results) >= maxResults {
return
}
@@ -1044,7 +1040,7 @@ func grepGuardedFile(path string, re *regexp.Regexp, context int, results *[]*gu
flushBeforeBuf := func() {
for _, e := range beforeBuf {
- if len(*results) >= maxResults {
+ if maxResults > 0 && len(*results) >= maxResults {
return
}
*results = append(*results, &gulu.GrepResult{File: path, Line: e.lineNum, Text: e.text, Context: true})
@@ -1053,7 +1049,7 @@ func grepGuardedFile(path string, re *regexp.Regexp, context int, results *[]*gu
}
emit := func(lineNum int, text string, isContext bool) {
- if len(*results) >= maxResults {
+ if maxResults > 0 && len(*results) >= maxResults {
return
}
*results = append(*results, &gulu.GrepResult{File: path, Line: lineNum, Text: text, Context: isContext})
@@ -1063,7 +1059,7 @@ func grepGuardedFile(path string, re *regexp.Regexp, context int, results *[]*gu
scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
lineNum := 0
for scanner.Scan() {
- if len(*results) >= maxResults {
+ if maxResults > 0 && len(*results) >= maxResults {
return
}
lineNum++
diff --git a/kernel/mcp/tools/file_limit_test.go b/kernel/mcp/tools/file_limit_test.go
new file mode 100644
index 0000000000..8c0640841c
--- /dev/null
+++ b/kernel/mcp/tools/file_limit_test.go
@@ -0,0 +1,75 @@
+package tools
+
+import (
+ "fmt"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestFileQueryLimits(t *testing.T) {
+ workspace := setupProbeWorkspace(t)
+ for i := 0; i < 205; i++ {
+ writeProbeFile(t, filepath.Join(workspace, "data", "query", fmt.Sprintf("%03d.txt", i)), "match\n")
+ }
+ writeProbeFile(t, filepath.Join(workspace, "data", "lines.txt"), strings.Repeat("match\n", 205))
+ for _, operation := range []string{"list", "find", "grep", "grep-file"} {
+ for _, tc := range []struct {
+ name string
+ limit any
+ count int
+ }{
+ {"default", nil, 200},
+ {"zero", float64(0), 205},
+ {"negative", float64(-1), 205},
+ {"positive", float64(3), 3},
+ } {
+ t.Run(operation+"/"+tc.name, func(t *testing.T) {
+ args := map[string]any{"path": "data/query", "pattern": "match"}
+ if tc.limit != nil {
+ args["limit"] = tc.limit
+ }
+ var result CallToolResult
+ var err error
+ switch operation {
+ case "list":
+ result, err = fileList(args)
+ case "find":
+ result, err = fileFind(args)
+ case "grep":
+ result, err = fileGrep(args)
+ case "grep-file":
+ args["path"] = "data/lines.txt"
+ result, err = fileGrep(args)
+ }
+ if err != nil || result.IsError {
+ t.Fatalf("query failed: %v, %s", err, probeText(result))
+ }
+ text := probeText(result)
+ marker := ".txt"
+ if operation == "grep-file" {
+ marker = " match"
+ }
+ if count := strings.Count(text, marker); count != tc.count {
+ t.Fatalf("returned %d results, want %d: %s", count, tc.count, text)
+ }
+ })
+ }
+ }
+}
+
+func TestGrepUnlimitedContextAndAuthorization(t *testing.T) {
+ workspace := setupProbeWorkspace(t)
+ writeProbeFile(t, filepath.Join(workspace, "data", "query", "lines.txt"), strings.Repeat("before\nmatch\nafter\n", 100))
+ writeProbeFile(t, filepath.Join(workspace, "conf", "conf.json"), `{"secret":"match"}`)
+ for _, limit := range []float64{0, -1} {
+ result, err := fileGrep(map[string]any{"path": "data/query", "pattern": "match", "context": float64(1), "limit": limit})
+ if err != nil || result.IsError || strings.Count(probeText(result), ".txt:") != 300 {
+ t.Fatalf("unlimited context query failed: %v, %s", err, probeText(result))
+ }
+ result, err = fileGrep(map[string]any{"path": "conf", "pattern": "match", "limit": limit})
+ if err != nil || result.IsError || strings.Contains(probeText(result), "secret") {
+ t.Fatalf("unlimited query exposed protected content: %v, %s", err, probeText(result))
+ }
+ }
+}