From 4bdc25c1272d7a7e53ee6fab1350b6a89d4a77a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=8E=E7=94=9F=E6=B4=BECoder=EF=BD=9E?= Date: Sat, 14 Feb 2026 09:49:48 +0800 Subject: [PATCH] fix shell allowlist initialization and add guard tests --- pkg/tools/shell.go | 8 +++++++- pkg/tools/shell_test.go | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/pkg/tools/shell.go b/pkg/tools/shell.go index 25ff5ee..26e735c 100644 --- a/pkg/tools/shell.go +++ b/pkg/tools/shell.go @@ -29,15 +29,21 @@ type ExecTool struct { } func NewExecTool(cfg config.ShellConfig, workspace string) *ExecTool { - denyPatterns := make([]*regexp.Regexp, 0) + denyPatterns := make([]*regexp.Regexp, 0, len(cfg.DeniedCmds)) for _, p := range cfg.DeniedCmds { denyPatterns = append(denyPatterns, regexp.MustCompile(`\b`+regexp.QuoteMeta(p)+`\b`)) } + allowPatterns := make([]*regexp.Regexp, 0, len(cfg.AllowedCmds)) + for _, p := range cfg.AllowedCmds { + allowPatterns = append(allowPatterns, regexp.MustCompile(`\b`+regexp.QuoteMeta(p)+`\b`)) + } + return &ExecTool{ workingDir: workspace, timeout: cfg.Timeout, denyPatterns: denyPatterns, + allowPatterns: allowPatterns, restrictToWorkspace: cfg.RestrictPath, sandboxEnabled: cfg.Sandbox.Enabled, sandboxImage: cfg.Sandbox.Image, diff --git a/pkg/tools/shell_test.go b/pkg/tools/shell_test.go index 2ececbb..2d7fef2 100644 --- a/pkg/tools/shell_test.go +++ b/pkg/tools/shell_test.go @@ -43,3 +43,21 @@ func TestAssessCommandRisk_GitCleanIsDestructive(t *testing.T) { t.Fatalf("expected git clean to be destructive, got %s", assessment.Level) } } + +func TestNewExecTool_LoadsAllowedCmdsIntoAllowPatterns(t *testing.T) { + tool := NewExecTool(config.ShellConfig{AllowedCmds: []string{"echo"}}, ".") + if len(tool.allowPatterns) != 1 { + t.Fatalf("expected one allow pattern, got %d", len(tool.allowPatterns)) + } +} + +func TestGuardCommand_BlocksCommandNotInAllowlist(t *testing.T) { + tool := NewExecTool(config.ShellConfig{AllowedCmds: []string{"echo"}}, ".") + if msg := tool.guardCommand("ls -la", "."); msg == "" { + t.Fatal("expected allowlist to block command not in allowed_cmds") + } + + if msg := tool.guardCommand("echo hi", "."); msg != "" { + t.Fatalf("expected allowed command to pass guard, got %q", msg) + } +}