Skip to content

Commit

Permalink
boundos:insideBaseDirEval: return true if baseDir is "/"
Browse files Browse the repository at this point in the history
insideBaseDirEval would fail if baseDir was "/".
Since "/" contains anything, and can never be a symlink,
just return true, nil if baseDir is "/".

Add a simple test for this case.

Also, while we are at it, have the returned error be a lot more
informative: show the name and the base diectory; further, have it
wrap os.ErrNotExist should anyone wish to use errors.Is at some
point.

Signed-off-by: Ronald G Minnich <rminnich@gmail.com>
  • Loading branch information
rminnich committed Apr 27, 2024
1 parent 72e8966 commit 0f777a6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
6 changes: 5 additions & 1 deletion osfs/os_bound.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,10 @@ func (fs *BoundOS) insideBaseDir(filename string) (bool, error) {
// a dir that is within the fs.baseDir, by first evaluating any symlinks
// that either filename or fs.baseDir may contain.
func (fs *BoundOS) insideBaseDirEval(filename string) (bool, error) {
// "/" contains all others.
if fs.baseDir == "/" {
return true, nil
}
dir, err := filepath.EvalSymlinks(filepath.Dir(filename))
if dir == "" || os.IsNotExist(err) {
dir = filepath.Dir(filename)
Expand All @@ -255,7 +259,7 @@ func (fs *BoundOS) insideBaseDirEval(filename string) (bool, error) {
wd = fs.baseDir
}
if filename != wd && dir != wd && !strings.HasPrefix(dir, wd+string(filepath.Separator)) {
return false, fmt.Errorf("path outside base dir")
return false, fmt.Errorf("path %q outside base dir %q: %w", filename, fs.baseDir, os.ErrNotExist)
}
return true, nil
}
8 changes: 8 additions & 0 deletions osfs/os_bound_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,14 @@ func TestReadDir(t *testing.T) {
g.Expect(dirs).To(gomega.BeNil())
}

func TestInsideBaseDirEval(t*testing.T) {
g := gomega.NewWithT(t)
fs := BoundOS{baseDir: "/"}
b, err := fs.insideBaseDirEval("a")
g.Expect(b).To(gomega.BeTrue())
g.Expect(err).To(gomega.BeNil())
}

func TestMkdirAll(t *testing.T) {
g := gomega.NewWithT(t)
root := t.TempDir()
Expand Down

0 comments on commit 0f777a6

Please sign in to comment.