From 65e6bafb23d78207a32a052799cdfdf7b31ec190 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 13 Nov 2026 03:44:49 +1100 Subject: [PATCH] fix(tools): the path jail is a value each tool set owns, not a process global (#1921) --- internal/tools/builtin/builtin.go | 18 +++---- internal/tools/builtin/confinement.go | 11 +++-- internal/tools/builtin/confinement_test.go | 2 +- internal/tools/builtin/edit.go | 21 +++++--- internal/tools/builtin/find.go | 9 ++-- internal/tools/builtin/grep.go | 9 ++-- internal/tools/builtin/pathutil.go | 54 ++++++++++----------- internal/tools/builtin/read.go | 9 ++-- internal/tools/builtin/write.go | 9 ++-- internal/tools/provider/builtin/provider.go | 8 +-- internal/tools/sendfile/tool.go | 6 +-- 11 files changed, 80 insertions(+), 76 deletions(-) diff --git a/internal/tools/builtin/builtin.go b/internal/tools/builtin/builtin.go index a035767b2..2acf0e26c 100644 --- a/internal/tools/builtin/builtin.go +++ b/internal/tools/builtin/builtin.go @@ -1,18 +1,18 @@ package builtin -// RegisterBuiltins registers all built-in tools into the given registry. -// The cwd parameter sets the working directory for file and shell operations. -func RegisterBuiltins(reg *Registry, cwd string) error { +// RegisterBuiltins registers all built-in tools into the given registry. The +// jail governs the file tools; the shell runs in jail.Root. +func RegisterBuiltins(reg *Registry, jail Jail) error { mq := NewMutationQueue() rt := NewReadTracker() builtins := []Tool{ - NewReadTool(cwd, rt), - NewWriteTool(cwd, mq, rt), - NewEditTool(cwd, mq, rt), - NewShellTool(cwd, mq), - NewGrepTool(cwd), - NewFindTool(cwd), + NewReadTool(jail, rt), + NewWriteTool(jail, mq, rt), + NewEditTool(jail, mq, rt), + NewShellTool(jail.Root, mq), + NewGrepTool(jail), + NewFindTool(jail), } for _, tool := range builtins { diff --git a/internal/tools/builtin/confinement.go b/internal/tools/builtin/confinement.go index dad875788..79ff2089f 100644 --- a/internal/tools/builtin/confinement.go +++ b/internal/tools/builtin/confinement.go @@ -15,9 +15,9 @@ var ErrPathNotAllowed = errors.New("path is outside the configured workspace") // ResolveReadable resolves path as the read tool does, then follows // symlinks and re-checks where they lead, so a link inside the workspace // cannot hand out a file outside it. The returned path has no symlinks. -func ResolveReadable(cwd, path string) (string, error) { - resolved := resolvePath(cwd, path) - if !isReadConfined(cwd, resolved) { +func ResolveReadable(jail Jail, path string) (string, error) { + resolved := resolvePath(jail.Root, path) + if !jail.ReadConfines(resolved) { return "", fmt.Errorf("%w: %s", ErrPathNotAllowed, resolved) } target, err := filepath.EvalSymlinks(resolved) @@ -28,8 +28,11 @@ func ResolveReadable(cwd, path string) (string, error) { if err != nil { return "", fmt.Errorf("resolve %s: %w", resolved, err) } + // Compare against the real root: target has its symlinks resolved. + root := Jail{Root: realDir(jail.Root), Unrestricted: jail.Unrestricted} cache := goModCacheDir() - if !isConfined(realDir(cwd), target) && (cache == "" || !isConfined(realDir(cache), target)) { + inCache := cache != "" && Jail{Root: realDir(cache)}.Confines(target) + if !root.Confines(target) && !inCache { return "", fmt.Errorf("%w: %s links to %s", ErrPathNotAllowed, resolved, target) } return target, nil diff --git a/internal/tools/builtin/confinement_test.go b/internal/tools/builtin/confinement_test.go index a51e15e21..b538d7fdb 100644 --- a/internal/tools/builtin/confinement_test.go +++ b/internal/tools/builtin/confinement_test.go @@ -45,7 +45,7 @@ func TestResolveReadableFollowsSymlinks(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := ResolveReadable(tt.cwd, tt.path) + _, err := ResolveReadable(Jail{Root: tt.cwd}, tt.path) if tt.allowed && err != nil { t.Fatalf("want allowed, got %v", err) } diff --git a/internal/tools/builtin/edit.go b/internal/tools/builtin/edit.go index daeead780..a5d88101c 100644 --- a/internal/tools/builtin/edit.go +++ b/internal/tools/builtin/edit.go @@ -63,12 +63,12 @@ var editSchema = Schema{ } // NewEditTool creates the built-in edit tool. -func NewEditTool(cwd string, mq *MutationQueue, rt *ReadTracker) Tool { +func NewEditTool(jail Jail, mq *MutationQueue, rt *ReadTracker) Tool { return Tool{ Schema: editSchema, Source: "builtin", Emoji: "✏️", - Execute: makeEditExecutor(cwd, mq, rt), + Execute: makeEditExecutor(jail, mq, rt), } } @@ -114,7 +114,8 @@ func parseEditParams(params json.RawMessage) (EditParams, error) { return p, nil } -func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { +func makeEditExecutor(jail Jail, mq *MutationQueue, rt *ReadTracker) Executor { + cwd := jail.Root return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { p, err := parseEditParams(params) if err != nil { @@ -127,7 +128,7 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { path := resolvePath(cwd, p.Path) - if !isConfined(cwd, path) { + if !jail.Confines(path) { return Result{Content: "path escapes working directory", IsError: true}, nil } @@ -193,7 +194,7 @@ func performEdit(path string, p EditParams, mq *MutationQueue) Result { newContent, err := applyEdits(content, p.Edits) if err != nil { errorKind := "invalid_arguments" - if strings.Contains(err.Error(), "old_text not found") { + if errors.Is(err, errOldTextNotFound) { errorKind = "stale_edit" } return Result{ @@ -322,12 +323,16 @@ func renderSpans(content string, spans []editSpan) string { return b.String() } +// errOldTextNotFound marks an edit whose old_text is not in the file. The +// executor maps it to the stale_edit error kind. +var errOldTextNotFound = errors.New("old_text not found in file") + func editNotFoundError(idx int, content, oldText string) error { - base := fmt.Sprintf("edit %d: old_text not found in file; it must match exactly, including whitespace and indentation", idx+1) + base := fmt.Errorf("edit %d: %w; it must match exactly, including whitespace and indentation", idx+1, errOldTextNotFound) if hint := nearestMatchHint(content, oldText); hint != "" { - return fmt.Errorf("%s\n%s", base, hint) + return fmt.Errorf("%w\n%s", base, hint) } - return errors.New(base) + return base } // nearestMatchHint quotes the file's text where a failed old_text most likely diff --git a/internal/tools/builtin/find.go b/internal/tools/builtin/find.go index 637d0b16f..56872d576 100644 --- a/internal/tools/builtin/find.go +++ b/internal/tools/builtin/find.go @@ -56,16 +56,17 @@ var findSchema = Schema{ } // NewFindTool creates the built-in find tool. -func NewFindTool(cwd string) Tool { +func NewFindTool(jail Jail) Tool { return Tool{ Schema: findSchema, Source: "builtin", Emoji: "📁", - Execute: makeFindExecutor(cwd), + Execute: makeFindExecutor(jail), } } -func makeFindExecutor(cwd string) Executor { +func makeFindExecutor(jail Jail) Executor { + cwd := jail.Root return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { var p FindParams if err := json.Unmarshal(params, &p); err != nil { @@ -80,7 +81,7 @@ func makeFindExecutor(cwd string) Executor { searchPath = resolvePath(cwd, p.Path) } - if !isConfined(cwd, searchPath) { + if !jail.Confines(searchPath) { return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } diff --git a/internal/tools/builtin/grep.go b/internal/tools/builtin/grep.go index 42af846de..c407ba0a5 100644 --- a/internal/tools/builtin/grep.go +++ b/internal/tools/builtin/grep.go @@ -89,16 +89,17 @@ var grepSchema = Schema{ // NewGrepTool creates the built-in grep tool. -func NewGrepTool(cwd string) Tool { +func NewGrepTool(jail Jail) Tool { return Tool{ Schema: grepSchema, Source: "builtin", Emoji: "🔍", - Execute: makeGrepExecutor(cwd), + Execute: makeGrepExecutor(jail), } } -func makeGrepExecutor(cwd string) Executor { +func makeGrepExecutor(jail Jail) Executor { + cwd := jail.Root return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { var p GrepParams if err := json.Unmarshal(params, &p); err != nil { @@ -119,7 +120,7 @@ func makeGrepExecutor(cwd string) Executor { searchPath = resolvePath(cwd, p.Path) } - if !isConfined(cwd, searchPath) { + if !jail.Confines(searchPath) { return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } diff --git a/internal/tools/builtin/pathutil.go b/internal/tools/builtin/pathutil.go index c89ec8e76..60bcdc0fb 100644 --- a/internal/tools/builtin/pathutil.go +++ b/internal/tools/builtin/pathutil.go @@ -5,7 +5,6 @@ import ( "path/filepath" "strings" "sync" - "sync/atomic" ) const ( @@ -44,36 +43,23 @@ var goModCacheDir = sync.OnceValue(func() string { return filepath.Join(home, "go", "pkg", "mod") }) -// isReadConfined reports whether a read may touch target: the workspace or -// the Go module cache. -func isReadConfined(base, target string) bool { - if isConfined(base, target) { - return true - } - cache := goModCacheDir() - return cache != "" && isConfined(cache, target) +// Jail is the path policy one set of file tools runs under. It is a value +// owned by its caller, so two providers in one process cannot disagree about +// it. +type Jail struct { + // Root is the workspace directory. Relative paths resolve against it. + Root string + // Unrestricted lifts the jail: any absolute path is allowed. + Unrestricted bool } -// pathConfinement gates the workspace jail on the file tools. On by default. -var pathConfinement atomic.Bool - -func init() { pathConfinement.Store(true) } - -// SetPathConfinement turns the workspace jail on the read, write, edit, find -// and grep tools on or off. Relative paths always resolve against the -// workspace. -func SetPathConfinement(enabled bool) { pathConfinement.Store(enabled) } - -// isConfined checks whether target is within (or equal to) the base directory. -// Returns false if target escapes via ../ or is an unrelated absolute path. -func isConfined(base, target string) bool { - if !pathConfinement.Load() { - return true // confinement disabled by configuration +// Confines reports whether target is within (or equal to) j.Root. It returns +// false when target escapes via ../ or is an unrelated absolute path. +func (j Jail) Confines(target string) bool { + if j.Unrestricted || j.Root == "" { + return true // no jail when unrestricted, or when no root is set } - if base == "" { - return true // no confinement if cwd is unset - } - baseAbs, err := filepath.Abs(base) + rootAbs, err := filepath.Abs(j.Root) if err != nil { return false } @@ -82,9 +68,19 @@ func isConfined(base, target string) bool { return false } - rel, err := filepath.Rel(baseAbs, targetAbs) + rel, err := filepath.Rel(rootAbs, targetAbs) if err != nil { return false } return !strings.HasPrefix(rel, "..") && rel != ".." } + +// ReadConfines reports whether a read may touch target: the jail root or the +// Go module cache. +func (j Jail) ReadConfines(target string) bool { + if j.Confines(target) { + return true + } + cache := goModCacheDir() + return cache != "" && Jail{Root: cache}.Confines(target) +} diff --git a/internal/tools/builtin/read.go b/internal/tools/builtin/read.go index 4a06642da..905c93b59 100644 --- a/internal/tools/builtin/read.go +++ b/internal/tools/builtin/read.go @@ -184,16 +184,17 @@ func listDirResult(path, display string) (Result, error) { } // NewReadTool creates the built-in read tool. -func NewReadTool(cwd string, rt *ReadTracker) Tool { +func NewReadTool(jail Jail, rt *ReadTracker) Tool { return Tool{ Schema: readSchema, Source: "builtin", Emoji: "📄", - Execute: makeReadExecutor(cwd, rt), + Execute: makeReadExecutor(jail, rt), } } -func makeReadExecutor(cwd string, rt *ReadTracker) Executor { +func makeReadExecutor(jail Jail, rt *ReadTracker) Executor { + cwd := jail.Root return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { p, terminal, err := parseReadParams(params) if err != nil { @@ -204,7 +205,7 @@ func makeReadExecutor(cwd string, rt *ReadTracker) Executor { } path := resolvePath(cwd, p.Path) - if !isReadConfined(cwd, path) { + if !jail.ReadConfines(path) { return Result{Content: "path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } diff --git a/internal/tools/builtin/write.go b/internal/tools/builtin/write.go index fdf8a807d..e8f588d56 100644 --- a/internal/tools/builtin/write.go +++ b/internal/tools/builtin/write.go @@ -42,16 +42,17 @@ var writeSchema = Schema{ } // NewWriteTool creates the built-in write tool. -func NewWriteTool(cwd string, mq *MutationQueue, rt *ReadTracker) Tool { +func NewWriteTool(jail Jail, mq *MutationQueue, rt *ReadTracker) Tool { return Tool{ Schema: writeSchema, Source: "builtin", Emoji: "📝", - Execute: makeWriteExecutor(cwd, mq, rt), + Execute: makeWriteExecutor(jail, mq, rt), } } -func makeWriteExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { +func makeWriteExecutor(jail Jail, mq *MutationQueue, rt *ReadTracker) Executor { + cwd := jail.Root return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { var p WriteParams if err := json.Unmarshal(params, &p); err != nil { @@ -64,7 +65,7 @@ func makeWriteExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor path := resolvePath(cwd, p.Path) - if !isConfined(cwd, path) { + if !jail.Confines(path) { return Result{Content: "path escapes working directory", IsError: true}, nil } diff --git a/internal/tools/provider/builtin/provider.go b/internal/tools/provider/builtin/provider.go index dcba840ca..18a7e24ec 100644 --- a/internal/tools/provider/builtin/provider.go +++ b/internal/tools/provider/builtin/provider.go @@ -56,13 +56,9 @@ func (p *Provider) Start(ctx context.Context) error { if p.workspace == "" { return errors.New("workspace tool provider: workspace directory is not configured") } - // Set before the tools are built. Confinement is consulted per call, so - // ordering only matters in that it must precede the first tool call, but - // keeping it next to construction is where a reader will look for it. - toolsbuiltin.SetPathConfinement(!p.unrestricted) - registry := toolsbuiltin.NewRegistry() - if err := toolsbuiltin.RegisterBuiltins(registry, p.workspace); err != nil { + jail := toolsbuiltin.Jail{Root: p.workspace, Unrestricted: p.unrestricted} + if err := toolsbuiltin.RegisterBuiltins(registry, jail); err != nil { return fmt.Errorf("workspace tool provider: register builtins: %w", err) } p.registry = registry diff --git a/internal/tools/sendfile/tool.go b/internal/tools/sendfile/tool.go index 5f7b80eb7..ed6cb60c2 100644 --- a/internal/tools/sendfile/tool.go +++ b/internal/tools/sendfile/tool.go @@ -68,7 +68,7 @@ func Tool(workspace string) *tools.ToolEntry { Handler: func(_ context.Context, input map[string]any) (any, error) { path, _ := input["path"].(string) caption, _ := input["caption"].(string) - return prepare(workspace, path, caption) + return prepare(builtin.Jail{Root: workspace}, path, caption) }, } } @@ -80,12 +80,12 @@ var errNotRegularFile = errors.New("not a regular file") // prepare validates the request and returns the result describing the // delivery. Every return path other than the final one is an error: a // caller must never be able to read "sent" out of a failed preparation. -func prepare(workspace, path, caption string) (tools.MultimodalResult, error) { +func prepare(jail builtin.Jail, path, caption string) (tools.MultimodalResult, error) { if strings.TrimSpace(path) == "" { return tools.MultimodalResult{}, fmt.Errorf("%s: path is required", ToolName) } - resolved, err := builtin.ResolveReadable(workspace, path) + resolved, err := builtin.ResolveReadable(jail, path) if err != nil { return tools.MultimodalResult{}, fmt.Errorf("%s: %w", ToolName, err) }