瀏覽代碼

fix: deny copy folder to itself or subpath (#1299)

mmetc 3 年之前
父節點
當前提交
c5dda0ffba
共有 2 個文件被更改,包括 48 次插入3 次删除
  1. 30 3
      pkg/cstest/utils.go
  2. 18 0
      pkg/cstest/utils_test.go

+ 30 - 3
pkg/cstest/utils.go

@@ -4,6 +4,7 @@ import (
 	"fmt"
 	"io/ioutil"
 	"os"
+	"path/filepath"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -22,10 +23,36 @@ func Copy(sourceFile string, destinationFile string) error {
 	return nil
 }
 
-func CopyDir(src string, dest string) error {
+// checkPathNotContained returns an error if 'subpath' is inside 'path'
+func checkPathNotContained(path string, subpath string) error {
+	absPath, err := filepath.Abs(path)
+	if err != nil {
+		return err
+	}
 
-	if dest[:len(src)] == src {
-		return fmt.Errorf("Cannot copy a folder into the folder itself!")
+	absSubPath, err := filepath.Abs(subpath)
+	if err != nil {
+		return err
+	}
+
+	current := absSubPath
+	for {
+		if current == absPath {
+			return fmt.Errorf("cannot copy a folder onto itself")
+		}
+		up := filepath.Dir(current)
+		if current == up {
+			break
+		}
+		current = up
+	}
+	return nil
+}
+
+func CopyDir(src string, dest string) error {
+	err := checkPathNotContained(src, dest)
+	if err != nil {
+		return err
 	}
 
 	f, err := os.Open(src)

+ 18 - 0
pkg/cstest/utils_test.go

@@ -0,0 +1,18 @@
+package cstest
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestCheckPathNotContained(t *testing.T) {
+	assert.Nil(t, checkPathNotContained("/foo", "/bar"))
+	assert.Nil(t, checkPathNotContained("/foo/bar", "/foo"))
+	assert.Nil(t, checkPathNotContained("/foo/bar", "/"))
+	assert.Nil(t, checkPathNotContained("/path/to/somewhere", "/path/to/somewhere-else"))
+	assert.Nil(t, checkPathNotContained("~/.local/path/to/somewhere", "~/.local/path/to/somewhere-else"))
+	assert.NotNil(t, checkPathNotContained("/foo", "/foo/bar"))
+	assert.NotNil(t, checkPathNotContained("/", "/foo"))
+	assert.NotNil(t, checkPathNotContained("/", "/foo/bar/baz"))
+}