33 lines
706 B
Go
33 lines
706 B
Go
package tools
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func resolvePath(baseDir, path string) (string, error) {
|
|
if path == "" {
|
|
path = "."
|
|
}
|
|
if filepath.IsAbs(path) {
|
|
return "", fmt.Errorf("absolute paths are not allowed; use a path relative to the project directory")
|
|
}
|
|
resolved := filepath.Clean(filepath.Join(baseDir, path))
|
|
if !isWithinDir(resolved, baseDir) {
|
|
return "", fmt.Errorf("path escapes the project directory: %s", path)
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
func isWithinDir(path, dir string) bool {
|
|
rel, err := filepath.Rel(dir, path)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
|
return false
|
|
}
|
|
return true
|
|
}
|