From 72d18c99afdb3d126589dea4209c06d2a2201c36 Mon Sep 17 00:00:00 2001 From: ParthSareen Date: Thu, 11 Jun 2026 21:00:21 -0700 Subject: [PATCH] agent: validate bash working directory --- agent/tools/bash.go | 10 +++++++++- agent/tools/bash_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/agent/tools/bash.go b/agent/tools/bash.go index 79e54cb39..538d7ab2c 100644 --- a/agent/tools/bash.go +++ b/agent/tools/bash.go @@ -113,7 +113,15 @@ func readFinalWorkingDir(path string) string { if err != nil { return "" } - return strings.TrimSpace(string(content)) + workingDir := strings.TrimSpace(string(content)) + if workingDir == "" { + return "" + } + info, err := os.Stat(workingDir) + if err != nil || !info.IsDir() { + return "" + } + return workingDir } func shellQuote(value string) string { diff --git a/agent/tools/bash_test.go b/agent/tools/bash_test.go index 6053cf302..ee5d827be 100644 --- a/agent/tools/bash_test.go +++ b/agent/tools/bash_test.go @@ -34,3 +34,33 @@ func TestBashReportsFinalWorkingDir(t *testing.T) { t.Fatalf("content = %q, want pwd output", result.Content) } } + +func TestReadFinalWorkingDirRejectsInvalidPaths(t *testing.T) { + dir := t.TempDir() + cwdFile := filepath.Join(dir, "cwd") + notDir := filepath.Join(dir, "file.txt") + if err := os.WriteFile(notDir, []byte("not a dir"), 0o644); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(cwdFile, []byte(notDir+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if got := readFinalWorkingDir(cwdFile); got != "" { + t.Fatalf("regular file cwd = %q, want empty", got) + } + + if err := os.WriteFile(cwdFile, []byte(filepath.Join(dir, "missing")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if got := readFinalWorkingDir(cwdFile); got != "" { + t.Fatalf("missing cwd = %q, want empty", got) + } + + if err := os.WriteFile(cwdFile, []byte(dir+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if got := readFinalWorkingDir(cwdFile); got != dir { + t.Fatalf("directory cwd = %q, want %q", got, dir) + } +}