Prevent creating notes outside the current notebook

pull/6/head
Mickaël Menu 3 years ago
parent 5968547381
commit e1c56c398d
No known key found for this signature in database
GPG Key ID: 53D73664CD359895

@ -5,6 +5,7 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"github.com/mickael-menu/zk/util/errors" "github.com/mickael-menu/zk/util/errors"
"github.com/mickael-menu/zk/util/paths" "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. // RelPath returns the path relative to the notebook root to the given path.
func (zk *Zk) RelPath(path string) (string, error) { func (zk *Zk) RelPath(absPath string) (string, error) {
wrap := errors.Wrapperf("%v: not a valid notebook path", path) wrap := errors.Wrapperf("%v: not a valid notebook path", absPath)
path, err := filepath.Abs(path) path, err := filepath.Abs(absPath)
if err != nil { if err != nil {
return path, wrap(err) return path, wrap(err)
} }
@ -265,6 +266,9 @@ func (zk *Zk) RelPath(path string) (string, error) {
if err != nil { if err != nil {
return path, wrap(err) return path, wrap(err)
} }
if strings.HasPrefix(path, "..") {
return path, fmt.Errorf("%s: path is outside the notebook", absPath)
}
if path == "." { if path == "." {
path = "" path = ""
} }

@ -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. // When requesting the root directory `.`, the config is the default one.
func TestDirAtRoot(t *testing.T) { func TestDirAtRoot(t *testing.T) {
wd, _ := os.Getwd() 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. // Modifying the GroupConfig of the returned Dir should not modify the global config.
func TestDirAtReturnsClonedConfig(t *testing.T) { func TestDirAtReturnsClonedConfig(t *testing.T) {
wd, _ := os.Getwd()
zk := Zk{ zk := Zk{
Path: "/test", Path: wd,
Config: Config{ Config: Config{
Note: NoteConfig{ Note: NoteConfig{
FilenameTemplate: "{{id}}.note", FilenameTemplate: "{{id}}.note",
@ -213,8 +228,9 @@ func TestDirAtReturnsClonedConfig(t *testing.T) {
} }
func TestDirAtWithOverrides(t *testing.T) { func TestDirAtWithOverrides(t *testing.T) {
wd, _ := os.Getwd()
zk := Zk{ zk := Zk{
Path: "/test", Path: wd,
Config: Config{ Config: Config{
Note: NoteConfig{ Note: NoteConfig{
FilenameTemplate: "{{id}}.note", FilenameTemplate: "{{id}}.note",

Loading…
Cancel
Save