package tool import ( "context" "encoding/json" "encoding/pem" "errors" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" ) func TestReadHardening(t *testing.T) { dir := t.TempDir() // Directory → error. if r := run(t, NewRead(), dir, map[string]any{"file_path": "."}); !r.IsError { t.Fatal("reading a directory should error") } // Binary file → notice, not garbage. os.WriteFile(filepath.Join(dir, "bin"), []byte{0x00, 0x01, 0x02, 'h', 'i'}, 0o644) if r := run(t, NewRead(), dir, map[string]any{"file_path": "bin"}); !strings.Contains(r.Flatten(), "binary file") { t.Fatalf("binary not detected: %q", r.Flatten()) } // Long line truncation. os.WriteFile(filepath.Join(dir, "long.txt"), []byte(strings.Repeat("a", 5000)), 0o644) out := run(t, NewRead(), dir, map[string]any{"file_path": "long.txt"}).Flatten() if !strings.Contains(out, "line truncated") { t.Fatalf("long line not truncated: len=%d", len(out)) } } func TestReadTruncationGuidesOffset(t *testing.T) { dir := t.TempDir() body := strings.Repeat("padding line of some length\n", 300) + "TAILMARKER\n" os.WriteFile(filepath.Join(dir, "big.txt"), []byte(body), 0o644) raw, _ := json.Marshal(map[string]any{"file_path": "big.txt"}) // Small MaxOutputChars forces truncation; effective budget = 200 + readOutputBonus. res, err := NewRead().Call(context.Background(), raw, &ToolContext{WorkingDir: dir, MaxOutputChars: 200}) if err != nil { t.Fatalf("read: %v", err) } out := res.Flatten() if !strings.Contains(out, "truncated to fit the output limit") || !strings.Contains(out, "offset=") { t.Fatalf("missing truncation + offset guidance: %q", out) } // The +readOutputBonus(1000) lifts the budget well above MaxOutputChars(200). if len(out) <= 200 { t.Fatalf("Read budget should exceed MaxOutputChars by the bonus; got len=%d", len(out)) } // Head is line-bounded and the tail line is not shown. if strings.Contains(out, "TAILMARKER") { t.Fatalf("tail line should not appear after truncation: %q", out) } } func TestReadTruncationDoesNotSpill(t *testing.T) { dir := t.TempDir() spill := t.TempDir() body := strings.Repeat("padding line of some length\n", 300) os.WriteFile(filepath.Join(dir, "big.txt"), []byte(body), 0o644) raw, _ := json.Marshal(map[string]any{"file_path": "big.txt"}) // Even with an OutputDir configured, Read does not spill a copy — the source // file is on disk, so it just guides the model to page on with offset. res, _ := NewRead().Call(context.Background(), raw, &ToolContext{WorkingDir: dir, OutputDir: spill, MaxOutputChars: 200}) out := res.Flatten() if !strings.Contains(out, "offset=") || strings.Contains(out, "saved to") { t.Fatalf("Read should guide offset without spilling: %q", out) } if files, _ := os.ReadDir(spill); len(files) != 0 { t.Fatalf("Read must not spill to OutputDir, found %d file(s)", len(files)) } } func TestWriteCreatedVsOverwrote(t *testing.T) { dir := t.TempDir() if r := run(t, NewWrite(), dir, map[string]any{"file_path": "f.txt", "content": "a"}); !strings.Contains(r.Flatten(), "Created") { t.Fatalf("expected Created: %q", r.Flatten()) } if r := run(t, NewWrite(), dir, map[string]any{"file_path": "f.txt", "content": "b"}); !strings.Contains(r.Flatten(), "Overwrote") { t.Fatalf("expected Overwrote: %q", r.Flatten()) } if r := run(t, NewWrite(), dir, map[string]any{"file_path": ".", "content": "x"}); !r.IsError { t.Fatal("writing over a directory should error") } } func TestMultiEditAtomic(t *testing.T) { dir := t.TempDir() os.WriteFile(filepath.Join(dir, "f.go"), []byte("alpha beta gamma"), 0o644) // Two good edits apply in order. run(t, NewMultiEdit(), dir, map[string]any{ "file_path": "f.go", "edits": []any{ map[string]any{"old_string": "alpha", "new_string": "ALPHA"}, map[string]any{"old_string": "gamma", "new_string": "GAMMA"}, }, }) if b, _ := os.ReadFile(filepath.Join(dir, "f.go")); string(b) != "ALPHA beta GAMMA" { t.Fatalf("multiedit result: %q", b) } // A failing edit aborts the whole batch (file unchanged). r := run(t, NewMultiEdit(), dir, map[string]any{ "file_path": "f.go", "edits": []any{ map[string]any{"old_string": "beta", "new_string": "BETA"}, map[string]any{"old_string": "nonexistent", "new_string": "x"}, }, }) if !r.IsError { t.Fatal("expected error for unmatched edit") } if b, _ := os.ReadFile(filepath.Join(dir, "f.go")); string(b) != "ALPHA beta GAMMA" { t.Fatalf("file should be unchanged after failed multiedit: %q", b) } } func TestLS(t *testing.T) { dir := t.TempDir() os.WriteFile(filepath.Join(dir, "b.txt"), []byte("hi"), 0o644) os.MkdirAll(filepath.Join(dir, "sub"), 0o755) out := run(t, NewLS(), dir, map[string]any{}).Flatten() if !strings.Contains(out, "sub/") || !strings.Contains(out, "b.txt") { t.Fatalf("ls output: %q", out) } } func TestTodoWrite(t *testing.T) { store := NewTodoStore() st := store.Tool() res, _ := st.Call(context.Background(), []byte(`{"todos":[{"content":"build","status":"in_progress"},{"content":"test","status":"pending"}]}`), &ToolContext{}) items := store.List() if len(items) != 2 || items[0].Status != TodoInProgress { t.Fatalf("todos: %+v", items) } // tool_result is an ack, not the list (the list rides the tool_use input and // the todo system-reminder). if !strings.Contains(res.Flatten(), "successfully") || strings.Contains(res.Flatten(), "build") { t.Fatalf("expected ack without the list, got: %q", res.Flatten()) } } func TestRenderTodoReminder(t *testing.T) { if RenderTodoReminder(nil) != "" { t.Fatal("empty list should render as empty string") } out := RenderTodoReminder([]Todo{ {Content: "build", Status: TodoInProgress}, {Content: "test", Status: TodoPending}, }) want := "1. [in_progress] build\n2. [pending] test" if out != want { t.Fatalf("render:\n got %q\nwant %q", out, want) } } func TestWebFetch(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("content-type", "text/html") w.Write([]byte(`
Hello & bye
`)) })) defer srv.Close() raw, _ := json.Marshal(map[string]any{"url": srv.URL}) res, err := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{}) if err != nil { t.Fatalf("webfetch: %v", err) } out := res.Flatten() if !strings.Contains(out, "Title") || !strings.Contains(out, "Hello & bye") { t.Fatalf("text extraction: %q", out) } if strings.Contains(out, "secret") { t.Fatalf("script should be stripped: %q", out) } } func TestWebFetchRejectsStaticAssets(t *testing.T) { var hits int srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { hits++ w.Write([]byte("console.log(1)")) })) defer srv.Close() // .js/.css (and with a query string), images, fonts → rejected before any request. for _, path := range []string{"/app.js", "/main.css", "/bundle.min.js?v=3", "/logo.png", "/font.woff2"} { raw, _ := json.Marshal(map[string]any{"url": srv.URL + path}) res, err := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{}) if err != nil { t.Fatalf("webfetch %s: %v", path, err) } if !res.IsError || !strings.Contains(res.Flatten(), "static asset") { t.Fatalf("%s should be rejected as a static asset, got: %q (isErr=%v)", path, res.Flatten(), res.IsError) } } if hits != 0 { t.Fatalf("no network request should be made for static assets, got %d", hits) } // A normal page path still works. raw, _ := json.Marshal(map[string]any{"url": srv.URL + "/docs/guide"}) res, _ := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{}) if res.IsError { t.Fatalf("normal page path should not be rejected: %q", res.Flatten()) } } func TestProxyLikelyErr(t *testing.T) { // Proxy/MITM-caused failures → a direct retry may help. for _, s := range []string{ `Get "https://x/": EOF`, "proxyconnect tcp: dial tcp 127.0.0.1:8788: connect: connection refused", "read tcp: connection reset by peer", "http2: server sent GOAWAY", "remote error: tls: handshake failure", "malformed HTTP response", } { if !proxyLikelyErr(errors.New(s)) { t.Errorf("want retry (proxy-likely) for %q", s) } } // Target/caller problems → a direct retry won't fix them. for _, s := range []string{ "dial tcp: lookup nope.invalid: no such host", "context deadline exceeded", "context canceled", "net/http: request canceled (Client.Timeout exceeded while awaiting headers)", } { if proxyLikelyErr(errors.New(s)) { t.Errorf("want NO retry for %q", s) } } if proxyLikelyErr(nil) { t.Error("nil error must be false") } } // TestWebFetchProxyFallback proves a proxied fetch that fails for a proxy-caused // reason (here: the proxy port is dead → connection refused) retries once directly // (no proxy) and reaches the target. A successful fetch is not annotated. func TestWebFetchProxyFallback(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("content-type", "text/html") w.Write([]byte(`Para one
Para two