// 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(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) 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) } // Compare against the real root: target has its symlinks resolved. root := Jail{Root: realDir(jail.Root), Unrestricted: jail.Unrestricted} cache := goModCacheDir() 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 } // 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 }