feat(): safer script resolution

This commit is contained in:
Nicolas Carlier 2019-01-07 07:40:18 +00:00
parent 519b1afc67
commit 682b265d3e
2 changed files with 12 additions and 2 deletions

View File

@ -5,11 +5,15 @@ import (
"fmt" "fmt"
"os" "os"
"path" "path"
"strings"
) )
// ResolveScript is resolving the target script. // ResolveScript is resolving the target script.
func ResolveScript(dir, name string) (string, error) { func ResolveScript(dir, name string) (string, error) {
script := path.Join(dir, fmt.Sprintf("%s.sh", name)) script := path.Clean(path.Join(dir, fmt.Sprintf("%s.sh", name)))
if !strings.HasPrefix(script, dir) {
return "", errors.New("Invalid script path: " + name)
}
if _, err := os.Stat(script); os.IsNotExist(err) { if _, err := os.Stat(script); os.IsNotExist(err) {
return "", errors.New("Script not found: " + script) return "", errors.New("Script not found: " + script)
} }

View File

@ -8,7 +8,7 @@ import (
) )
func TestResolveScript(t *testing.T) { func TestResolveScript(t *testing.T) {
script, err := tools.ResolveScript("../../scripts", "echo") script, err := tools.ResolveScript("../../scripts", "../scripts/echo")
assert.Nil(t, err, "") assert.Nil(t, err, "")
assert.Equal(t, "../../scripts/echo.sh", script, "") assert.Equal(t, "../../scripts/echo.sh", script, "")
} }
@ -18,3 +18,9 @@ func TestNotResolveScript(t *testing.T) {
assert.NotNil(t, err, "") assert.NotNil(t, err, "")
assert.Equal(t, "Script not found: ../../scripts/foo.sh", err.Error(), "") assert.Equal(t, "Script not found: ../../scripts/foo.sh", err.Error(), "")
} }
func TestResolveBadScript(t *testing.T) {
_, err := tools.ResolveScript("../../scripts", "../tests/test_simple")
assert.NotNil(t, err, "")
assert.Equal(t, "Invalid script path: ../tests/test_simple", err.Error(), "")
}