Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/sandbox/daemon-go/internal/routes/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,11 @@ func Edit(deps FsDeps) http.HandlerFunc {
}
}

const (
grepDefaultResultLimit = 250
grepMaxResultLimit = 10000
)

func Grep(deps FsDeps) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var body struct {
Expand Down Expand Up @@ -520,9 +525,12 @@ func Grep(deps FsDeps) http.HandlerFunc {
}
args = append(args, "--", body.Pattern, searchPath)

limit := 250
limit := grepDefaultResultLimit
if body.Limit > 0 {
limit = body.Limit
if limit > grepMaxResultLimit {
limit = grepMaxResultLimit
}
}

cmd := exec.Command("rg", args...)
Expand Down
39 changes: 39 additions & 0 deletions packages/sandbox/daemon-go/internal/routes/fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
Expand Down Expand Up @@ -58,6 +59,44 @@ func TestDecodeBodyRejectsOversizedRequest(t *testing.T) {
}
}

// Without an upper bound, a caller-supplied `limit` let /grep buffer an
// unbounded number of match lines into memory — the same crash-the-daemon
// class the request-body cap above closes for the request side.
func TestGrepCapsCallerSuppliedLimit(t *testing.T) {
if _, err := exec.LookPath("rg"); err != nil {
t.Skip("ripgrep not installed")
}
repoDir := t.TempDir()
var content strings.Builder
for i := 0; i < grepMaxResultLimit+500; i++ {
content.WriteString("needle\n")
}
if err := os.WriteFile(filepath.Join(repoDir, "haystack.txt"), []byte(content.String()), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
deps := FsDeps{AppRoot: repoDir, RepoDir: repoDir}
body, _ := json.Marshal(map[string]any{
"pattern": "needle",
"output_mode": "content",
"limit": grepMaxResultLimit * 10,
})
req := httptest.NewRequest(http.MethodPost, "/grep", bytes.NewReader(body))
rec := httptest.NewRecorder()
Grep(deps)(rec, req)
if rec.Code != 200 {
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
}
var out struct {
MatchCount int `json:"matchCount"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if out.MatchCount > grepMaxResultLimit {
t.Fatalf("expected matchCount capped at %d, got %d", grepMaxResultLimit, out.MatchCount)
}
}

func readReq(t *testing.T, deps FsDeps, path string) *httptest.ResponseRecorder {
t.Helper()
body, _ := json.Marshal(map[string]any{"path": path, "full": true})
Expand Down
Loading