Skip to content

Commit 7f53514

Browse files
authored
Fix : sanitize PATH dir (#665)
Actually comparaison between .krew/bin directory and path segment directory is done with equal operator. This PR allow method filepath.Abs to be call during krew path creation /internal/environment/environment.go#L43 and also in /cmd/krew/cmd/internal/setup_check.go#L62 path directory iteration
1 parent 00bd183 commit 7f53514

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

cmd/krew/cmd/internal/setup_check.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,12 @@ func IsBinDirInPATH(paths environment.Paths) bool {
5858

5959
binPath := paths.BinPath()
6060
for _, dirInPATH := range filepath.SplitList(os.Getenv("PATH")) {
61-
if dirInPATH == binPath {
61+
normalizedDirInPATH, err := filepath.Abs(dirInPATH)
62+
if err != nil {
63+
klog.Warningf("Cannot get absolute path: %v, %v", normalizedDirInPATH, err)
64+
continue
65+
}
66+
if normalizedDirInPATH == binPath {
6267
return true
6368
}
6469
}

cmd/krew/cmd/internal/setup_check_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ import (
2323
"sigs.k8s.io/krew/internal/testutil"
2424
)
2525

26+
const environmentPath = "/home/../home/user//./.krew"
27+
2628
func TestIsBinDirInPATH_firstRun(t *testing.T) {
2729
tempDir := testutil.NewTempDir(t)
2830

@@ -43,6 +45,35 @@ func TestIsBinDirInPATH_secondRun(t *testing.T) {
4345
}
4446
}
4547

48+
// TestIsBinDirInPATH_NonNormalized case when PATH content is not well normalized
49+
func TestIsBinDirInPATH_NonNormalized(t *testing.T) {
50+
tempDir := testutil.NewTempDir(t)
51+
52+
// backup and restore initial PATH value
53+
defer func(backupPath string) {
54+
err := os.Setenv("PATH", backupPath)
55+
if err != nil {
56+
t.Fatalf(`os.Setenv("PATH", %s) failed with %v`, backupPath, err)
57+
}
58+
}(os.Getenv("PATH"))
59+
60+
// set PATH with non-normalized folder path
61+
err := os.Setenv("PATH", tempDir.Path(environmentPath+"/bin"))
62+
if err != nil {
63+
t.Fatalf(`os.Setenv("PATH", %s/bin) failed with %v`, environmentPath, err)
64+
}
65+
paths := environment.NewPaths(tempDir.Path(environmentPath))
66+
err = os.MkdirAll(paths.BasePath(), os.ModePerm)
67+
if err != nil {
68+
t.Fatalf("os.MkdirAll(%s) failed with %v", paths.BasePath(), err)
69+
}
70+
71+
got := IsBinDirInPATH(paths)
72+
if got == false {
73+
t.Errorf("IsBinDirPATH(%v) = %t, want true", paths, got)
74+
}
75+
}
76+
4677
func TestSetupInstructions_windows(t *testing.T) {
4778
const instructionsContain = `USERPROFILE`
4879
os.Setenv("KREW_OS", "windows")

0 commit comments

Comments
 (0)