CodeQL: Try to fix uncontrolled data used in path expression (#43462)

Ref #43080
This commit is contained in:
Marcus Efraimsson
2022-01-11 17:37:58 +01:00
committed by GitHub
parent 2a766c6a04
commit f6414ea2b2
4 changed files with 97 additions and 3 deletions

View File

@@ -138,3 +138,19 @@ func containsDistFolder(subFiles []subFile) bool {
return false
}
// CleanRelativePath returns the shortest path name equivalent to path
// by purely lexical processing. It make sure the provided path is rooted
// and then uses filepath.Clean and filepath.Rel to make sure the path
// doesn't include any separators or elements that shouldn't be there
// like ., .., //.
func CleanRelativePath(path string) (string, error) {
cleanPath := filepath.Clean(filepath.Join("/", path))
rel, err := filepath.Rel("/", cleanPath)
if err != nil {
// slash is prepended above therefore this is not expected to fail
return "", err
}
return rel, nil
}

37
pkg/util/filepath_test.go Normal file
View File

@@ -0,0 +1,37 @@
package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCleanRelativePath(t *testing.T) {
testcases := []struct {
input string
expectedPath string
}{
{
input: "",
expectedPath: ".",
},
{
input: "/test/test.txt",
expectedPath: "test/test.txt",
},
{
input: "../../test/test.txt",
expectedPath: "test/test.txt",
},
{
input: "./../test/test.txt",
expectedPath: "test/test.txt",
},
}
for _, tt := range testcases {
path, err := CleanRelativePath(tt.input)
assert.NoError(t, err)
assert.Equal(t, tt.expectedPath, path)
}
}