From 68729904b4e361b585404cd977cde79dc0205245 Mon Sep 17 00:00:00 2001 From: Ronald G Minnich Date: Tue, 16 Apr 2024 15:24:32 -0700 Subject: [PATCH] boundos:insideBaseDirEval: return true if baseDir is "/" 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 --- osfs/os_bound.go | 6 +++++- osfs/os_bound_test.go | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/osfs/os_bound.go b/osfs/os_bound.go index b4b6dbc..c0a6109 100644 --- a/osfs/os_bound.go +++ b/osfs/os_bound.go @@ -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) @@ -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("%q: path outside base dir %q: %w", filename, fs.baseDir, os.ErrNotExist) } return true, nil } diff --git a/osfs/os_bound_test.go b/osfs/os_bound_test.go index e9e1a0b..ed446a6 100644 --- a/osfs/os_bound_test.go +++ b/osfs/os_bound_test.go @@ -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()