diff --git a/core/zk/zk.go b/core/zk/zk.go index 887a135..5fb02fb 100644 --- a/core/zk/zk.go +++ b/core/zk/zk.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "os" "path/filepath" + "strings" "github.com/mickael-menu/zk/util/errors" "github.com/mickael-menu/zk/util/paths" @@ -254,10 +255,10 @@ func (zk *Zk) DBPath() string { } // RelPath returns the path relative to the notebook root to the given path. -func (zk *Zk) RelPath(path string) (string, error) { - wrap := errors.Wrapperf("%v: not a valid notebook path", path) +func (zk *Zk) RelPath(absPath string) (string, error) { + wrap := errors.Wrapperf("%v: not a valid notebook path", absPath) - path, err := filepath.Abs(path) + path, err := filepath.Abs(absPath) if err != nil { return path, wrap(err) } @@ -265,6 +266,9 @@ func (zk *Zk) RelPath(path string) (string, error) { if err != nil { return path, wrap(err) } + if strings.HasPrefix(path, "..") { + return path, fmt.Errorf("%s: path is outside the notebook", absPath) + } if path == "." { path = "" } diff --git a/core/zk/zk_test.go b/core/zk/zk_test.go index 7c46f7b..bd555f1 100644 --- a/core/zk/zk_test.go +++ b/core/zk/zk_test.go @@ -68,6 +68,20 @@ func TestDirAtGivenPath(t *testing.T) { } } +func TestDirAtOutsideNotebook(t *testing.T) { + wd, _ := os.Getwd() + zk := &Zk{Path: wd} + + for _, path := range []string{ + "..", + "../..", + "/tmp", + } { + _, err := zk.DirAt(path) + assert.Err(t, err, "path is outside the notebook") + } +} + // When requesting the root directory `.`, the config is the default one. func TestDirAtRoot(t *testing.T) { wd, _ := os.Getwd() @@ -167,8 +181,9 @@ func TestDirAtFindsGroup(t *testing.T) { // Modifying the GroupConfig of the returned Dir should not modify the global config. func TestDirAtReturnsClonedConfig(t *testing.T) { + wd, _ := os.Getwd() zk := Zk{ - Path: "/test", + Path: wd, Config: Config{ Note: NoteConfig{ FilenameTemplate: "{{id}}.note", @@ -213,8 +228,9 @@ func TestDirAtReturnsClonedConfig(t *testing.T) { } func TestDirAtWithOverrides(t *testing.T) { + wd, _ := os.Getwd() zk := Zk{ - Path: "/test", + Path: wd, Config: Config{ Note: NoteConfig{ FilenameTemplate: "{{id}}.note",