fix(tools): the path jail is a value each tool set owns, not a process global (#1921)

This commit is contained in:
sam committed 2026-11-13 03:47:34 +11:00
1 parent 1c191b4ee0
commit 65e6bafb23
11 files changed
+80 -76

No files matched your search

+9 -9
View File
@@ -1,18 +1,18 @@
package builtin package builtin
// RegisterBuiltins registers all built-in tools into the given registry. // RegisterBuiltins registers all built-in tools into the given registry. The
// The cwd parameter sets the working directory for file and shell operations. // jail governs the file tools; the shell runs in jail.Root.
func RegisterBuiltins(reg *Registry, cwd string) error { func RegisterBuiltins(reg *Registry, jail Jail) error {
mq := NewMutationQueue() mq := NewMutationQueue()
rt := NewReadTracker() rt := NewReadTracker()
builtins := []Tool{ builtins := []Tool{
NewReadTool(cwd, rt), NewReadTool(jail, rt),
NewWriteTool(cwd, mq, rt), NewWriteTool(jail, mq, rt),
NewEditTool(cwd, mq, rt), NewEditTool(jail, mq, rt),
NewShellTool(cwd, mq), NewShellTool(jail.Root, mq),
NewGrepTool(cwd), NewGrepTool(jail),
NewFindTool(cwd), NewFindTool(jail),
} }
for _, tool := range builtins { for _, tool := range builtins {
+7 -4
View File
@@ -15,9 +15,9 @@ var ErrPathNotAllowed = errors.New("path is outside the configured workspace")
// ResolveReadable resolves path as the read tool does, then follows // ResolveReadable resolves path as the read tool does, then follows
// symlinks and re-checks where they lead, so a link inside the workspace // 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. // cannot hand out a file outside it. The returned path has no symlinks.
func ResolveReadable(cwd, path string) (string, error) { func ResolveReadable(jail Jail, path string) (string, error) {
resolved := resolvePath(cwd, path) resolved := resolvePath(jail.Root, path)
if !isReadConfined(cwd, resolved) { if !jail.ReadConfines(resolved) {
return "", fmt.Errorf("%w: %s", ErrPathNotAllowed, resolved) return "", fmt.Errorf("%w: %s", ErrPathNotAllowed, resolved)
} }
target, err := filepath.EvalSymlinks(resolved) target, err := filepath.EvalSymlinks(resolved)
@@ -28,8 +28,11 @@ func ResolveReadable(cwd, path string) (string, error) {
if err != nil { if err != nil {
return "", fmt.Errorf("resolve %s: %w", resolved, err) 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() 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 "", fmt.Errorf("%w: %s links to %s", ErrPathNotAllowed, resolved, target)
} }
return target, nil return target, nil
+1 -1
View File
@@ -45,7 +45,7 @@ func TestResolveReadableFollowsSymlinks(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { 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 { if tt.allowed && err != nil {
t.Fatalf("want allowed, got %v", err) t.Fatalf("want allowed, got %v", err)
} }
+13 -8
View File
@@ -63,12 +63,12 @@ var editSchema = Schema{
} }
// NewEditTool creates the built-in edit tool. // 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{ return Tool{
Schema: editSchema, Schema: editSchema,
Source: "builtin", Source: "builtin",
Emoji: "✏️", 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 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) { return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) {
p, err := parseEditParams(params) p, err := parseEditParams(params)
if err != nil { if err != nil {
@@ -127,7 +128,7 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor {
path := resolvePath(cwd, p.Path) path := resolvePath(cwd, p.Path)
if !isConfined(cwd, path) { if !jail.Confines(path) {
return Result{Content: "path escapes working directory", IsError: true}, nil 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) newContent, err := applyEdits(content, p.Edits)
if err != nil { if err != nil {
errorKind := "invalid_arguments" errorKind := "invalid_arguments"
if strings.Contains(err.Error(), "old_text not found") { if errors.Is(err, errOldTextNotFound) {
errorKind = "stale_edit" errorKind = "stale_edit"
} }
return Result{ return Result{
@@ -322,12 +323,16 @@ func renderSpans(content string, spans []editSpan) string {
return b.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 { 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 != "" { 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 // nearestMatchHint quotes the file's text where a failed old_text most likely
+5 -4
View File
@@ -56,16 +56,17 @@ var findSchema = Schema{
} }
// NewFindTool creates the built-in find tool. // NewFindTool creates the built-in find tool.
func NewFindTool(cwd string) Tool { func NewFindTool(jail Jail) Tool {
return Tool{ return Tool{
Schema: findSchema, Schema: findSchema,
Source: "builtin", Source: "builtin",
Emoji: "📁", 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) { return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) {
var p FindParams var p FindParams
if err := json.Unmarshal(params, &p); err != nil { if err := json.Unmarshal(params, &p); err != nil {
@@ -80,7 +81,7 @@ func makeFindExecutor(cwd string) Executor {
searchPath = resolvePath(cwd, p.Path) 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 return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil
} }
+5 -4
View File
@@ -89,16 +89,17 @@ var grepSchema = Schema{
// NewGrepTool creates the built-in grep tool. // NewGrepTool creates the built-in grep tool.
func NewGrepTool(cwd string) Tool { func NewGrepTool(jail Jail) Tool {
return Tool{ return Tool{
Schema: grepSchema, Schema: grepSchema,
Source: "builtin", Source: "builtin",
Emoji: "🔍", 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) { return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) {
var p GrepParams var p GrepParams
if err := json.Unmarshal(params, &p); err != nil { if err := json.Unmarshal(params, &p); err != nil {
@@ -119,7 +120,7 @@ func makeGrepExecutor(cwd string) Executor {
searchPath = resolvePath(cwd, p.Path) 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 return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil
} }
+25 -29
View File
@@ -5,7 +5,6 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"sync" "sync"
"sync/atomic"
) )
const ( const (
@@ -44,36 +43,23 @@ var goModCacheDir = sync.OnceValue(func() string {
return filepath.Join(home, "go", "pkg", "mod") return filepath.Join(home, "go", "pkg", "mod")
}) })
// isReadConfined reports whether a read may touch target: the workspace or // Jail is the path policy one set of file tools runs under. It is a value
// the Go module cache. // owned by its caller, so two providers in one process cannot disagree about
func isReadConfined(base, target string) bool { // it.
if isConfined(base, target) { type Jail struct {
return true // Root is the workspace directory. Relative paths resolve against it.
} Root string
cache := goModCacheDir() // Unrestricted lifts the jail: any absolute path is allowed.
return cache != "" && isConfined(cache, target) Unrestricted bool
} }
// pathConfinement gates the workspace jail on the file tools. On by default. // Confines reports whether target is within (or equal to) j.Root. It returns
var pathConfinement atomic.Bool // false when target escapes via ../ or is an unrelated absolute path.
func (j Jail) Confines(target string) bool {
func init() { pathConfinement.Store(true) } if j.Unrestricted || j.Root == "" {
return true // no jail when unrestricted, or when no root is set
// 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
} }
if base == "" { rootAbs, err := filepath.Abs(j.Root)
return true // no confinement if cwd is unset
}
baseAbs, err := filepath.Abs(base)
if err != nil { if err != nil {
return false return false
} }
@@ -82,9 +68,19 @@ func isConfined(base, target string) bool {
return false return false
} }
rel, err := filepath.Rel(baseAbs, targetAbs) rel, err := filepath.Rel(rootAbs, targetAbs)
if err != nil { if err != nil {
return false return false
} }
return !strings.HasPrefix(rel, "..") && rel != ".." 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)
}
+5 -4
View File
@@ -184,16 +184,17 @@ func listDirResult(path, display string) (Result, error) {
} }
// NewReadTool creates the built-in read tool. // NewReadTool creates the built-in read tool.
func NewReadTool(cwd string, rt *ReadTracker) Tool { func NewReadTool(jail Jail, rt *ReadTracker) Tool {
return Tool{ return Tool{
Schema: readSchema, Schema: readSchema,
Source: "builtin", Source: "builtin",
Emoji: "📄", 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) { return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) {
p, terminal, err := parseReadParams(params) p, terminal, err := parseReadParams(params)
if err != nil { if err != nil {
@@ -204,7 +205,7 @@ func makeReadExecutor(cwd string, rt *ReadTracker) Executor {
} }
path := resolvePath(cwd, p.Path) 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 return Result{Content: "path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil
} }
+5 -4
View File
@@ -42,16 +42,17 @@ var writeSchema = Schema{
} }
// NewWriteTool creates the built-in write tool. // 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{ return Tool{
Schema: writeSchema, Schema: writeSchema,
Source: "builtin", Source: "builtin",
Emoji: "📝", 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) { return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) {
var p WriteParams var p WriteParams
if err := json.Unmarshal(params, &p); err != nil { 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) path := resolvePath(cwd, p.Path)
if !isConfined(cwd, path) { if !jail.Confines(path) {
return Result{Content: "path escapes working directory", IsError: true}, nil return Result{Content: "path escapes working directory", IsError: true}, nil
} }
+2 -6
View File
@@ -56,13 +56,9 @@ func (p *Provider) Start(ctx context.Context) error {
if p.workspace == "" { if p.workspace == "" {
return errors.New("workspace tool provider: workspace directory is not configured") 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() 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) return fmt.Errorf("workspace tool provider: register builtins: %w", err)
} }
p.registry = registry p.registry = registry
+3 -3
View File
@@ -68,7 +68,7 @@ func Tool(workspace string) *tools.ToolEntry {
Handler: func(_ context.Context, input map[string]any) (any, error) { Handler: func(_ context.Context, input map[string]any) (any, error) {
path, _ := input["path"].(string) path, _ := input["path"].(string)
caption, _ := input["caption"].(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 // prepare validates the request and returns the result describing the
// delivery. Every return path other than the final one is an error: a // 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. // 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) == "" { if strings.TrimSpace(path) == "" {
return tools.MultimodalResult{}, fmt.Errorf("%s: path is required", ToolName) 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 { if err != nil {
return tools.MultimodalResult{}, fmt.Errorf("%s: %w", ToolName, err) return tools.MultimodalResult{}, fmt.Errorf("%s: %w", ToolName, err)
} }