mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
CodeQL: Try to fix uncontrolled data used in path expression (#43462)
Ref #43080
This commit is contained in:
committed by
GitHub
parent
2a766c6a04
commit
f6414ea2b2
@@ -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
37
pkg/util/filepath_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user