fix: allow access to '..' in mapfs (#7575)

Signed-off-by: nikpivkin <nikita.pivkin@smartforce.io>
This commit is contained in:
Nikita Pivkin
2024-09-27 08:03:46 +06:00
committed by GitHub
parent 13ef3e7d62
commit a8fbe46119
4 changed files with 31 additions and 4 deletions

View File

@@ -123,7 +123,7 @@ func (m *FS) CopyFilesUnder(dir string) error {
// Stat returns a FileInfo describing the file.
func (m *FS) Stat(name string) (fs.FileInfo, error) {
if strings.HasPrefix(name, "../") && m.underlyingRoot != "" {
if m.isPathAboveRoot(name) {
return os.Stat(filepath.Join(m.underlyingRoot, name))
}
@@ -145,7 +145,7 @@ func (m *FS) Stat(name string) (fs.FileInfo, error) {
// ReadDir reads the named directory
// and returns a list of directory entries sorted by filename.
func (m *FS) ReadDir(name string) ([]fs.DirEntry, error) {
if strings.HasPrefix(name, "../") && m.underlyingRoot != "" {
if m.isPathAboveRoot(name) {
return os.ReadDir(filepath.Join(m.underlyingRoot, name))
}
return m.root.ReadDir(cleanPath(name))
@@ -153,7 +153,7 @@ func (m *FS) ReadDir(name string) ([]fs.DirEntry, error) {
// Open opens the named file for reading.
func (m *FS) Open(name string) (fs.File, error) {
if strings.HasPrefix(name, "../") && m.underlyingRoot != "" {
if m.isPathAboveRoot(name) {
return os.Open(filepath.Join(m.underlyingRoot, name))
}
return m.root.Open(cleanPath(name))
@@ -188,7 +188,7 @@ func (m *FS) MkdirAll(path string, perm fs.FileMode) error {
// The caller is permitted to modify the returned byte slice.
// This method should return a copy of the underlying data.
func (m *FS) ReadFile(name string) ([]byte, error) {
if strings.HasPrefix(name, "../") && m.underlyingRoot != "" {
if m.isPathAboveRoot(name) {
return os.ReadFile(filepath.Join(m.underlyingRoot, name))
}
@@ -245,3 +245,7 @@ func cleanPath(path string) string {
path = strings.TrimLeft(path, "/") // Remove the leading slash
return path
}
func (m *FS) isPathAboveRoot(name string) bool {
return (name == ".." || strings.HasPrefix(name, "../")) && m.underlyingRoot != ""
}

View File

@@ -478,3 +478,26 @@ func TestFS_RemoveAll(t *testing.T) {
require.ErrorIs(t, err, fs.ErrNotExist)
})
}
func TestFS_WithUnderlyingRoot(t *testing.T) {
root := "testdata/subdir"
fsys := mapfs.New(mapfs.WithUnderlyingRoot(root))
require.NoError(t, fsys.WriteFile("foo.txt", root+"/foo.txt"))
require.NoError(t, fsys.WriteFile("..foo.txt", root+"/..foo.txt"))
fi, err := fsys.Stat("..")
require.NoError(t, err)
assert.True(t, fi.IsDir())
fi, err = fsys.Stat("../hello.txt")
require.NoError(t, err)
assert.False(t, fi.IsDir())
fi, err = fsys.Stat("foo.txt")
require.NoError(t, err)
assert.False(t, fi.IsDir())
fi, err = fsys.Stat("..foo.txt")
require.NoError(t, err)
assert.False(t, fi.IsDir())
}

0
pkg/mapfs/testdata/subdir/..foo.txt vendored Normal file
View File

0
pkg/mapfs/testdata/subdir/foo.txt vendored Normal file
View File