mirror of
https://github.com/docker/docker-agent.git
synced 2026-11-06 15:07:58 +00:00
Add modernize and perfsprint to .golangci.yml and resolve all lint issues across 97 files: - Replace fmt.Errorf with errors.New where no format verbs are used - Replace fmt.Sprintf(%d) with strconv.Itoa for int conversions - Replace redundant fmt.Sprintf(%s) with direct string values - Use slices.Contains instead of manual loops (SkillsConfig.HasLocal) - Use omitzero instead of omitempty on struct fields (time.Time, SkillsConfig) - Inline boolPtr helpers to new(bool) and remove unused functions - Replace string concatenation in loops with strings.Builder - Use fmt.Fprintf instead of WriteString(fmt.Sprintf(...)) Assisted-By: docker-agent
64 lines
1.4 KiB
Go
64 lines
1.4 KiB
Go
package path
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func ValidatePathInDirectory(path, allowedDir string) (string, error) {
|
|
if path == "" {
|
|
return "", errors.New("empty path")
|
|
}
|
|
|
|
cleanPath := filepath.Clean(path)
|
|
|
|
if cleanPath == "" || cleanPath == "." {
|
|
return "", errors.New("empty or invalid path")
|
|
}
|
|
|
|
if filepath.IsAbs(cleanPath) && allowedDir == "" {
|
|
if strings.Contains(path, "..") {
|
|
return "", errors.New("path contains directory traversal sequences")
|
|
}
|
|
return cleanPath, nil
|
|
}
|
|
|
|
if allowedDir == "" {
|
|
if strings.HasPrefix(cleanPath, "..") {
|
|
return "", errors.New("path contains directory traversal sequences")
|
|
}
|
|
return cleanPath, nil
|
|
}
|
|
|
|
cleanAllowedDir := filepath.Clean(allowedDir)
|
|
absAllowedDir, err := filepath.Abs(cleanAllowedDir)
|
|
if err != nil {
|
|
return "", fmt.Errorf("invalid allowed directory: %w", err)
|
|
}
|
|
|
|
var targetPath string
|
|
if filepath.IsAbs(cleanPath) {
|
|
targetPath = cleanPath
|
|
} else {
|
|
targetPath = filepath.Join(absAllowedDir, cleanPath)
|
|
}
|
|
|
|
absTargetPath, err := filepath.Abs(targetPath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("invalid path: %w", err)
|
|
}
|
|
|
|
relPath, err := filepath.Rel(absAllowedDir, absTargetPath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("cannot determine relative path: %w", err)
|
|
}
|
|
|
|
if strings.HasPrefix(relPath, "..") {
|
|
return "", fmt.Errorf("path outside allowed directory: %s", path)
|
|
}
|
|
|
|
return absTargetPath, nil
|
|
}
|