45 lines
1.4 KiB
Go
45 lines
1.4 KiB
Go
// Not lifted from tau: archie-original. It exports the read tool's own
|
|
// path policy so a tool outside this package cannot end up applying a
|
|
// second, subtly different one.
|
|
package builtin
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
)
|
|
|
|
// ErrPathNotAllowed reports a path refused by the workspace confinement.
|
|
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) {
|
|
return "", fmt.Errorf("%w: %s", ErrPathNotAllowed, resolved)
|
|
}
|
|
target, err := filepath.EvalSymlinks(resolved)
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve %s: %w", resolved, err)
|
|
}
|
|
target, err = filepath.Abs(target)
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve %s: %w", resolved, err)
|
|
}
|
|
cache := goModCacheDir()
|
|
if !isConfined(realDir(cwd), target) && (cache == "" || !isConfined(realDir(cache), target)) {
|
|
return "", fmt.Errorf("%w: %s links to %s", ErrPathNotAllowed, resolved, target)
|
|
}
|
|
return target, nil
|
|
}
|
|
|
|
// realDir returns dir with symlinks resolved, or dir when it cannot be.
|
|
func realDir(dir string) string {
|
|
if r, err := filepath.EvalSymlinks(dir); err == nil {
|
|
return r
|
|
}
|
|
return dir
|
|
}
|